Suppose you operate a grid-scale battery or pumped-hydro reservoir at 17:00: wholesale power sells for right now, whereas tomorrow evening could either spike to if cloud cover stalls solar generation or stay moderate if wind inflows surge. Should you discharge now, hold, or charge? Forward greedy rules fail because every MWh discharged today changes the state-of-charge available tomorrow; brute-force scenario trees grow exponentially with horizon . Bellman’s (1952) principle of optimality (Mental Move #16, Induct Backward Under Future Uncertainty) solves the sequential problem backward from to . In this lecture, you will build and audit Stochastic Bellman DP (dynamic_optimality.stochastic_bellman_storage) across 24-hour duck-curve electricity markets, quantify the Expected Value of Perfect Information (EVPI), uncover why round-trip efficiency creates a wide no-trade price deadband (), and check the Banach contraction of infinite-horizon value iteration numerically.
Learning objectives¶
Formulate multi-stage sequential control under exogenous uncertainty via Bellman’s backward optimality equation, and expose why certainty-equivalent planning (‘Flaw of Averages’) misprices physical capacity bounds.
Compute optimal value tables and feedback control policies on 24-hour duck-curve markets using
dynamic_optimality.stochastic_bellman_storage.Quantify the Expected Value of Perfect Information () and derive the round-trip efficiency deadband threshold .
Verify Banach fixed-point contraction for infinite-horizon discounted MDPs and evaluate closed-loop Bellman policies via Monte Carlo simulation.
Time: about 60 min
try: # use the installed package, or the copy in this repository
import engthink
except ImportError:
import pathlib, subprocess, sys
for _root in [pathlib.Path.cwd(), *pathlib.Path.cwd().parents]:
if (_root / "engthink" / "__init__.py").exists():
sys.path.insert(0, str(_root))
break
else: # on Google Colab: install from GitHub
subprocess.run([sys.executable, "-m", "pip", "install", "-q",
"git+https://github.com/ktwyw/engthink.git"], check=True)
import engthink
import inspect
import math
import numpy as np
import matplotlib.pyplot as plt
from engthink import (constants_benchmarks, divide_spatial, dynamic_optimality, emergence_verification,
greedy_heuristic_search, information_streams, invariants_complexity, reductions_constraints,
representation_scaling)
from engthink.plotting import label_panels, log_ticks, panel_label, use_style
use_style()
def show_source(obj):
"""Return the source code of a library function or class."""
return inspect.getsource(obj)
def heading(text):
print(f"\n{text}\n" + "=" * len(text))1. Backward Induction Under Uncertainty & The Flaw of Averages¶
Consider a storage asset with state-of-charge , control action ( charges from the grid at cost adding to storage; withdraws from storage delivering to the grid at revenue ), and random renewable inflow :
Why must we induct backward from terminal value ? At , is already known for every state , so for each we immediately maximize immediate reward plus expected continuation value:
Notice why Certainty-Equivalent Planning—replacing random inflow with its mean —commits the Flaw of Averages: because clip(..., 0, S_max) and concave continuation values satisfy Jensen’s Inequality , deterministic mean-inflow planning ignores spillage risk at and systematically overestimates value.
heading("Demonstration 1: Stochastic backward induction against brute-force policy tree and flaw of averages")
mm16 = [m for m in constants_benchmarks.MENTAL_MOVES_DB if m["id"] == 16][0]
print(f"Mental Move #{mm16['id']} ({mm16['name']}): {mm16['invariant']}")
# 1. Exact verification on a 2-stage micro-benchmark against exhaustive contingent policy enumeration:
prices_2 = np.array([30.0, 95.0])
inf_scen = np.array([0.0, 20.0]) # Dry (0 MWh) vs. Stormy wind burst (+20 MWh), 50/50
inf_prob = np.array([0.5, 0.5])
sol_2 = dynamic_optimality.stochastic_bellman_storage(
prices_2, inf_scen, inf_prob, n_soc_states=21, max_capacity=40.0, max_rate=20.0, efficiency=0.90
)
# Exhaustively enumerate all feasible (a0, a1_if_dry, a1_if_wet) policies from s0 = 20 MWh on the discrete action grid:
acts_2 = np.linspace(-20.0, 20.0, 11)
s0_test = 20.0
idx_s0 = int(np.argmin(np.abs(sol_2["soc_grid"] - s0_test)))
def immediate_step(s: float, a: float, price: float, w: float, cap: float = 40.0, eta: float = 0.90) -> tuple[float, float]:
if a >= 0.0:
rew = -price * a
s_next = min(cap, max(0.0, s + eta * a + w))
else:
rew = price * eta * (-a)
s_next = min(cap, max(0.0, s + a + w))
return rew, s_next
best_brute = -np.inf
for a0 in acts_2:
if -a0 > s0_test + 1e-12:
continue
r0_d, s1_d = immediate_step(s0_test, float(a0), prices_2[0], inf_scen[0])
r0_w, s1_w = immediate_step(s0_test, float(a0), prices_2[0], inf_scen[1])
best_d = max(immediate_step(s1_d, float(a1), prices_2[1], 0.0)[0] for a1 in acts_2 if -a1 <= s1_d + 1e-12)
best_w = max(immediate_step(s1_w, float(a1), prices_2[1], 0.0)[0] for a1 in acts_2 if -a1 <= s1_w + 1e-12)
best_brute = max(best_brute, 0.5 * (r0_d + best_d) + 0.5 * (r0_w + best_w))
assert np.isclose(sol_2["value_table"][0, idx_s0], best_brute, atol=1e-10)
# 2. Demonstrate Jensen's Flaw of Averages near full capacity across 6 stages:
prices_6 = np.array([25.0, 30.0, 28.0, 40.0, 110.0, 130.0])
w_scen_6 = np.array([0.0, 35.0])
w_prob_6 = np.array([0.5, 0.5])
w_mean_6 = np.array([float(w_scen_6 @ w_prob_6)]) # Mean inflow = 17.5 MWh
sol_stoch = dynamic_optimality.stochastic_bellman_storage(
prices_6, w_scen_6, w_prob_6, n_soc_states=41, max_capacity=100.0, max_rate=25.0, efficiency=0.92
)
sol_mean_ce = dynamic_optimality.stochastic_bellman_storage(
prices_6, w_mean_6, np.array([1.0]), n_soc_states=41, max_capacity=100.0, max_rate=25.0, efficiency=0.92
)
# By Jensen's inequality on concave V_t(s), E[V] <= V(E[w]) everywhere:
gap_jensen = sol_mean_ce["value_table"][0, :] - sol_stoch["value_table"][0, :]
assert np.all(gap_jensen >= -1e-9) and float(np.max(gap_jensen)) > 400.0
print(f"2-Stage s0=20 MWh: Bellman DP = ${sol_2['value_table'][0, idx_s0]:.2f} vs. Exhaustive Policy Tree = ${best_brute:.2f}")
print(f"6-Stage Flaw of Averages max overestimation max_s [V_CE(s) - V_Bellman(s)] = +${np.max(gap_jensen):.2f} (spillage blindness)")
fig, ax = plt.subplots(figsize=(7.4, 4.0))
ax.plot(sol_stoch["soc_grid"], sol_mean_ce["value_table"][0, :], lw=2.1, ls="--", color="#C0392B", label=r"Certainty-equivalent $V_0^{\mathrm{CE}}(s)$ using $\mathbb{E}[W]$ (overoptimistic)")
ax.plot(sol_stoch["soc_grid"], sol_stoch["value_table"][0, :], lw=2.3, color="#2166AC", label=r"Exact stochastic Bellman $V_0^*(s)$")
ax.fill_between(sol_stoch["soc_grid"], sol_stoch["value_table"][0, :], sol_mean_ce["value_table"][0, :], color="#C0392B", alpha=0.14, label="Flaw-of-averages spillage illusion")
ax.set_xlabel("Initial state of charge $s_0$ [MWh]")
ax.set_ylabel("Expected 6-stage profit [USD]")
ax.set_title("Stochastic value against the certainty-equivalent plan")
ax.legend(fontsize=8.3)
plt.show()
Demonstration 1: Stochastic backward induction against brute-force policy tree and flaw of averages
===================================================================================================
Mental Move #16 (Induct Backward Under Future Uncertainty): V_t(s) = max_a {r(s,a) + E[V_{t+1}(s')]}
2-Stage s0=20 MWh: Bellman DP = $1710.00 vs. Exhaustive Policy Tree = $1710.00
6-Stage Flaw of Averages max overestimation max_s [V_CE(s) - V_Bellman(s)] = +$1123.46 (spillage blindness)

Figure 7.1. Expected six-stage profit against the initial state of charge. The certainty-equivalent plan (dashed), which replaces the random inflow by its mean, overestimates the stochastic Bellman value (solid) at every state, by up to 1,123 USD; the shaded gap comes from spillage that the mean inflow hides.
What Demonstration 1 shows. At high initial state-of-charge (), a deterministic planner using average inflow assumes all fits inside the tank (). In reality, half the time spills over the dam crest while the other half delivers . Over the six stages the certainty-equivalent value exceeds the stochastic Bellman value by up to USD (the largest difference over the initial states). The stochastic policy accounts for the spillage by discharging earlier to make room.
2. 24-Hour Duck-Curve Optimal Dispatch & Feedback Policy Maps¶
Modern solar-heavy power grids exhibit the duck curve: cheap midday wholesale prices (10:00–15:00) when rooftop PV floods the grid, a small morning shoulder (07:00–08:00), and a steep evening scarcity peak (18:00–21:00) as the sun sets just when residential load peaks. Notice what dynamic_optimality.stochastic_bellman_storage produces: not a single brittle open-loop schedule, but a complete state-feedback policy lookup table for every hour and every storage level.
heading("Demonstration 2: 24-hour duck-curve Bellman value and optimal policy map")
hours_24 = np.arange(24)
duck_prices = np.array([
28.0, 24.0, 22.0, 21.0, 24.0, 34.0, 48.0, 54.0, # 00..07 (overnight + morning shoulder)
38.0, 22.0, 14.0, 10.0, 9.0, 11.0, 15.0, 26.0, # 08..15 (deep solar midday belly)
52.0, 96.0, 145.0, 162.0, 138.0, 92.0, 54.0, 36.0 # 16..23 (steep evening scarcity ramp)
], dtype=float)
w_duck_scen = np.array([0.0, 3.0, 9.0], dtype=float)
w_duck_prob = np.array([0.35, 0.45, 0.20], dtype=float)
duck_sol = dynamic_optimality.stochastic_bellman_storage(
duck_prices,
w_duck_scen,
w_duck_prob,
n_soc_states=41,
max_capacity=100.0,
max_rate=25.0,
efficiency=0.92,
terminal_value_per_unit=25.0,
)
soc_g = duck_sol["soc_grid"]
act_map = duck_sol["optimal_action_table"] # shape (24, 41)
# Verify physically sensible optimal actions:
# At midday solar trough (t=12, price=$9/MWh) and low SOC (s=10 MWh), optimal policy charges at max rate +25 MW
assert np.isclose(act_map[12, 4], +25.0, atol=1e-12)
# At evening scarcity peak (t=19, price=$162/MWh) and high SOC (s=80 MWh), optimal policy discharges at max rate -25 MW
assert np.isclose(act_map[19, 32], -25.0, atol=1e-12)
assert duck_sol["expected_optimal_profit_from_zero"] > 6000.0
print(f"Expected 24h optimal profit from s0 = 0 MWh : ${duck_sol['expected_optimal_profit_from_zero']:,.2f}")
print(f"Expected 24h optimal profit from s0 = 50 MWh : ${duck_sol['value_table'][0, 20]:,.2f}")
print(f"Midday trough action a*(t=12h, SOC=10 MWh) : {act_map[12, 4]:+.1f} MW (charge hard at $9/MWh)")
print(f"Evening peak action a*(t=19h, SOC=80 MWh) : {act_map[19, 32]:+.1f} MW (discharge hard at $162/MWh)")
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9.6, 4.0))
ax1.step(hours_24, duck_prices, where="mid", lw=2.3, color="#C0392B")
ax1.fill_between(hours_24, 0.0, duck_prices, step="mid", color="#C0392B", alpha=0.12)
ax1.set_xlabel("Hour of day $t$ [h]")
ax1.set_ylabel("Wholesale price $P_t$ [USD/MWh]")
ax1.set_title("24-hour duck-curve price profile")
im = ax2.imshow(
act_map.T,
origin="lower",
aspect="auto",
extent=[-0.5, 23.5, 0.0, 100.0],
cmap="RdBu",
vmin=-25.0,
vmax=25.0,
)
ax2.set_xlabel("Hour of day $t$ [h]")
ax2.set_ylabel("State of charge $\\mathrm{SOC}$ [MWh]")
ax2.set_title(r"Optimal feedback policy $a^*(t, \mathrm{SOC})$ [MW]")
ax2.grid(False)
fig.colorbar(im, ax=ax2, label="Action (+charge / -discharge) [MW]")
label_panels(fig)
plt.show()
Demonstration 2: 24-hour duck-curve Bellman value and optimal policy map
========================================================================
Expected 24h optimal profit from s0 = 0 MWh : $15,001.78
Expected 24h optimal profit from s0 = 50 MWh : $16,295.56
Midday trough action a*(t=12h, SOC=10 MWh) : +25.0 MW (charge hard at $9/MWh)
Evening peak action a*(t=19h, SOC=80 MWh) : -25.0 MW (discharge hard at $162/MWh)

