Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

7. Decisions under uncertainty: stochastic dynamic programming for energy storage

School of Engineering, Nazarbayev University

Suppose you operate a grid-scale battery or pumped-hydro reservoir at 17:00: wholesale power sells for 65 USD/MWh65\ \mathrm{USD/MWh} right now, whereas tomorrow evening could either spike to 220 USD/MWh220\ \mathrm{USD/MWh} 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 TT. Bellman’s (1952) principle of optimality (Mental Move #16, Induct Backward Under Future Uncertainty) solves the sequential problem backward from t=Tt = T to t=0t = 0. 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 η<1\eta < 1 creates a wide no-trade price deadband (Psell/Pbuy>1/η2P_{\mathrm{sell}}/P_{\mathrm{buy}} > 1/\eta^2), and check the Banach contraction of infinite-horizon value iteration numerically.

Learning objectives

  1. 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.

  2. Compute optimal value tables Vt(SOC)V_t(\mathrm{SOC}) and feedback control policies a∗(t,SOC)a^*(t, \mathrm{SOC}) on 24-hour duck-curve markets using dynamic_optimality.stochastic_bellman_storage.

  3. Quantify the Expected Value of Perfect Information (EVPI=E[Vclairvoyant]−VBellman≥0\mathrm{EVPI} = \mathbb{E}[V_{\mathrm{clairvoyant}}] - V_{\mathrm{Bellman}} \geq 0) and derive the round-trip efficiency deadband threshold Psell/Pbuy>1/η2P_{\mathrm{sell}}/P_{\mathrm{buy}} > 1/\eta^2.

  4. Verify Banach fixed-point contraction ∥V(k+1)−V(k)∥∞≤γ∥V(k)−V(k−1)∥∞\|V^{(k+1)} - V^{(k)}\|_\infty \leq \gamma \|V^{(k)} - V^{(k-1)}\|_\infty for infinite-horizon discounted MDPs and evaluate closed-loop Bellman policies via Monte Carlo simulation.

Time: about 60 min

1. Backward Induction Under Uncertainty & The Flaw of Averages

Consider a storage asset with state-of-charge st∈[0,Smax⁡]s_t \in [0, S_{\max}], control action at∈[−Rmax⁡,+Rmax⁡]a_t \in [-R_{\max}, +R_{\max}] (at>0a_t > 0 charges from the grid at cost PtatP_t a_t adding ηat\eta a_t to storage; at<0a_t < 0 withdraws ∣at∣≤st|a_t| \leq s_t from storage delivering η∣at∣\eta |a_t| to the grid at revenue ηPt∣at∣\eta P_t |a_t|), and random renewable inflow Wt∼p(w)W_t \sim p(w):

st+1=clip ⁣(st+Δsctrl(at)+Wt,  0,  Smax⁡),Δsctrl(a)={η a,a≥0,a,a<0.(1.1)s_{t+1} = \mathrm{clip}\!\Big(s_t + \Delta s_{\mathrm{ctrl}}(a_t) + W_t,\; 0,\; S_{\max}\Big), \qquad \Delta s_{\mathrm{ctrl}}(a) = \begin{cases} \eta\, a, & a \geq 0, \\ a, & a < 0. \end{cases} \tag{1.1}

Why must we induct backward from terminal value VT(s)=vterm sV_T(s) = v_{\mathrm{term}}\, s? At t=T−1t = T - 1, VTV_T is already known for every state sTs_T, so for each sT−1s_{T-1} we immediately maximize immediate reward plus expected continuation value:

Vt(s)=max⁡a∈A(s){rt(s,a)+∑kpk Vt+1 ⁣(clip(s+Δsctrl(a)+wk,  0,  Smax⁡))}(1.2)V_t(s) = \max_{a \in \mathcal{A}(s)} \left\{ r_t(s, a) + \sum_{k} p_k\, V_{t+1}\!\Big(\mathrm{clip}\big(s + \Delta s_{\mathrm{ctrl}}(a) + w_k,\; 0,\; S_{\max}\big)\Big) \right\} \tag{1.2}

Notice why Certainty-Equivalent Planning—replacing random inflow WtW_t with its mean wˉ=E[Wt]\bar{w} = \mathbb{E}[W_t]—commits the Flaw of Averages: because clip(..., 0, S_max) and concave continuation values Vt+1(s)V_{t+1}(s) satisfy Jensen’s Inequality E[Vt+1(s+W)]≤Vt+1(s+E[W])\mathbb{E}[V_{t+1}(s + W)] \leq V_{t+1}(s + \mathbb{E}[W]), deterministic mean-inflow planning ignores spillage risk at Smax⁡S_{\max} and systematically overestimates value.


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 size 814x440 with 1 Axes>

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 (s0≈75 MWhs_0 \approx 75\ \mathrm{MWh}), a deterministic planner using average inflow wˉ=17.5 MWh\bar{w} = 17.5\ \mathrm{MWh} assumes all 17.5 MWh17.5\ \mathrm{MWh} fits inside the 100 MWh100\ \mathrm{MWh} tank (75+17.5=92.5≤10075 + 17.5 = 92.5 \leq 100). In reality, half the time Wt=35 MWhW_t = 35\ \mathrm{MWh} spills 10 MWh10\ \mathrm{MWh} over the 100 MWh100\ \mathrm{MWh} dam crest while the other half delivers 0 MWh0\ \mathrm{MWh}. Over the six stages the certainty-equivalent value exceeds the stochastic Bellman value by up to 1,1231{,}123 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 a∗(t,SOC)a^*(t, \mathrm{SOC}) for every hour t∈{0,…,23}t \in \{0,\dots,23\} and every storage level.


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 size 1056x440 with 3 Axes>

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 a∗(t,SOC)a^*(t, \mathrm{SOC}): charging (blue) in the cheap hours, discharging (red) at the peak, holding (white) in between.

What Demonstration 2 shows. In the map of a∗(t,SOC)a^*(t, \mathrm{SOC}), blue zones (+25 MW+25\ \mathrm{MW}) absorb cheap 9–15 USD/MWh9\text{–}15\ \mathrm{USD/MWh} midday solar energy (while tapering off near SOC→100 MWh\mathrm{SOC} \to 100\ \mathrm{MWh} to leave headroom for random renewable inflows), white zones (0 MW0\ \mathrm{MW}) hold energy through the moderate hours, and deep red zones (−25 MW-25\ \mathrm{MW}) discharge into the 145–162 USD/MWh145\text{–}162\ \mathrm{USD/MWh} evening peak.


3. Expected Value of Perfect Information (EVPI)

How much would an ideal clairvoyant weather oracle—predicting every hour’s exact inflow w0,w1,…,wT−1w_0, w_1, \dots, w_{T-1} in advance—be worth in dollars per day? Let Vclair(w0:T−1)V_{\mathrm{clair}}(w_{0:T-1}) denote optimal hindsight DP profit for a specific realized weather sequence w0:T−1w_{0:T-1}, and let VBellmanV_{\mathrm{Bellman}} denote expected profit under non-anticipative Stochastic Bellman control. For any myopic heuristic VmyopicV_{\mathrm{myopic}}:

E[Vmyopic]  ≤  VBellman  ≤  E[Vclairvoyant],EVPI≡E[Vclairvoyant]−VBellman≥0(3.1)\mathbb{E}[V_{\mathrm{myopic}}] \;\leq\; V_{\mathrm{Bellman}} \;\leq\; \mathbb{E}[V_{\mathrm{clairvoyant}}], \qquad \mathrm{EVPI} \equiv \mathbb{E}[V_{\mathrm{clairvoyant}}] - V_{\mathrm{Bellman}} \geq 0 \tag{3.1}

EVPI\mathrm{EVPI} places a hard economic ceiling on how much you should ever pay for better weather-forecasting sensors or ML models.


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 size 792x440 with 1 Axes>

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 (13,20813{,}208 USD against 13,42913{,}429 USD per day) without knowing the future inflows, and 2,0762{,}076 USD per day more than the myopic rule. EVPI=220\mathrm{EVPI} = 220 USD per day is the most that a perfect inflow forecast could be worth in this model.


4. Round-Trip Efficiency η\eta & the No-Trade Deadband

Why do lower-efficiency storage technologies (such as hydrogen power-to-gas-to-power, here assumed to have one-way η=0.65\eta = 0.65 and round-trip ηRT=η2≈0.42\eta_{\mathrm{RT}} = \eta^2 \approx 0.42) sit idle during moderate price swings where Li-ion batteries (assumed η=0.94\eta = 0.94, ηRT≈0.88\eta_{\mathrm{RT}} \approx 0.88) cycle actively?

Trace 1 MWh1\ \mathrm{MWh} bought from the grid at PbuyP_{\mathrm{buy}}: charging stores η MWh\eta\ \mathrm{MWh} inside the reservoir, and discharging delivers η⋅(η MWh)=η2 MWh\eta \cdot (\eta\ \mathrm{MWh}) = \eta^2\ \mathrm{MWh} back to the grid at PsellP_{\mathrm{sell}}. Net profit per MWh bought is η2Psell−Pbuy\eta^2 P_{\mathrm{sell}} - P_{\mathrm{buy}}, which is strictly positive if and only if:

PsellPbuy>1η2=1ηRT(4.1)\frac{P_{\mathrm{sell}}}{P_{\mathrm{buy}}} > \frac{1}{\eta^2} = \frac{1}{\eta_{\mathrm{RT}}} \tag{4.1}

Whenever price ratios fall inside [1,  1/η2][1,\; 1/\eta^2], thermodynamic conversion losses exceed arbitrage revenue, so the optimal action is to do nothing (a∗=0a^* = 0) over a wide band of prices.


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 size 1012x429 with 2 Axes>

Figure 7.4. Effect of the round-trip efficiency η2\eta^2. (a) Expected daily profit. (b) Fraction of the policy table in which the optimal action is to hold, which falls from about 46 % at η2=0.36\eta^2 = 0.36 to 4 % at η2=1\eta^2 = 1.

Inside the algorithm

What if a system operates continuously over an infinite horizon (t=0,1,2,…t = 0, 1, 2, \dots) with discount factor γ∈(0,1)\gamma \in (0, 1), transition tensor P(s′∣s,a)P(s' \mid s, a), and reward matrix R(s,a)R(s, a)? Define the Bellman Optimality Operator T\mathcal{T}:

(TV)(s)=max⁡a{R(s,a)+γ∑s′P(s′∣s,a) V(s′)}(5.1)(\mathcal{T}V)(s) = \max_{a} \left\{ R(s, a) + \gamma \sum_{s'} P(s' \mid s, a)\, V(s') \right\} \tag{5.1}

Because ∣max⁡af(a)−max⁡ag(a)∣≤max⁡a∣f(a)−g(a)∣|\max_a f(a) - \max_a g(a)| \leq \max_a |f(a) - g(a)| and ∑s′P(s′∣s,a)=1\sum_{s'} P(s' \mid s, a) = 1, T\mathcal{T} is a γ\gamma-contraction in the supremum norm ∥⋅∥∞\|\cdot\|_\infty:

∥Tu−Tv∥∞  ≤  γ ∥u−v∥∞  ⟹  ∥V(k+1)−V(k)∥∞  ≤  γ ∥V(k)−V(k−1)∥∞(5.2)\|\mathcal{T}u - \mathcal{T}v\|_\infty \;\leq\; \gamma\, \|u - v\|_\infty \quad \implies \quad \|V^{(k+1)} - V^{(k)}\|_\infty \;\leq\; \gamma\, \|V^{(k)} - V^{(k-1)}\|_\infty \tag{5.2}

By the Banach Fixed-Point Theorem, iterating V(k+1)=TV(k)V^{(k+1)} = \mathcal{T}V^{(k)} from any initial vector V(0)V^{(0)} converges geometrically to a unique global fixed point V∗=TV∗V^* = \mathcal{T}V^*. We inspect stochastic_bellman_storage and verify Banach contraction numerically.

Check against the library


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 size 792x429 with 1 Axes>

Figure 7.5. Value iteration on an infinite-horizon problem with γ=0.92\gamma = 0.92: 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.

  1. Verify a result. Verify numerically that (a) V0(s)V_0(s) on an evening peak stochastic dispatch horizon is monotonically non-decreasing (ΔV0≥0\Delta V_0 \geq 0) and concave (Δ2V0≤0\Delta^2 V_0 \leq 0) across soc_grid, and (b) on a 2-period pure arbitrage test (P0=40 USD/MWhP_0 = 40\ \mathrm{USD/MWh}, η=0.80  ⟹  P∗=P0/η2=62.5 USD/MWh\eta = 0.80 \implies P^* = P_0 / \eta^2 = 62.5\ \mathrm{USD/MWh}), stochastic_bellman_storage holds (a0∗(0)=0a_0^*(0) = 0) for every P1<62.5P_1 < 62.5 and charges at full rate (a0∗(0)=+25 MWa_0^*(0) = +25\ \mathrm{MW}) for every P1>62.5P_1 > 62.5.

  2. Find how it fails. Verify ValueError guards on stochastic_bellman_storage, then audit (a) how forward myopic greedy dispatch empties a 50 MWh50\ \mathrm{MWh} battery on a 48 USD/MWh48\ \mathrm{USD/MWh} morning bump right before a 240 USD/MWh240\ \mathrm{USD/MWh} evening spike, and (b) how tabular grid DP memory ∣S∣d∣A∣dT|S|^d |A|^d T grows across d=1…6d = 1 \dots 6 coupled reservoirs.

  3. 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 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.


Self-check for the exercises
============================
All checks passed.