Worked solutions to the three exercises of Lecture 7. Each solution is computed here and checked with assert statements against an exact identity or an independent calculation. The first code cell sets up the notebook and runs Demonstration 1 of the lecture without showing its output, because some of the solutions use its variables.
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))
# Demonstration 1 of the lecture, run without output: the solutions use its variables.
import contextlib, io
_show, plt.show = plt.show, lambda *args, **kwargs: None
_stdout = contextlib.redirect_stdout(io.StringIO()); _stdout.__enter__()
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()
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. 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_storage holds () for every and charges at full rate () for every .
heading("Exercise 1: Monotonicity and concavity of V_0(s) and exact 1/eta^2 arbitrage threshold")
p_day = np.array([150.0, 125.0, 95.0, 65.0, 40.0, 28.0])
sol_v = dynamic_optimality.stochastic_bellman_storage(
p_day,
inflow_scenarios=np.array([0.0, 5.0, 10.0]),
inflow_probs=np.array([0.3, 0.5, 0.2]),
n_soc_states=21,
max_capacity=100.0,
max_rate=25.0,
efficiency=0.90,
terminal_value_per_unit=20.0,
)
v0 = sol_v["value_table"][0, :]
s_grid = sol_v["soc_grid"]
dv1 = np.diff(v0)
dv2 = np.diff(v0, n=2)
# 1. Verify monotonicity (dV/ds >= 0) and concavity (d^2V/ds^2 <= 0 on action-aligned 5 MWh grid):
assert np.all(dv1 >= -1e-10)
assert np.all(dv2 <= 1e-9)
# 2. Verify exact round-trip arbitrage threshold P_sell / P_buy > 1 / eta^2:
p_buy = 40.0
eta_arb = 0.80
p_crit = p_buy / (eta_arb ** 2) # 40.0 / 0.64 = 62.50 $/MWh exact
p1_scan = np.linspace(45.0, 80.0, 36)
p1_scan = p1_scan[~np.isclose(p1_scan, p_crit)] # Test strictly below and strictly above 62.5
a0_actions = []
v0_profits = []
for p_sell in p1_scan:
s_arb = dynamic_optimality.stochastic_bellman_storage(
np.array([p_buy, float(p_sell)]),
inflow_scenarios=np.array([0.0]),
inflow_probs=np.array([1.0]),
n_soc_states=21,
max_capacity=100.0,
max_rate=25.0,
efficiency=eta_arb,
terminal_value_per_unit=0.0,
)
a0_actions.append(s_arb["optimal_action_table"][0, 0])
v0_profits.append(s_arb["expected_optimal_profit_from_zero"])
a0_actions = np.array(a0_actions)
v0_profits = np.array(v0_profits)
below = p1_scan < p_crit
above = p1_scan > p_crit
assert np.allclose(a0_actions[below], 0.0, atol=1e-12)
assert np.allclose(v0_actions := v0_profits[below], 0.0, atol=1e-12)
assert np.allclose(a0_actions[above], 25.0, atol=1e-12)
assert np.allclose(v0_profits[above], 25.0 * (eta_arb ** 2 * p1_scan[above] - p_buy), atol=1e-10)
print(f"V0(s) monotonicity min(dV) = {np.min(dv1):+.2f} >= 0 | concavity max(d^2V) = {np.max(dv2):+.3e} <= 0")
print(f"Exact arbitrage threshold P* = P_buy / eta^2 = {p_crit:.2f} USD/MWh verified across all {len(p1_scan)} prices")
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9.2, 3.8))
ax1.plot(s_grid[:-1], dv1 / (s_grid[1] - s_grid[0]), marker="o", ms=3.5, lw=2.0, color="#2166AC")
ax1.set_xlabel("State of charge $s$ [MWh]")
ax1.set_ylabel(r"Marginal value $\Delta V_0 / \Delta s$ [USD/MWh]")
ax1.set_title("Marginal value of stored energy")
ax2.step(p1_scan, a0_actions, where="mid", lw=2.2, color="#C0392B", label=r"Optimal charge $a_0^*(0)$ [MW]")
ax2.axvline(p_crit, color="#2E8B57", ls="--", lw=1.8, label=rf"Threshold $P_0/\eta^2 = {p_crit:.1f}$ USD/MWh")
ax2.set_xlabel(r"Period-1 selling price $P_{\mathrm{sell}}$ [USD/MWh]")
ax2.set_ylabel("Optimal period-0 action [MW]")
ax2.set_title(r"Charging starts at $P_{\mathrm{sell}} = P_{\mathrm{buy}}/\eta^2$")
ax2.legend(fontsize=8)
label_panels(fig)
plt.show()
Exercise 1: Monotonicity and concavity of V_0(s) and exact 1/eta^2 arbitrage threshold
======================================================================================
V0(s) monotonicity min(dV) = +178.33 >= 0 | concavity max(d^2V) = +9.095e-13 <= 0
Exact arbitrage threshold P* = P_buy / eta^2 = 62.50 USD/MWh verified across all 36 prices