Figure 7.2. The 24-hour synthetic price profile and the optimal policy. (a) Hourly price with the midday trough and the evening peak. (b) Optimal action : charging (blue) in the cheap hours, discharging (red) at the peak, holding (white) in between.
What Demonstration 2 shows. In the map of , blue zones () absorb cheap midday solar energy (while tapering off near to leave headroom for random renewable inflows), white zones () hold energy through the moderate hours, and deep red zones () discharge into the evening peak.
3. Expected Value of Perfect Information (EVPI)¶
How much would an ideal clairvoyant weather oracle—predicting every hour’s exact inflow in advance—be worth in dollars per day? Let denote optimal hindsight DP profit for a specific realized weather sequence , and let denote expected profit under non-anticipative Stochastic Bellman control. For any myopic heuristic :
places a hard economic ceiling on how much you should ever pay for better weather-forecasting sensors or ML models.
heading("Demonstration 3: Clairvoyant hindsight oracle against stochastic Bellman against myopic heuristic (EVPI)")
def solve_hindsight_trajectory_dp(
prices: np.ndarray,
realized_inflows: np.ndarray,
soc_grid: np.ndarray,
max_rate: float = 25.0,
efficiency: float = 0.92,
terminal_val: float = 25.0,
) -> float:
"""Exact deterministic backward DP when realized time-varying inflows w[0..T-1] are known in advance."""
t_hor = prices.size
cap = float(soc_grid[-1])
actions = np.linspace(-max_rate, max_rate, 11)
v_next = terminal_val * soc_grid
for t in range(t_hor - 1, -1, -1):
p_t = float(prices[t])
w_t = float(realized_inflows[t])
v_cur = np.empty_like(soc_grid)
for si, s_c in enumerate(soc_grid):
best_q = -np.inf
for a in actions:
if a >= 0.0:
rew = -p_t * a
s_nx = min(cap, max(0.0, s_c + efficiency * a + w_t))
else:
if -a > s_c + 1e-12:
continue
rew = p_t * efficiency * (-a)
s_nx = min(cap, max(0.0, s_c + a + w_t))
q_val = rew + float(np.interp(s_nx, soc_grid, v_next))
if q_val > best_q:
best_q = q_val
v_cur[si] = best_q
v_next = v_cur
return float(v_next[0])
# Sanity check: constant inflow trajectory matches stochastic_bellman_storage(probs=[1.0]) to machine precision
chk_const = dynamic_optimality.stochastic_bellman_storage(
duck_prices, np.array([3.0]), np.array([1.0]), n_soc_states=41, max_capacity=100.0, max_rate=25.0, efficiency=0.92, terminal_value_per_unit=25.0
)
assert np.isclose(solve_hindsight_trajectory_dp(duck_prices, np.full(24, 3.0), soc_g), chk_const["expected_optimal_profit_from_zero"], atol=1e-12)
# Monte Carlo evaluation across 250 random 24-hour weather trajectories from s0 = 0 MWh
# Use an integer-aligned dispatch testbed (n_soc_states=101, efficiency=0.80, w in {0, 5, 10}) so discrete actions
# a in {-25,-20,...,+25} map every state transition s + ds + w onto exact grid integers with zero interpolation drift
w_ev_scen = np.array([0.0, 5.0, 10.0], dtype=float)
w_ev_prob = np.array([0.35, 0.45, 0.20], dtype=float)
ev_sol = dynamic_optimality.stochastic_bellman_storage(
duck_prices,
w_ev_scen,
w_ev_prob,
n_soc_states=101,
max_capacity=100.0,
max_rate=25.0,
efficiency=0.80,
terminal_value_per_unit=25.0,
)
soc_101 = ev_sol["soc_grid"]
act_101 = ev_sol["optimal_action_table"]
rng_ev = np.random.default_rng(7)
n_mc = 250
w_draws = rng_ev.choice(w_ev_scen, size=(n_mc, 24), p=w_ev_prob)
v_clair_mc = np.zeros(n_mc)
v_bell_mc = np.zeros(n_mc)
v_myop_mc = np.zeros(n_mc)
p_med = float(np.median(duck_prices))
for m in range(n_mc):
w_seq = w_draws[m]
v_clair_mc[m] = solve_hindsight_trajectory_dp(duck_prices, w_seq, soc_101, max_rate=25.0, efficiency=0.80, terminal_val=25.0)
# Exact closed-loop Stochastic Bellman rollout on integer SOC grid:
s_b = 0
prof_b = 0.0
for t in range(24):
a_b = float(act_101[t, s_b])
if a_b >= 0.0:
prof_b -= duck_prices[t] * a_b
s_b = min(100, s_b + int(round(0.80 * a_b + w_seq[t])))
else:
prof_b += duck_prices[t] * 0.80 * (-a_b)
s_b = min(100, max(0, s_b + int(round(a_b + w_seq[t]))))
v_bell_mc[m] = prof_b + 25.0 * s_b
# Naive myopic rule using the same discrete 5-MW action increments:
s_m = 0
prof_m = 0.0
for t in range(24):
a_m = 25.0 if duck_prices[t] < 0.75 * p_med else (-float(min(s_m - (s_m % 5), 25)) if duck_prices[t] > 1.05 * p_med else 0.0)
if a_m >= 0.0:
prof_m -= duck_prices[t] * a_m
s_m = min(100, s_m + int(round(0.80 * a_m + w_seq[t])))
else:
prof_m += duck_prices[t] * 0.80 * (-a_m)
s_m = min(100, max(0, s_m + int(round(a_m + w_seq[t]))))
v_myop_mc[m] = prof_m + 25.0 * s_m
mean_myop = float(np.mean(v_myop_mc))
mean_bell = float(np.mean(v_bell_mc))
mean_clair = float(np.mean(v_clair_mc))
evpi_dollars = mean_clair - mean_bell
# On every single trajectory, hindsight clairvoyance >= any feasible policy, so EVPI >= 0:
assert np.all(v_clair_mc >= v_bell_mc - 1e-9)
assert mean_myop < mean_bell <= mean_clair
assert evpi_dollars > 0.0
print(f"Myopic Price-Rule Mean Profit : ${mean_myop:,.2f} / day")
print(f"Stochastic Bellman Mean Profit : ${mean_bell:,.2f} / day (Theoretical DP = ${ev_sol['expected_optimal_profit_from_zero']:,.2f})")
print(f"Clairvoyant Hindsight Mean Profit : ${mean_clair:,.2f} / day")
print(f"Expected Value of Perfect Info : EVPI = ${evpi_dollars:,.2f} / day ({100.0 * evpi_dollars / mean_bell:.2f}% forecast ceiling)")
fig, ax = plt.subplots(figsize=(7.2, 4.0))
labels_p = ["Myopic threshold", "Stochastic Bellman", "Clairvoyant oracle"]
means_p = [mean_myop, mean_bell, mean_clair]
bars = ax.bar(labels_p, means_p, color=["#C0392B", "#2166AC", "#2E8B57"], width=0.52)
ax.set_ylabel("Expected daily profit [USD/day]")
ax.set_title(f"Three policies; EVPI = {evpi_dollars:.1f} USD/day over {n_mc} weather realizations")
ax.set_ylim(0.0, 1.15 * mean_clair)
for b_rect, v_num in zip(bars, means_p):
ax.text(b_rect.get_x() + 0.5 * b_rect.get_width(), v_num + 120.0, f"{v_num:,.0f}", ha="center", fontsize=9)
plt.show()
Demonstration 3: Clairvoyant hindsight oracle against stochastic Bellman against myopic heuristic (EVPI)
========================================================================================================
Myopic Price-Rule Mean Profit : $11,132.45 / day
Stochastic Bellman Mean Profit : $13,208.39 / day (Theoretical DP = $13,264.13)
Clairvoyant Hindsight Mean Profit : $13,428.63 / day
Expected Value of Perfect Info : EVPI = $220.24 / day (1.67% forecast ceiling)

