WaterValues Package — Code Walkthrough
This document walks through the WaterValues package implementation. Cross-reference with 01-sdp-theory.md for the mathematics.
Package structure
WaterValues/
Project.toml — deps: HydroCore, Statistics, Dates
src/
WaterValues.jl — main module, exports
discretisation.jl — VolumeGrid, WeeklyInflows, extract_weekly_inflows
watervalue_table.jl — WaterValueTable struct, lookup, interpolation
sdp.jl — SDPParameters, run_sdp, solve_sdp
test/
runtests.jl — 886 tests (all passing)discretisation.jl
VolumeGrid
g = VolumeGrid(0.0, 100.0, 30) # explicit bounds + n points
g = VolumeGrid(reservoir; n=30) # from HydroCore.ReservoirStores a uniform grid [v_min, v_max] with n points. The grid values are a plain Vector{Float64} — simple, fast, no indirection.
Key accessors:
length(g)→ number of pointsg[i]→ volume at grid point igrid_step(g)→ uniform spacing (Mm³)
WeeklyInflows
wi = WeeklyInflows(week, values)Holds all historical inflow observations for one week-of-year. Each value is one equally-likely scenario (Mm³/week).
extractweeklyinflows
weekly = extract_weekly_inflows(inflow_series)
# → Vector{WeeklyInflows} of length 52Takes an HydroCore.InflowSeries (m³/s) and:
- Groups observations by week-of-year (using
week_of_year(dt)) - Converts each value from m³/s to Mm³/week:
× 168 × 3600 × 1e-6 - Returns a 52-element vector of
WeeklyInflows
watervalue_table.jl
WaterValueTable
wvt = WaterValueTable(grid, wv_matrix, vf_matrix)Stores:
wv: (52 × N) matrix of water values [NOK/Mm³]vf: (52 × N) matrix of value function [NOK]
Why NOK/Mm³? The SDP state is volume (Mm³), so the natural unit for the marginal value of water is NOK/Mm³. To convert to the industry-standard NOK/MWh, multiply by the plant's energy yield (MWh/Mm³).
lookup — linear interpolation
wv = lookup(wvt; week=30, volume=65.0) # NOK/Mm³Finds the two nearest grid points and linearly interpolates. Volumes outside [v_min, v_max] are clamped to the boundary.
idx = searchsortedlast(grid.values, volume)
t = (volume - v_lo) / (v_hi - v_lo)
wv = w_lo + t × (w_hi - w_lo)This O(log N) lookup is fast enough for simulation (millions of calls/run).
sdp.jl
SDPParameters
Configuration struct — explicit rather than keyword-only to make the algorithm auditable. Key fields:
n_cycles: number of annual iterations (default 10)terminal_wv: NOK/Mm³ starting value (estimated from price × efficiency)price: flat electricity price NOK/MWhr_max: max turbine discharge (Mm³/week)tol: convergence criterion (NOK)
run_sdp — the core algorithm
wvt = run_sdp(grid, weekly_inflows, pq_curve, params)Three nested loops:
for cycle in 1:n_cycles:
for t = 52 downto 1:
for i in 1:N (volume grid points):
average over S inflow scenarios:
find r* via fine grid search (500 points)
optimal_value = revenue(r*) + V_{t+1}(v_new)
V_t(v_i) = mean over scenariosAfter the loops, finite differences extract the WV table.
Fine grid search (500 points over [rlo, rhi]):
- Simple and correct for concave objectives
- Fast enough: 52 × 30 × 20 × 500 = 15.6M evaluations per cycle
- Each evaluation is just: PQ lookup + interpolation (microseconds)
- Total for 10 cycles: ~0.1–0.5 seconds on modern hardware
solve_sdp — convenience entry point
wvt = solve_sdp(reservoir, plant, weekly_inflows;
price=400.0, n_grid=30, n_cycles=10)Handles the bookkeeping:
- Builds
VolumeGridfrom reservoir bounds - Converts
plant.max_discharge(m³/s) →r_max(Mm³/week) - Estimates
terminal_wvfrom price × average plant efficiency - Calls
run_sdp
Design choices and trade-offs
Why a fine grid search instead of golden-section?
The fine grid search is O(N_search) but completely predictable — no branching, vectorisable, cache-friendly. For 500 points it's ~1 μs per inner call. Golden-section would be faster in theory but more code for marginal gain here.
Why store vf and wv separately?
The value function vf is needed for interpolation during the SDP iteration. The water value wv (marginal derivative) is what callers actually use. Keeping both allows inspection of the raw value function for debugging and validation.
Why NOK/Mm³ rather than NOK/MWh?
The SDP state is volume, not energy. Converting to MWh requires knowing the plant efficiency, which varies with head. Storing in NOK/Mm³ is internally consistent. Callers with access to the plant can convert easily:
energy_yield = power(plant.pq_curve, plant.max_discharge) /
(plant.max_discharge * 3600e-6 * 168) # MWh/Mm³
wv_mwh = lookup(wvt; week=t, volume=v) / energy_yieldWhat to build next (Phase 1.5 / Phase 2)
- Variable head: pass HV curves and update effective head each step
- Seasonal price: replace flat price with a weekly price vector
- Short-term LP (Phase 2): use
lookup_vfas end-condition in JuMP model - Simulation (Phase 3): run Monte Carlo using
lookupas operating policy