Figure S7.1. Checks of the Bellman solution. (a) Marginal value of stored energy against the state of charge; it decreases, so is concave. (b) Optimal first-period action against the second-period price: the switch from holding to charging occurs at USD/MWh (dashed).
Explanation. Each additional MWh of initial charge can only be sold during progressively less lucrative hours once the highest-price peak discharge slots () are saturated, making marginal storage value monotonically non-increasing ( concave). Meanwhile, buying MWh at yields MWh sold at , so net gain switches sign sharply at .
Exercise 2¶
Problem. Verify ValueError guards on stochastic_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.
heading("Exercise 2: Failure-mode audit — forward myopic trap and multi-reservoir curse of dimensionality")
# 0. Input guard checks:
caught = 0
for bad_kw in [
{"prices": np.array([]), "inflow_scenarios": np.array([0.0]), "inflow_probs": np.array([1.0])},
{"prices": np.array([30.0]), "inflow_scenarios": np.array([0.0, 5.0]), "inflow_probs": np.array([0.4, 0.4])},
{"prices": np.array([30.0]), "inflow_scenarios": np.array([0.0, 5.0]), "inflow_probs": np.array([1.2, -0.2])},
{"prices": np.array([30.0]), "inflow_scenarios": np.array([0.0]), "inflow_probs": np.array([1.0]), "efficiency": 1.1},
{"prices": np.array([30.0]), "inflow_scenarios": np.array([0.0]), "inflow_probs": np.array([1.0]), "n_soc_states": 2},
]:
try:
dynamic_optimality.stochastic_bellman_storage(**bad_kw)
except ValueError:
caught += 1
assert caught == 5
# (a) Forward myopic dispatch trap: s0 = 50 MWh, max_rate = 25 MW, zero inflows
# Morning bump (t=0,1: $48/MWh), midday ($35/MWh), evening spike (t=3,4: $240/MWh)
p_spike = np.array([48.0, 48.0, 35.0, 240.0, 240.0])
eta_sp = 0.90
sol_sp = dynamic_optimality.stochastic_bellman_storage(
p_spike, np.array([0.0]), np.array([1.0]), n_soc_states=21, max_capacity=50.0, max_rate=25.0, efficiency=eta_sp
)
v_bellman_50 = sol_sp["value_table"][0, -1] # s0 = 50 MWh
# Myopic controller sells whenever P_t > $40/MWh (looks profitable locally), dumping all 50 MWh at $48/MWh in t=0,1:
s_myop = 50.0
v_myop_50 = 0.0
for p_t in p_spike:
a_m = -min(s_myop, 25.0) if p_t > 40.0 else 0.0
v_myop_50 += p_t * eta_sp * (-a_m)
s_myop += a_m
# Bellman waits through $48, charges or holds at $35, and discharges all 50 MWh into the two $240/MWh peak hours
assert np.isclose(v_myop_50, 50.0 * eta_sp * 48.0, atol=1e-12)
assert np.isclose(v_bellman_50, 50.0 * eta_sp * 240.0, atol=1e-12)
assert np.isclose(v_bellman_50 / v_myop_50, 5.0, atol=1e-12)
# (b) Curse of Dimensionality across d = 1..6 coupled reservoirs (|S| = 21 states/dim, |A| = 11 actions/dim, T = 24):
dims = np.arange(1, 7)
states_d = 21 ** dims
q_evals_d = (21 ** dims) * (11 ** dims) * 24
ram_gb_value_table = (25 * states_d * 8) / 1e9
assert states_d[0] == 21 and states_d[-1] == 85_766_121
print(f"Forward Myopic Profit (s0=50 MWh) : ${v_myop_50:,.2f} (dumped early at $48/MWh)")
print(f"Bellman Optimal Profit (s0=50 MWh): ${v_bellman_50:,.2f} (5.0x higher; held for the $240/MWh peak)")
print(f"Curse of Dimensionality (d=1 -> d=6): states grow from {states_d[0]:,d} -> {states_d[-1]:,d}; Q-evaluations/sweep -> {q_evals_d[-1]:.2e}")
Exercise 2: Failure-mode audit — forward myopic trap and multi-reservoir curse of dimensionality
================================================================================================
Forward Myopic Profit (s0=50 MWh) : $2,160.00 (dumped early at $48/MWh)
Bellman Optimal Profit (s0=50 MWh): $10,800.00 (5.0x higher; held for the $240/MWh peak)
Curse of Dimensionality (d=1 -> d=6): states grow from 21 -> 85,766,121; Q-evaluations/sweep -> 3.65e+15
Explanation. (a) Selling at has positive immediate cash flow, blinding any zero-lookahead greedy rule to the opportunity cost encoded in Bellman’s continuation value. (b) Bellman coined the phrase Curse of Dimensionality precisely because tensor-product grids scale as : at coupled reservoirs, one 24-hour backward sweep requires inner Q-evaluations, motivating approximate/dual dynamic programming (SDDP) in high dimensions.
Exercise 3¶
Problem. 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 across 500 random 24-hour weather trajectories (inflow_samples of shape (500, 24)), verifying convergence to theoretical expected DP profit and strict superiority over fixed price-threshold rules.
heading("Exercise 3: Implement it yourself — Monte Carlo closed-loop Bellman fleet simulator")
def simulate_closed_loop_bellman_fleet(
prices: np.ndarray,
bellman_sol: dict,
inflow_samples: np.ndarray,
max_capacity: float = 100.0,
efficiency: float = 0.92,
terminal_value_per_unit: float = 25.0,
) -> dict:
"""Simulate a fleet/ensemble of closed-loop storage trajectories following bellman_sol['optimal_action_table']."""
pr = np.asarray(prices, dtype=float).ravel()
w_mat = np.asarray(inflow_samples, dtype=float)
n_trials, t_hor = w_mat.shape
assert t_hor == pr.size
soc_grid = bellman_sol["soc_grid"]
act_tbl = bellman_sol["optimal_action_table"]
s_vec = np.zeros(n_trials, dtype=float)
profits = np.zeros(n_trials, dtype=float)
soc_hist = np.zeros((n_trials, t_hor + 1), dtype=float)
for t in range(t_hor):
a_cmd = np.interp(s_vec, soc_grid, act_tbl[t])
# Enforce physical discharge limit -a <= s_vec:
a_exec = np.maximum(-s_vec, a_cmd)
charging = a_exec >= 0.0
profits[charging] -= pr[t] * a_exec[charging]
profits[~charging] += pr[t] * efficiency * (-a_exec[~charging])
ds = np.where(charging, efficiency * a_exec, a_exec)
s_vec = np.clip(s_vec + ds + w_mat[:, t], 0.0, max_capacity)
soc_hist[:, t + 1] = s_vec
profits += terminal_value_per_unit * s_vec
return {
"profits": profits,
"mean_profit": float(np.mean(profits)),
"std_error": float(np.std(profits, ddof=1) / np.sqrt(n_trials)),
"soc_trajectories": soc_hist,
}
prices_24 = np.array([
28.0, 24.0, 22.0, 21.0, 24.0, 34.0, 48.0, 54.0,
38.0, 22.0, 14.0, 10.0, 9.0, 11.0, 15.0, 26.0,
52.0, 96.0, 145.0, 162.0, 138.0, 92.0, 54.0, 36.0,
])
w_sc = np.array([0.0, 3.0, 9.0])
w_pr = np.array([0.35, 0.45, 0.20])
b_sol = dynamic_optimality.stochastic_bellman_storage(
prices_24, w_sc, w_pr, n_soc_states=41, max_capacity=100.0, max_rate=25.0, efficiency=0.92, terminal_value_per_unit=25.0
)
rng_fl = np.random.default_rng(2026)
w_samples_500 = rng_fl.choice(w_sc, size=(500, 24), p=w_pr)
mc_bell = simulate_closed_loop_bellman_fleet(prices_24, b_sol, w_samples_500)
# Compare against heuristic price-band policy (charge < $25/MWh, discharge > $85/MWh):
heur_act = np.zeros_like(b_sol["optimal_action_table"])
for t in range(24):
if prices_24[t] < 25.0:
heur_act[t, :] = 25.0
elif prices_24[t] > 85.0:
heur_act[t, :] = -np.minimum(b_sol["soc_grid"], 25.0)
mc_heur = simulate_closed_loop_bellman_fleet(
prices_24, {"soc_grid": b_sol["soc_grid"], "optimal_action_table": heur_act}, w_samples_500
)
dp_theory = b_sol["expected_optimal_profit_from_zero"]
assert abs(mc_bell["mean_profit"] - dp_theory) < 3.5 * mc_bell["std_error"]
assert mc_bell["mean_profit"] > mc_heur["mean_profit"] + 400.0
assert np.mean(mc_bell["profits"] >= mc_heur["profits"]) > 0.95
print(f"Theoretical Bellman V_0(0) : ${dp_theory:,.2f}")
print(f"Closed-Loop MC Mean (N = 500) : ${mc_bell['mean_profit']:,.2f} +/- ${mc_bell['std_error']:.2f}")
print(f"Heuristic Price-Band Mean : ${mc_heur['mean_profit']:,.2f} (Bellman wins on {100.0 * np.mean(mc_bell['profits'] >= mc_heur['profits']):.1f}% of days)")
fig, ax = plt.subplots(figsize=(7.4, 4.0))
t_grid = np.arange(25)
p10, p50, p90 = np.percentile(mc_bell["soc_trajectories"], [10, 50, 90], axis=0)
ax.fill_between(t_grid, p10, p90, color="#2166AC", alpha=0.22, label="10th-90th percentile SOC envelope")
ax.plot(t_grid, p50, lw=2.4, color="#2166AC", label="Median closed-loop SOC trajectory")
ax.set_xlabel("Hour $t$ [h]")
ax.set_ylabel("Battery state of charge [MWh]")
ax.set_title("Closed-loop state of charge over 500 days")
ax.legend(loc="upper center", bbox_to_anchor=(0.5, -0.16), ncol=2, fontsize=8.5)
plt.show()
Exercise 3: Implement it yourself — Monte Carlo closed-loop Bellman fleet simulator
===================================================================================
Theoretical Bellman V_0(0) : $15,001.78
Closed-Loop MC Mean (N = 500) : $15,050.66 +/- $29.50
Heuristic Price-Band Mean : $9,437.59 (Bellman wins on 100.0% of days)

Figure S7.2. Closed-loop Bellman dispatch over 500 synthetic weather days: median state of charge (line) and the band between the 10th and 90th percentiles.
Summary. The closed-loop Monte Carlo mean over 500 synthetic weather days, USD, agrees with the backward Bellman value USD to within 1.7 standard errors. The feedback policy adjusts its charging to the realised inflows and beats the fixed price-band rule on every one of the 500 days.