Figure 7.3. Mean daily profit over 250 synthetic weather days for the myopic rule, the stochastic Bellman policy and the clairvoyant policy that knows the inflows in advance. The difference between the last two, 220 USD per day, is the expected value of perfect information.
What Demonstration 3 shows. Stochastic Bellman earns 98.4 % of the clairvoyant profit ( USD against USD per day) without knowing the future inflows, and USD per day more than the myopic rule. USD per day is the most that a perfect inflow forecast could be worth in this model.
4. Round-Trip Efficiency & the No-Trade Deadband¶
Why do lower-efficiency storage technologies (such as hydrogen power-to-gas-to-power, here assumed to have one-way and round-trip ) sit idle during moderate price swings where Li-ion batteries (assumed , ) cycle actively?
Trace bought from the grid at : charging stores inside the reservoir, and discharging delivers back to the grid at . Net profit per MWh bought is , which is strictly positive if and only if:
Whenever price ratios fall inside , thermodynamic conversion losses exceed arbitrage revenue, so the optimal action is to do nothing () over a wide band of prices.
heading("Demonstration 4: One-way efficiency sweep — profit erosion and deadband widening")
eta_grid = np.linspace(0.60, 1.00, 17)
profits_eta = np.zeros_like(eta_grid)
idle_frac_eta = np.zeros_like(eta_grid)
for idx, eta_v in enumerate(eta_grid):
s_eta = dynamic_optimality.stochastic_bellman_storage(
duck_prices,
w_duck_scen,
w_duck_prob,
n_soc_states=41,
max_capacity=100.0,
max_rate=25.0,
efficiency=float(eta_v),
terminal_value_per_unit=25.0,
)
profits_eta[idx] = s_eta["expected_optimal_profit_from_zero"]
# Fraction of (t, SOC > 0) policy cells choosing strict hold a* == 0:
sub_act = s_eta["optimal_action_table"][:, 1:-1]
idle_frac_eta[idx] = float(np.mean(np.isclose(sub_act, 0.0, atol=1e-12)))
assert np.all(np.diff(profits_eta) > 0.0) # Higher efficiency strictly increases value
assert idle_frac_eta[0] > idle_frac_eta[-1] # Lower efficiency widens the hold deadband
print(f"eta = 0.60 (RT = 36%, P_sell/P_buy > {1.0/0.60**2:.2f}x): Profit = ${profits_eta[0]:,.1f}, Idle policy cells = {100.0 * idle_frac_eta[0]:.1f}%")
print(f"eta = 0.90 (RT = 81%, P_sell/P_buy > {1.0/0.90**2:.2f}x): Profit = ${profits_eta[12]:,.1f}, Idle policy cells = {100.0 * idle_frac_eta[12]:.1f}%")
print(f"eta = 1.00 (RT =100%, P_sell/P_buy > {1.0/1.00**2:.2f}x): Profit = ${profits_eta[-1]:,.1f}, Idle policy cells = {100.0 * idle_frac_eta[-1]:.1f}%")
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9.2, 3.9))
ax1.plot(eta_grid ** 2, profits_eta, marker="o", lw=2.2, color="#2166AC")
ax1.set_xlabel(r"Round-trip efficiency $\eta_{\mathrm{RT}} = \eta^2$")
ax1.set_ylabel("Expected daily profit [USD/day]")
ax1.set_title("Value sensitivity to round-trip efficiency")
ax2.plot(eta_grid ** 2, 100.0 * idle_frac_eta, marker="s", lw=2.2, color="#E08214")
ax2.set_xlabel(r"Round-trip efficiency $\eta_{\mathrm{RT}} = \eta^2$")
ax2.set_ylabel("Hold / deadband cells $a^* = 0$ [%]")
ax2.set_title("Share of hold actions")
label_panels(fig)
plt.show()
Demonstration 4: One-way efficiency sweep — profit erosion and deadband widening
================================================================================
eta = 0.60 (RT = 36%, P_sell/P_buy > 2.78x): Profit = $8,269.4, Idle policy cells = 45.9%
eta = 0.90 (RT = 81%, P_sell/P_buy > 1.23x): Profit = $14,545.6, Idle policy cells = 13.9%
eta = 1.00 (RT =100%, P_sell/P_buy > 1.00x): Profit = $16,803.8, Idle policy cells = 4.2%

