-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathdp_battery_algorithm.py
More file actions
2483 lines (2239 loc) · 108 KB
/
Copy pathdp_battery_algorithm.py
File metadata and controls
2483 lines (2239 loc) · 108 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Dynamic Programming Algorithm for Battery Energy Storage System (BESS) Optimization.
This module implements a sophisticated dynamic programming approach to optimize battery
dispatch decisions over a 24-hour horizon, considering time-varying electricity prices,
solar production forecasts, and home consumption patterns.
UPDATED: Now captures strategic intent at decision time rather than analyzing flows afterward.
ALGORITHM OVERVIEW:
The optimization uses backward induction dynamic programming to find the globally optimal
battery charging and discharging schedule. At each hour, the algorithm evaluates all
possible battery actions (charge/discharge/hold) and selects the one that minimizes
total cost over the remaining time horizon.
KEY FEATURES:
- 24-hour optimization horizon with perfect foresight
- Cost basis tracking for stored energy (FIFO accounting)
- Multi-objective optimization: cost minimization + battery longevity
- Simultaneous energy flow optimization across multiple sources/destinations
- Strategic intent capture at decision time for transparency and hardware control
STRATEGIC INTENT CAPTURE:
The algorithm now captures the strategic reasoning behind each decision:
- GRID_CHARGING: Storing cheap grid energy for arbitrage
- SOLAR_STORAGE: Storing excess solar for later use
- LOAD_SUPPORT: Discharging to meet home load
- BATTERY_EXPORT: Discharging to grid for profit
- IDLE: No significant activity
ENERGY FLOW MODELING:
The algorithm models complex energy flows where multiple sources can serve multiple
destinations simultaneously:
- Solar → {Home, Battery, Grid Export}
- Battery → {Home, Grid Export}
- Grid → {Home, Battery Charging}
OPTIMIZATION OBJECTIVES:
1. Primary: Minimize total electricity costs over 24-hour period
2. Secondary: Minimize battery degradation through cycle cost modeling
3. Constraints: Physical battery limits, efficiency losses, minimum SOC
RETURN STRUCTURE:
The algorithm returns comprehensive results including:
- Optimal battery actions for each hour
- Strategic intent for each decision
- Detailed energy flow breakdowns showing where each kWh flows
- Economic analysis comparing different scenarios
- All data needed for hardware implementation and performance analysis
"""
__all__ = [
"optimize_battery_schedule",
"print_optimization_results",
]
import logging
from dataclasses import dataclass
from enum import Enum
import numpy as np
from core.bess.dp_constants import (
POWER_STEP_KW,
SOE_STEP_KWH,
)
from core.bess.execution_model import (
DEFAULT_CAPABILITIES,
PlatformCapabilities,
lattice_grid_charge,
)
from core.bess.models import (
EconomicData,
EconomicSummary,
EnergyData,
OptimizationResult,
PeriodData,
apply_export_curtailment_to_period_data,
)
from core.bess.settings import BatterySettings, HomeSettings
from core.bess.strategic_intent import (
create_decision_data,
)
# Configure logging
logging.basicConfig(
level=logging.DEBUG, format="%(asctime)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)
# Algorithm parameters. SOE_STEP_KWH/POWER_STEP_KW live in dp_constants.py
# (shared with strategic_intent.py -- see that module's docstring for why).
POWER_TOLERANCE_KW = 0.001 # Threshold to distinguish IDLE from charge/discharge
class StrategicIntent(Enum):
"""Strategic intents for battery actions, determined at decision time."""
# Primary intents (mutually exclusive)
GRID_CHARGING = "GRID_CHARGING" # Storing cheap grid energy for arbitrage
SOLAR_STORAGE = "SOLAR_STORAGE" # Storing excess solar for later use
LOAD_SUPPORT = "LOAD_SUPPORT" # Discharging to meet home load
BATTERY_EXPORT = "BATTERY_EXPORT" # Discharging battery to grid for profit
SOLAR_EXPORT = "SOLAR_EXPORT" # Solar surplus exporting to grid, battery idle
IDLE = "IDLE" # No significant action
def _discretize_state_action_space(
battery_settings: BatterySettings,
) -> tuple[np.ndarray, np.ndarray]:
"""Discretize state and action spaces - FIXED to return SOE levels."""
# State space: State of Energy (kWh)
soe_levels = np.arange(
battery_settings.min_soe_kwh,
battery_settings.max_soe_kwh + SOE_STEP_KWH,
SOE_STEP_KWH,
)
# Action space: power levels (kW)
max_power = max(
battery_settings.max_charge_power_kw, battery_settings.max_discharge_power_kw
)
power_levels = np.arange(
-max_power,
max_power + POWER_STEP_KW,
POWER_STEP_KW,
)
# Guarantee IDLE (power=0) is an available action. The arange above is
# offset so it never lands exactly on zero, and under the #146 binary-store
# semantics ("any positive power charges at max rate") the smallest positive
# grid power is a full-rate grid charge — not a hold. Without an explicit
# IDLE action the value iteration cannot represent holding the battery, so
# the always-achievable IDLE floor (V[t,i] >= idle_reward + V[t+1,i]) is
# unreachable and V collapses below it.
if not np.any(np.abs(power_levels) <= POWER_TOLERANCE_KW):
power_levels = np.sort(np.append(power_levels, 0.0))
return soe_levels, power_levels
def _idle_battery_flows(
soe: float,
next_soe: float,
battery_settings: BatterySettings,
) -> tuple[float, float]:
"""Derive battery_charged/battery_discharged for an IDLE period.
During IDLE, excess solar passively charges the battery. The SOE delta
(computed by _state_transition) is already efficiency-adjusted, so we
reverse the efficiency to get the solar throughput consumed.
Returns:
(battery_charged, battery_discharged) in kWh throughput.
"""
# No below-floor special case needed: _soe_floor (#233) only clamps next_soe
# up to min_soe_kwh when soe already started at/above it -- when soe is
# below the floor, the floor is soe itself, so a zero-solar period already
# yields next_soe == soe (delta 0) without help from this function. Below
# the floor with real solar, the delta is genuine stored energy and must
# be credited the same as any other IDLE period (#269).
passive_energy_stored = next_soe - soe
battery_charged = (
passive_energy_stored / battery_settings.efficiency_charge
if passive_energy_stored > 0
else 0.0
)
return battery_charged, 0.0
def _soe_floor(soe: float, battery_settings: BatterySettings) -> float:
"""The feasible/reportable SOE floor for a period that *started* at
`soe`: `min_soe_kwh` if the period started at/above it, otherwise `soe`
itself. Recovering from a below-floor start (e.g. a live sensor reading
under Min SOC in demo mode, see #233) must never fabricate a jump to
the floor with zero real energy stored."""
return battery_settings.min_soe_kwh if soe >= battery_settings.min_soe_kwh else soe
def _effective_ac_cap_kwh(battery_settings: BatterySettings, dt: float) -> float | None:
"""Per-period AC-output energy cap (kWh), or None when the feature is off.
Models a hybrid inverter whose total AC output (PV DC→AC conversion plus
battery discharge) is capped, while DC-coupled PV can charge the battery
above the cap. The margin is a model-side haircut only — it compensates
for hourly forecasts flattening sub-period peaks — and is never written
to hardware.
"""
if battery_settings.inverter_max_ac_power_kw <= 0.0:
return None
return (
battery_settings.inverter_max_ac_power_kw
* (1.0 - battery_settings.inverter_ac_power_margin)
* dt
)
def _effective_import_cap_kwh(
home_settings: HomeSettings | None, dt: float
) -> float | None:
"""Per-period grid-import energy cap (kWh) derived from the house's fuse
service limit, or None when power monitoring is disabled (issue #429).
Multiplied by `phase_count`: each phase is an independent fuse, so a
balanced 3-phase house can import up to `phase_count` times a single
phase's ceiling before any individual phase is stressed. `HomePowerMonitor`
(`core/bess/power_monitor.py`) already relies on this same assumption at
runtime -- on a fully unloaded 3-phase house it authorizes the battery up
to its full `max_charge_power_w` (not a single phase's worth), since
`available_pct` is computed relative to `max_charge_power_w / phase_count`
per phase. `HomePowerMonitor` remains the real-time backstop against
unbalanced loads (it measures actual per-phase current and throttles
battery charging against the single worst-loaded phase, commit 37201cb9,
#11); the DP has no per-phase forecast to reproduce that live check, so it
caps against the balanced-load assumption instead of the unbalanced
worst case.
"""
if home_settings is None or not home_settings.power_monitoring_enabled:
return None
return (
home_settings.voltage
* home_settings.max_fuse_current
* home_settings.safety_margin
* home_settings.phase_count
/ 1000.0
) * dt
def _ac_flows(
solar_production: float,
home_consumption: float,
solar_to_battery: float,
battery_discharged: float,
ac_cap_kwh: float | None,
) -> tuple[float, float, float]:
"""AC-side grid flows for one period, shared by every disposition.
Solar not stored DC-side must pass through the inverter's AC stage; with a
cap, anything above it is clipped (lost, zero credit). Battery discharge
shares the same AC stage — callers must pre-limit discharge to the cap
headroom (`ac_cap_kwh - min(solar, ac_cap_kwh)`).
Returns (grid_imported, grid_exported, clipped_solar) in kWh.
"""
residual_solar = solar_production - solar_to_battery
if ac_cap_kwh is None:
ac_solar = residual_solar
else:
ac_solar = min(residual_solar, ac_cap_kwh)
clipped_solar = residual_solar - ac_solar
ac_output = ac_solar + battery_discharged
home_served = min(ac_output, home_consumption)
grid_exported = ac_output - home_served
grid_imported = home_consumption - home_served
return grid_imported, grid_exported, clipped_solar
def _ac_flows_grid(
solar_to_battery: np.ndarray,
battery_discharged: np.ndarray | float,
solar_production: float,
home_consumption: float,
ac_cap_kwh: float | None,
) -> tuple[np.ndarray, np.ndarray]:
"""np mirror of `_ac_flows` — same formulas, broadcast-friendly.
Returns (grid_imported, grid_exported), omitting `clipped_solar` (unused
by any vectorized caller so far).
"""
residual_solar = solar_production - solar_to_battery
if ac_cap_kwh is None:
ac_solar = residual_solar
else:
ac_solar = np.minimum(residual_solar, ac_cap_kwh)
ac_output = ac_solar + battery_discharged
home_served = np.minimum(ac_output, home_consumption)
return home_consumption - home_served, ac_output - home_served
@dataclass(frozen=True)
class PeriodFlows:
"""Every physical energy flow one candidate action produces in one period
(kWh) -- the single flow record principle P4 requires
(`docs/agents/optimizer-architecture.md`).
Flows only. **No prices and no costs belong on this record**, deliberately:
the DP's objective is evaluated at the #269 floored `reward_sell_price`
while the reported `PeriodData` is priced at the real `sell_price`, so a
single costed record would collapse a distinction the optimizer depends
on. The record says what moved; each consumer prices it.
`energy_stored` is the charge-throughput basis `(solar_to_battery +
grid_to_battery) * efficiency_charge` -- the quantity the reward's wear
term is charged on. `_build_period_data` deliberately keeps charging wear
on the SoE-delta basis `max(0, next_soe - soe)` instead: the two are
algebraically identical but take different float paths, and the reported
economics are pinned bit-identically against goldens computed on the
SoE-delta form.
"""
solar_to_battery: float
grid_to_battery: float
battery_charged: float
battery_discharged: float
grid_imported: float
grid_exported: float
clipped_solar: float
energy_stored: float
def _period_flows(
power: float,
soe: float,
next_soe: float,
home_consumption: float,
solar_production: float,
battery_settings: BatterySettings,
dt: float,
import_cap_kwh: float | None = None,
) -> PeriodFlows:
"""Derive one candidate action's complete flow set -- the only place a
planned period's *reported and priced* flows are computed.
Not the only place the charge split appears, and the difference matters
if you are about to edit it: `_state_transition` carries its own copy to
produce `next_soe`, and the two numpy mirrors (`_state_transition_grid`,
`_compute_reward_grid`) carry vectorized copies that P1(a) permits the
backward passes. A change to the split here must be made there too, or
reported `battery_soe_end` will stop agreeing with reported
`battery_charged`.
Before Phase 3 this arithmetic existed three MORE times over
(`_compute_reward`, `_build_period_data`, `_create_idle_schedule`), which
is the reward-vs-flows divergence class P4 forbids: an edit to the reward
side that did not reach the reporting side produced periods whose priced
energy and reported energy disagreed (#497/#459).
The term order and the in-place `grid_imported += grid_to_battery` are
load-bearing, not stylistic. 56 of the corpus's 2194 selections are
decided by a value gap under 1e-12 between candidates with different
recorded actions (measured 2026-08-10), so re-associating this arithmetic
-- "compute once, then multiply out" -- moves ULPs and flips them.
The AC cap is derived here rather than accepted as an argument, and
`_price_flows` derives it the same way. It used to be a parameter, which
meant a caller could produce flows under one cap and have them priced
under another -- the reward-vs-flows divergence class P4 exists to
remove, merely relocated from the physics to its inputs. Every caller
passed `_effective_ac_cap_kwh(battery_settings, dt)` anyway, so there was
nothing to express and something to get wrong.
"""
ac_cap_kwh = _effective_ac_cap_kwh(battery_settings, dt)
if power > POWER_TOLERANCE_KW: # STORE disposition (+ optional grid charge)
surplus = max(0.0, solar_production - home_consumption)
room_throughput = (
battery_settings.max_soe_kwh - soe
) / battery_settings.efficiency_charge
rate_throughput = battery_settings.max_charge_power_kw * dt
solar_to_battery = min(surplus, rate_throughput, room_throughput)
remaining_rate = max(
0.0, min(rate_throughput, room_throughput) - solar_to_battery
)
grid_to_battery = remaining_rate # solar fills first, grid tops up the rest
# genuine excess solar (above rate/room) is exported; deliberate grid
# top-up imported
grid_imported, grid_exported, clipped_solar = _ac_flows(
solar_production, home_consumption, solar_to_battery, 0.0, ac_cap_kwh
)
if import_cap_kwh is not None:
# Grid charging must not push total import (load + charging) over
# the house fuse's import cap (#429) -- throttle the grid-charge
# component to whatever headroom the load leaves.
grid_to_battery = min(
grid_to_battery, max(0.0, import_cap_kwh - grid_imported)
)
# Only under the cap: with the cap binding, nothing physical
# stops the command overshooting, so the plan must come down to
# the lattice instead (4c).
grid_to_battery = float(
lattice_grid_charge(
solar_to_battery,
grid_to_battery,
battery_settings.max_charge_power_kw / 100 * dt,
)
)
energy_stored = (
solar_to_battery + grid_to_battery
) * battery_settings.efficiency_charge
grid_imported += grid_to_battery
return PeriodFlows(
solar_to_battery=solar_to_battery,
grid_to_battery=grid_to_battery,
battery_charged=solar_to_battery + grid_to_battery,
battery_discharged=0.0,
grid_imported=grid_imported,
grid_exported=grid_exported,
clipped_solar=clipped_solar,
energy_stored=energy_stored,
)
if power < -POWER_TOLERANCE_KW: # Discharging
battery_discharged = abs(power) * dt
grid_imported, grid_exported, clipped_solar = _ac_flows(
solar_production, home_consumption, 0.0, battery_discharged, ac_cap_kwh
)
return PeriodFlows(
solar_to_battery=0.0,
grid_to_battery=0.0,
battery_charged=0.0,
battery_discharged=battery_discharged,
grid_imported=grid_imported,
grid_exported=grid_exported,
clipped_solar=clipped_solar,
energy_stored=0.0,
)
# IDLE -- passive solar charging; the battery never discharges here
# (`_idle_battery_flows` returns 0.0 for it by construction).
battery_charged, battery_discharged = _idle_battery_flows(
soe, next_soe, battery_settings
)
grid_imported, grid_exported, clipped_solar = _ac_flows(
solar_production,
home_consumption,
battery_charged,
battery_discharged,
ac_cap_kwh,
)
return PeriodFlows(
solar_to_battery=battery_charged,
grid_to_battery=0.0,
battery_charged=battery_charged,
battery_discharged=battery_discharged,
grid_imported=grid_imported,
grid_exported=grid_exported,
clipped_solar=clipped_solar,
energy_stored=next_soe - soe,
)
def _state_transition(
soe: float,
power: float,
battery_settings: BatterySettings,
dt: float,
solar_production: float,
home_consumption: float,
ac_cap_kwh: float | None = None,
import_cap_kwh: float | None = None,
) -> float:
"""
Calculate the next state of energy based on current SOE and power action.
EFFICIENCY HANDLING:
- Charging: power x dt x efficiency = energy actually stored
- Discharging: power x dt / efficiency = energy removed from storage
This ensures that efficiency losses are properly accounted for in energy balance.
PASSIVE SOLAR CHARGING (IDLE):
When power=0, excess solar (production - consumption) passively charges the
battery up to capacity, clamped by the inverter's max charge rate. This models
the economically correct baseline: free solar energy is more valuable stored
for later use than exported at the (typically lower) sell price.
`ac_cap_kwh` is a live footgun and callers should pass
`_effective_ac_cap_kwh(battery_settings, dt)` rather than omitting it. It is
read only inside the `import_cap_kwh` branch, to throttle grid charging
against the house fuse (#429), so a caller that passes an import cap while
omitting this one computes `next_soe` under a different inverter limit than
`_period_flows` derives for the very same action -- the reward-vs-flows
divergence P4 exists to remove.
It cannot be asserted away, which is the trap: `_effective_ac_cap_kwh`
returns None for a battery with no AC cap configured, so None is a
legitimate value here and is indistinguishable from a forgotten argument.
The real remedy is to derive the cap inside this function, as
`_period_flows` and `_price_flows` now do -- deferred rather than done here
only because this is the bit-parity-pinned physics core the migration plan
says to refactor around. Today `select_action` is the only caller passing an
import cap and it passes the derived value, so nothing is presently wrong.
"""
if power > POWER_TOLERANCE_KW: # STORE disposition (+ optional grid charge)
surplus = max(0.0, solar_production - home_consumption)
room_throughput = (
battery_settings.max_soe_kwh - soe
) / battery_settings.efficiency_charge
rate_throughput = battery_settings.max_charge_power_kw * dt
solar_to_battery = min(surplus, rate_throughput, room_throughput)
remaining_rate = max(
0.0, min(rate_throughput, room_throughput) - solar_to_battery
)
grid_to_battery = remaining_rate # solar fills first, grid tops up the rest
if import_cap_kwh is not None:
# Grid charging must not push total import (load + charging)
# over the house fuse's import cap (#429) -- throttle the
# grid-charge component to whatever headroom the load leaves.
load_import, _, _ = _ac_flows(
solar_production, home_consumption, solar_to_battery, 0.0, ac_cap_kwh
)
grid_to_battery = min(
grid_to_battery, max(0.0, import_cap_kwh - load_import)
)
# Same quantization as the flow record, so the state transition
# and the flows agree on what was charged (4c).
grid_to_battery = float(
lattice_grid_charge(
solar_to_battery,
grid_to_battery,
battery_settings.max_charge_power_kw / 100 * dt,
)
)
charge_energy = (
solar_to_battery + grid_to_battery
) * battery_settings.efficiency_charge
next_soe = min(battery_settings.max_soe_kwh, soe + charge_energy)
elif power < -POWER_TOLERANCE_KW: # Discharging
# Energy removed from storage = power throughput ÷ discharging efficiency
discharge_energy = abs(power) * dt / battery_settings.efficiency_discharge
available_energy = soe - battery_settings.min_soe_kwh
actual_discharge = min(discharge_energy, available_energy)
next_soe = soe - actual_discharge
else: # IDLE — passive solar charging (mirrors load_first hardware behavior)
surplus = max(0.0, solar_production - home_consumption)
room_throughput = (
battery_settings.max_soe_kwh - soe
) / battery_settings.efficiency_charge
rate_throughput = battery_settings.max_charge_power_kw * dt
solar_to_battery = min(surplus, rate_throughput, room_throughput)
charge_energy = solar_to_battery * battery_settings.efficiency_charge
next_soe = min(battery_settings.max_soe_kwh, soe + charge_energy)
# Ensure SOE stays within physical bounds (see _soe_floor).
next_soe = min(
battery_settings.max_soe_kwh, max(_soe_floor(soe, battery_settings), next_soe)
)
return next_soe
def _state_transition_grid(
soe: np.ndarray,
power: np.ndarray,
battery_settings: BatterySettings,
dt: float,
solar_production: float,
home_consumption: float,
ac_cap_kwh: float | None = None,
import_cap_kwh: float | None = None,
) -> np.ndarray:
"""Vectorized form of `_state_transition` for the DP backward pass.
`soe` is a column vector (S, 1) of SoE levels and `power` is a row
vector (1, A) of candidate actions; the result broadcasts to (S, A).
Every arithmetic step mirrors `_state_transition` exactly (same
operations, same order) so results are bit-identical per cell -- this
is what lets `_run_dynamic_programming` vectorize without changing the
DP's numerics. See #236.
"""
max_soe = battery_settings.max_soe_kwh
min_soe = battery_settings.min_soe_kwh
eff_charge = battery_settings.efficiency_charge
eff_discharge = battery_settings.efficiency_discharge
surplus = max(0.0, solar_production - home_consumption)
rate_throughput = battery_settings.max_charge_power_kw * dt
# STORE disposition (power > TOL): binary physics -- next_soe does not
# depend on the exact positive power value, only on soe (see
# _build_period_data's "STORE physics are binary" note).
room_throughput = (max_soe - soe) / eff_charge
solar_to_battery = np.minimum(np.minimum(surplus, rate_throughput), room_throughput)
remaining_rate = np.maximum(
0.0, np.minimum(rate_throughput, room_throughput) - solar_to_battery
)
grid_to_battery = remaining_rate
if import_cap_kwh is not None:
load_import, _ = _ac_flows_grid(
solar_to_battery, 0.0, solar_production, home_consumption, ac_cap_kwh
)
grid_to_battery = np.minimum(
grid_to_battery, np.maximum(0.0, import_cap_kwh - load_import)
)
# Mirrors the replay's quantization so both passes value the same
# charge (4c) -- the one-action-set requirement on the charge side.
grid_to_battery = lattice_grid_charge(
solar_to_battery,
grid_to_battery,
battery_settings.max_charge_power_kw / 100 * dt,
)
store_charge_energy = (solar_to_battery + grid_to_battery) * eff_charge
store_next_soe = np.minimum(max_soe, soe + store_charge_energy)
# Discharging (power < -TOL)
discharge_energy = np.abs(power) * dt / eff_discharge
available_energy = soe - min_soe
actual_discharge = np.minimum(discharge_energy, available_energy)
discharge_next_soe = soe - actual_discharge
# IDLE -- passive solar charging only, no grid top-up
idle_charge_energy = solar_to_battery * eff_charge
idle_next_soe = np.minimum(max_soe, soe + idle_charge_energy)
next_soe = np.where(
power > POWER_TOLERANCE_KW,
store_next_soe,
np.where(power < -POWER_TOLERANCE_KW, discharge_next_soe, idle_next_soe),
)
# See _soe_floor's docstring (#233) -- only raise to the floor when soe
# started at/above it.
floor = np.where(soe >= min_soe, min_soe, soe)
next_soe = np.minimum(max_soe, np.maximum(floor, next_soe))
return next_soe
def _compute_reward_grid(
power: np.ndarray,
soe: np.ndarray,
next_soe: np.ndarray,
home_consumption: float,
battery_settings: BatterySettings,
dt: float,
current_buy_price: float,
current_sell_price: float,
solar_production: float,
import_cap_kwh: float | None = None,
) -> tuple[np.ndarray, np.ndarray]:
"""Vectorized form of `_compute_reward`'s reward calculation.
Only the reward (and, for the import-cap feasibility mask, total
grid_imported) is needed by the DP backward pass -- it discards
`new_cost_basis`, same simplification the caller already applies to the
scalar path (`reward, _ = _compute_reward(...)`). Formulas mirror
`_compute_reward` exactly, branch for branch, for numerical parity. See
#236.
Returns (reward, grid_imported).
"""
max_soe = battery_settings.max_soe_kwh
eff_charge = battery_settings.efficiency_charge
cycle_cost = battery_settings.cycle_cost_per_kwh
ac_cap_kwh = _effective_ac_cap_kwh(battery_settings, dt)
is_charge = power > POWER_TOLERANCE_KW
is_discharge = power < -POWER_TOLERANCE_KW
def ac_flows_grid(solar_to_battery, battery_discharged):
return _ac_flows_grid(
solar_to_battery,
battery_discharged,
solar_production,
home_consumption,
ac_cap_kwh,
)
# Idle passive-absorption flows. No below-floor special case needed --
# see _idle_battery_flows's docstring (#269): the delta is already zero
# below the floor when there's no real solar, and genuine when there is.
passive_energy_stored = next_soe - soe
idle_battery_charged = np.where(
passive_energy_stored > 0,
passive_energy_stored / eff_charge,
0.0,
)
battery_discharged_active = np.abs(power) * dt
# STORE disposition reward (mirrors the early-return branch in
# _compute_reward, which redefines grid_imported/grid_exported locally)
surplus = max(0.0, solar_production - home_consumption)
rate_throughput = battery_settings.max_charge_power_kw * dt
room_throughput = (max_soe - soe) / eff_charge
solar_to_battery = np.minimum(np.minimum(surplus, rate_throughput), room_throughput)
remaining_rate = np.maximum(
0.0, np.minimum(rate_throughput, room_throughput) - solar_to_battery
)
grid_to_battery = remaining_rate
grid_imported_store, grid_exported_store = ac_flows_grid(solar_to_battery, 0.0)
if import_cap_kwh is not None:
# Grid charging must not push total import (load + charging) over
# the house fuse's import cap (#429).
grid_to_battery = np.minimum(
grid_to_battery, np.maximum(0.0, import_cap_kwh - grid_imported_store)
)
# Same quantization as the other three sites (4c).
grid_to_battery = lattice_grid_charge(
solar_to_battery,
grid_to_battery,
battery_settings.max_charge_power_kw / 100 * dt,
)
energy_stored_store = (solar_to_battery + grid_to_battery) * eff_charge
battery_wear_cost_store = energy_stored_store * cycle_cost
grid_imported_store = grid_imported_store + grid_to_battery
total_cost_store = (
grid_imported_store * current_buy_price
- grid_exported_store * current_sell_price
+ battery_wear_cost_store
)
reward_store = -total_cost_store
# Discharging reward. No self-throttle correction (#240): where actions
# are actually chosen, sub-resolution overshoots never reach this code
# (_discharge_candidates and the PWL mask exclude them), so any action
# taken has grid_exported that is zero or a genuine, measurable export.
# The coarse backward pass does still price in-band grid points here --
# intentionally, as a value-approximation proxy; see the comment at its
# feasibility mask in _run_dynamic_programming.
grid_imported_d, grid_exported_discharge = ac_flows_grid(
0.0, battery_discharged_active
)
total_cost_discharge = (
grid_imported_d * current_buy_price
- grid_exported_discharge * current_sell_price
)
reward_discharge = -total_cost_discharge
# IDLE reward
grid_imported_idle, grid_exported_idle = ac_flows_grid(idle_battery_charged, 0.0)
energy_stored_idle = next_soe - soe
battery_wear_cost_idle = energy_stored_idle * cycle_cost
total_cost_idle = (
grid_imported_idle * current_buy_price
- grid_exported_idle * current_sell_price
+ battery_wear_cost_idle
)
reward_idle = -total_cost_idle
reward = np.where(
is_charge, reward_store, np.where(is_discharge, reward_discharge, reward_idle)
)
grid_imported = np.where(
is_charge,
grid_imported_store,
np.where(is_discharge, grid_imported_d, grid_imported_idle),
)
return reward, grid_imported
def _compute_reward(
power: float,
soe: float,
next_soe: float,
period: int,
home_consumption: float,
battery_settings: BatterySettings,
dt: float,
buy_price: list[float],
sell_price: list[float],
solar_production: float,
cost_basis: float,
import_cap_kwh: float | None = None,
) -> tuple[float, float, PeriodFlows]:
"""Hot-path reward computation — prices the period's `PeriodFlows` record.
CYCLE COST POLICY:
- Applied only to charging operations (not discharging)
- Applied to energy actually stored (after efficiency losses)
- Grid costs applied to energy throughput (what you draw from grid)
- Cost basis includes BOTH grid costs AND cycle costs for profitability analysis
DISCHARGE ACCOUNTING:
- No profitability veto: every physically valid discharge gets a finite
reward. IDLE, competing in the same max() during backward induction,
already makes the hold-vs-discharge call correctly via the
forward-looking value function -- a separate floor on top of that is
redundant at best (see docs/superpowers/specs/2026-07-06-dp-bellman-guardrail-removal-design.md).
- No self-throttle threshold (#240, superseded by #497): this function
credits whatever flows `_ac_flows` reports, threshold-free. Discharges
whose overshoot is below the export resolution are excluded from the
action set outright (`_discharge_is_unexecutable`), never priced here.
Returns:
(reward, new_cost_basis, flows). The `PeriodFlows` record is exposed
so callers get this candidate's complete physical flows without
recomputing them -- the import-cap feasibility constraint (#429) and
the reported `PeriodData` both read it rather than re-deriving (P4).
"""
flows = _period_flows(
power=power,
soe=soe,
next_soe=next_soe,
home_consumption=home_consumption,
solar_production=solar_production,
battery_settings=battery_settings,
dt=dt,
import_cap_kwh=import_cap_kwh,
)
reward, new_cost_basis = _price_flows(
flows=flows,
power=power,
soe=soe,
next_soe=next_soe,
period=period,
home_consumption=home_consumption,
battery_settings=battery_settings,
dt=dt,
buy_price=buy_price,
sell_price=sell_price,
solar_production=solar_production,
cost_basis=cost_basis,
)
return reward, new_cost_basis, flows
def _price_flows(
flows: PeriodFlows,
power: float,
soe: float,
next_soe: float,
period: int,
home_consumption: float,
battery_settings: BatterySettings,
dt: float,
buy_price: list[float],
sell_price: list[float],
solar_production: float,
cost_basis: float,
) -> tuple[float, float]:
"""Price an already-derived `PeriodFlows` record: returns
`(reward, new_cost_basis)`.
Split from `_compute_reward` so the objective is demonstrably a function
*of the record* rather than of a second derivation of the physics (P4).
That is what lets `_replay_accounting_pass` price the stored records a
PWL splice produced instead of re-deriving flows from the spliced
trajectory -- where a caller passing a different `import_cap_kwh` than
the selection loop used would otherwise silently price a period the plan
never contained.
Takes no `import_cap_kwh`: the cap is a constraint on *flows*, already
applied inside `_period_flows`. Re-applying it here could only
disagree.
"""
current_buy_price = buy_price[period]
current_sell_price = sell_price[period]
ac_cap_kwh = _effective_ac_cap_kwh(battery_settings, dt)
grid_imported = flows.grid_imported
grid_exported = flows.grid_exported
# ============================================================================
# BATTERY CYCLE COST AND COST BASIS CALCULATION
# ============================================================================
new_cost_basis = cost_basis
if power > POWER_TOLERANCE_KW: # STORE disposition
solar_to_battery = flows.solar_to_battery
grid_to_battery = flows.grid_to_battery
energy_stored = flows.energy_stored
battery_wear_cost = energy_stored * battery_settings.cycle_cost_per_kwh
if ac_cap_kwh is None:
solar_opportunity_cost = solar_to_battery * current_sell_price
else:
# Storing solar only forgoes the export it actually displaces —
# absorbing energy that would have been clipped anyway is free.
_, export_without_storing, _ = _ac_flows(
solar_production, home_consumption, 0.0, 0.0, ac_cap_kwh
)
solar_opportunity_cost = (
export_without_storing - grid_exported
) * current_sell_price
grid_energy_cost = grid_to_battery * current_buy_price
total_new_cost = grid_energy_cost + solar_opportunity_cost + battery_wear_cost
if next_soe > battery_settings.min_soe_kwh:
existing_cost = soe * cost_basis
new_cost_basis = (existing_cost + total_new_cost) / next_soe
else:
new_cost_basis = (
(total_new_cost / energy_stored) if energy_stored > 0 else cost_basis
)
total_cost = (
grid_imported * current_buy_price
- grid_exported * current_sell_price
+ battery_wear_cost
)
return -total_cost, new_cost_basis
elif power < -POWER_TOLERANCE_KW: # Discharging
battery_wear_cost = 0.0
else: # IDLE — passive solar charging
battery_charged = flows.battery_charged
energy_stored = flows.energy_stored # kWh stored in battery after efficiency
battery_wear_cost = energy_stored * battery_settings.cycle_cost_per_kwh
if energy_stored > 0 and next_soe > battery_settings.min_soe_kwh:
if ac_cap_kwh is None:
solar_opportunity_cost = battery_charged * current_sell_price
else:
# Same clipping discount as the STORE branch: passively
# absorbing energy that would have been clipped anyway
# forgoes only the export it actually displaces.
_, export_without_absorbing, _ = _ac_flows(
solar_production, home_consumption, 0.0, 0.0, ac_cap_kwh
)
solar_opportunity_cost = (
export_without_absorbing - grid_exported
) * current_sell_price
new_cost_basis = (
soe * cost_basis + solar_opportunity_cost + battery_wear_cost
) / next_soe
# ============================================================================
# REWARD CALCULATION
# ============================================================================
total_cost = (
grid_imported * current_buy_price
- grid_exported * current_sell_price
+ battery_wear_cost
)
return -total_cost, new_cost_basis
def _record_marginal_value(
decision,
*,
V,
t: int,
soe: float,
battery_settings: BatterySettings,
buy_price_t: float,
) -> None:
"""Record dV/dSoE for this period and the discharge authorization it implies.
The shadow price is the value of the last kWh below this state, so it does
not exist at the bottom level -- and a SoE at or below the reserve floor
clamps there. Previously the assignment was simply skipped,
leaving `shadow_price` at its 0.0 default, which every consumer read as
"stored energy is worthless" and used to open the sub-period discharge
ceiling on a value that had never been computed (#526).
The authorization is decided here instead, where the value function is
owned. At the bottom level there is no removable kWh below this state, so
there is nothing to authorize and the decision stays False -- absence is
not permission. Both call sites route through this function so the grid
forward pass and the PWL-splice replay cannot drift onto different rules,
which is the mirrored-implementation bug class P1 exists to prevent.
The same argument applies to the *value estimate* itself, which is what
#571 fixed: this used to do its own index arithmetic, snapping to the
nearest grid point with `round()` while the policy walks the interpolant
(`_interpolate_value`, which floors). A state in the lower half of a cell
was therefore priced off the cell below -- a region of the value function
the battery is not in -- so the reported slope stepped mid-cell instead of
at cell boundaries, and the gate reads that number raw. It now reads the
interpolant like every other consumer.
"""
shadow_price = _value_slope_below(V[t], soe, battery_settings)
if shadow_price is None:
return
decision.shadow_price = shadow_price
decision.intra_period_discharge_allowed = bool(
buy_price_t * battery_settings.efficiency_discharge >= shadow_price
)
def _build_period_data(
flows: PeriodFlows,
power: float,
soe: float,
next_soe: float,
period: int,
home_consumption: float,
battery_settings: BatterySettings,
dt: float,
buy_price: list[float],
sell_price: list[float],
solar_production: float,
new_cost_basis: float,
currency: str,
continuation_value: float = 0.0,
export_curtailment_active: bool = False,
) -> PeriodData:
"""Build full PeriodData for the winning action of a DP cell.
`flows` is the record `_compute_reward` already produced for this same
action (P4): reporting prices exactly the energy the objective priced,
and there is no second derivation here that an edit to the reward side
could fail to reach. It is a required argument with no recomputing
fallback on purpose -- a default that re-derived the flows would be the
second construction site this phase exists to remove. `import_cap_kwh` is
likewise gone from the signature: the cap shapes `grid_to_battery` inside
`_period_flows`, so a reporting-side copy of that throttle could only
ever disagree with the priced one.
continuation_value: the DP's actual value-to-go from the resulting state
(_interpolate_value(V_next, next_soe, ...), the same term
_best_action_at_continuous_state adds to reward when choosing this
action) -- reported as decision.future_value. Defaults to 0.0 for any
caller that hasn't been updated to pass the real continuation value
(see issue #353).
export_curtailment_active: caller-computed, capability-aware curtailment
flag (see optimize_battery_schedule's docstring). Used only to derive