Figure 7.4. Effect of the round-trip efficiency . (a) Expected daily profit. (b) Fraction of the policy table in which the optimal action is to hold, which falls from about 46 % at to 4 % at .
Inside the algorithm¶
What if a system operates continuously over an infinite horizon () with discount factor , transition tensor , and reward matrix ? Define the Bellman Optimality Operator :
Because and , is a -contraction in the supremum norm :
By the Banach Fixed-Point Theorem, iterating from any initial vector converges geometrically to a unique global fixed point . We inspect stochastic_bellman_storage and verify Banach contraction numerically.
Check against the library¶
heading("Inside the algorithm: stochastic_bellman_storage and infinite-horizon Banach contraction")
print(show_source(dynamic_optimality.stochastic_bellman_storage))
def infinite_horizon_bellman_value_iteration(
P_trans: np.ndarray,
R_mat: np.ndarray,
gamma: float = 0.92,
tol: float = 1e-12,
max_iter: int = 500,
) -> dict:
"""Solve V* = T(V*) via Bellman Value Iteration and record step-by-step sup-norm deltas."""
n_states, n_actions, _ = P_trans.shape
v = np.zeros(n_states, dtype=float)
deltas = []
for _ in range(max_iter):
# Q[s, a] = R[s, a] + gamma * sum_{s'} P[s, a, s'] * v[s']
q_mat = R_mat + gamma * (P_trans @ v)
v_next = np.max(q_mat, axis=1)
diff = float(np.max(np.abs(v_next - v)))
deltas.append(diff)
v = v_next
if diff < tol:
break
q_final = R_mat + gamma * (P_trans @ v)
pi_star = np.argmax(q_final, axis=1)
bellman_res = float(np.max(np.abs( np.max(q_final, axis=1) - v )))
return {"V_star": v, "policy": pi_star, "deltas": np.array(deltas), "bellman_residual": bellman_res}
# Construct a 6-state, 3-action stationary microgrid MDP (SOC levels x regime states):
rng_mdp = np.random.default_rng(19)
n_s, n_a = 6, 3
raw_p = rng_mdp.uniform(0.05, 1.0, size=(n_s, n_a, n_s))
P_mdp = raw_p / np.sum(raw_p, axis=2, keepdims=True)
R_mdp = np.array([
[10.0, 2.0, -8.0],
[14.0, 6.0, -5.0],
[18.0, 12.0, -2.0],
[22.0, 19.0, 8.0],
[20.0, 26.0, 17.0],
[15.0, 29.0, 31.0],
], dtype=float)
gamma_test = 0.92
vi_res = infinite_horizon_bellman_value_iteration(P_mdp, R_mdp, gamma=gamma_test, tol=1e-11)
d_seq = vi_res["deltas"]
# Measure contraction ratios well above float64 ulp rounding floor (~1e-3):
above_ulp = d_seq[:-1] > 1e-3
ratios = d_seq[1:][above_ulp] / d_seq[:-1][above_ulp]
# 1. Verify strict Banach contraction factor ||V^{(k+1)} - V^{(k)}||_inf <= gamma * ||V^{(k)} - V^{(k-1)}||_inf
assert np.all(ratios <= gamma_test + 1e-7)
assert vi_res["bellman_residual"] < 1e-11
# 2. Verify exact agreement with linear-system policy evaluation (I - gamma P^{pi*}) V = r^{pi*}:
pi_opt = vi_res["policy"]
P_pi = P_mdp[np.arange(n_s), pi_opt, :]
r_pi = R_mdp[np.arange(n_s), pi_opt]
v_exact_lin = np.linalg.solve(np.eye(n_s) - gamma_test * P_pi, r_pi)
assert np.allclose(vi_res["V_star"], v_exact_lin, atol=1e-11)
print(f"Converged in {len(d_seq)} iterations | Final Bellman residual ||TV* - V*||_inf = {vi_res['bellman_residual']:.3e}")
print(f"Max empirical contraction ratio max_k (d_{{k+1}} / d_k) = {np.max(ratios):.6f} <= gamma = {gamma_test:.6f}")
fig, ax = plt.subplots(figsize=(7.2, 3.9))
k_idx = np.arange(len(d_seq))
ax.semilogy(k_idx, d_seq, marker="o", ms=3.5, lw=2.0, color="#2166AC", label=r"Actual $\|V^{(k+1)} - V^{(k)}\|_\infty$")
ax.semilogy(k_idx, d_seq[0] * (gamma_test ** k_idx), lw=1.8, ls="--", color="#C0392B", label=r"Banach bound $\|V^{(1)} - V^{(0)}\|_\infty \cdot \gamma^k$")
ax.set_xlabel("Value iteration step $k$")
ax.set_ylabel(r"Sup-norm step change $\| \Delta V^{(k)} \|_\infty$")
ax.set_title(r"Value iteration contracts by $\gamma = 0.92$ per step")
ax.legend(fontsize=8.5)
plt.show()
Inside the algorithm: stochastic_bellman_storage and infinite-horizon Banach contraction
========================================================================================
def stochastic_bellman_storage(
prices: np.ndarray,
inflow_scenarios: np.ndarray,
inflow_probs: np.ndarray,
n_soc_states: int = 21,
max_capacity: float = 100.0,
max_rate: float = 25.0,
efficiency: float = 0.92,
terminal_value_per_unit: float = 0.0,
) -> dict:
"""Backward-induction Stochastic Bellman DP for battery/reservoir dispatch under uncertain inflows."""
pr = np.asarray(prices, dtype=float).ravel()
inf_s = np.asarray(inflow_scenarios, dtype=float).ravel()
inf_p = np.asarray(inflow_probs, dtype=float).ravel()
if pr.size < 1 or inf_s.size != inf_p.size or not np.isclose(np.sum(inf_p), 1.0) or np.any(inf_p < 0.0):
raise ValueError("Require non-empty prices and valid probability distribution inflow_probs summing to 1.")
if n_soc_states < 3 or max_capacity <= 0.0 or max_rate <= 0.0 or not (0.0 < efficiency <= 1.0):
raise ValueError("Invalid storage state/rate/efficiency parameters.")
t_hor = pr.size
soc_grid = np.linspace(0.0, float(max_capacity), int(n_soc_states))
# Action a in [-max_rate, +max_rate]: a > 0 charges from grid, a < 0 discharges to grid.
actions = np.linspace(-float(max_rate), float(max_rate), 11)
val = np.zeros((t_hor + 1, soc_grid.size), dtype=float)
val[t_hor, :] = float(terminal_value_per_unit) * soc_grid
opt_act = np.zeros((t_hor, soc_grid.size), dtype=float)
for t in range(t_hor - 1, -1, -1):
price_t = float(pr[t])
v_next = val[t + 1, :]
for si, s_cur in enumerate(soc_grid):
best_q = -np.inf
best_a = 0.0
for a in actions:
if a >= 0.0:
# Buying power `a` costs price_t * a and adds efficiency * a to storage:
reward = -price_t * a
ds_ctrl = float(efficiency) * a
else:
# Discharging `-a` from storage cannot exceed current s_cur; delivers efficiency * (-a) to grid:
if -a > s_cur + 1e-12:
continue
reward = price_t * float(efficiency) * (-a)
ds_ctrl = a
s_next_vec = np.clip(s_cur + ds_ctrl + inf_s, 0.0, float(max_capacity))
ev_future = float(np.sum(inf_p * np.interp(s_next_vec, soc_grid, v_next)))
q_tot = reward + ev_future
if q_tot > best_q:
best_q = q_tot
best_a = float(a)
val[t, si] = best_q
opt_act[t, si] = best_a
return {
"soc_grid": soc_grid,
"value_table": val,
"optimal_action_table": opt_act,
"expected_optimal_profit_from_zero": float(val[0, 0]),
}
Converged in 341 iterations | Final Bellman residual ||TV* - V*||_inf = 8.583e-12
Max empirical contraction ratio max_k (d_{k+1} / d_k) = 0.920000 <= gamma = 0.920000

Figure 7.5. Value iteration on an infinite-horizon problem with : the sup-norm change between successive iterates (solid) decreases geometrically and stays below the contraction bound (dashed) for all 341 iterations.
Exercises¶
Worked solutions are in 07_solutions.ipynb. The cell below the list is a short self-check to start from.
Verify a result. Verify numerically that (a) on an evening peak stochastic dispatch horizon is monotonically non-decreasing () and concave () across
soc_grid, and (b) on a 2-period pure arbitrage test (, ),stochastic_bellman_storageholds () for every and charges at full rate () for every .Find how it fails. Verify
ValueErrorguards onstochastic_bellman_storage, then audit (a) how forward myopic greedy dispatch empties a battery on a morning bump right before a evening spike, and (b) how tabular grid DP memory grows across coupled reservoirs.Implement it yourself. Implement
simulate_closed_loop_bellman_fleet(prices, bellman_sol, inflow_samples, max_capacity=100.0, efficiency=0.92, terminal_value_per_unit=25.0)to evaluate closed-loop Bellman control across500random 24-hour weather trajectories (inflow_samplesof shape(500, 24)), verifying convergence to theoretical expected DP profit and strict superiority over fixed price-threshold rules.
heading("Self-check for the exercises")
assert np.isclose(sol_2["value_table"][0, idx_s0], best_brute, atol=1e-10)
assert mean_myop < mean_bell <= mean_clair and evpi_dollars > 0.0
assert np.all(ratios <= gamma_test + 1e-7) and np.allclose(vi_res["V_star"], v_exact_lin, atol=1e-11)
print("All checks passed.")
Self-check for the exercises
============================
All checks passed.