Skip to main content

flexpool_plan/
lp.rs

1//! The storage linear programme: expected revenue and CVaR, solved by Clarabel.
2
3use clarabel::algebra::CscMatrix;
4use clarabel::solver::{
5    DefaultSettingsBuilder, DefaultSolver, IPSolver, NonnegativeConeT, SolverStatus,
6    SupportedConeT, ZeroConeT,
7};
8
9use crate::PlanError;
10
11/// The CVaR tail: the worst 10 % of scenarios.
12pub const CVAR_ALPHA: f64 = 0.1;
13/// State of charge window as shares of usable energy.
14pub const SOC_MIN: f64 = 0.1;
15/// Upper end of the window.
16pub const SOC_MAX: f64 = 0.9;
17/// Start (and minimum end) state of charge as a share of usable energy.
18pub const SOC_START: f64 = 0.5;
19/// Interior-point iteration bound: deterministic, unlike a time limit.
20const MAX_ITER: u32 = 200;
21
22/// One pool's batteries as one storage.
23#[derive(Debug, Clone, Copy, PartialEq)]
24pub struct Storage {
25    /// Rated power, MW (charge plus discharge never exceed it).
26    pub power_mw: f64,
27    /// Usable energy, MWh.
28    pub energy_mwh: f64,
29    /// Round-trip efficiency in (0, 1].
30    pub round_trip: f64,
31    /// Cost per MWh discharged, €/MWh.
32    pub cycle_cost: f64,
33}
34
35impl Storage {
36    /// Charge efficiency (√ round trip).
37    #[must_use]
38    pub fn eta_charge(&self) -> f64 {
39        self.round_trip.sqrt()
40    }
41
42    /// Discharge efficiency (√ round trip).
43    #[must_use]
44    pub fn eta_discharge(&self) -> f64 {
45        self.round_trip.sqrt()
46    }
47
48    /// The energy the plan starts with, MWh.
49    #[must_use]
50    pub fn start_mwh(&self) -> f64 {
51        SOC_START * self.energy_mwh
52    }
53}
54
55/// A solved schedule.
56#[derive(Debug, Clone, PartialEq)]
57pub struct Schedule {
58    /// Charge per interval, MW.
59    pub charge: Vec<f64>,
60    /// Discharge per interval, MW.
61    pub discharge: Vec<f64>,
62    /// Energy at the end of each interval, MWh.
63    pub soc: Vec<f64>,
64    /// The value of one more MWh stored at the end of each interval, €/MWh (the energy-balance duals).
65    pub water_value: Vec<f64>,
66}
67
68impl Schedule {
69    /// Revenue of the schedule at `prices`, € (cycle cost included).
70    #[must_use]
71    pub fn revenue(&self, prices: &[f64], storage: &Storage, hours: f64) -> f64 {
72        prices
73            .iter()
74            .zip(self.charge.iter().zip(&self.discharge))
75            .map(|(p, (c, d))| ((p - storage.cycle_cost) * d - p * c) * hours)
76            .sum()
77    }
78}
79
80/// Solves max (1 − β)·E(R) + β·CVaR₀.₁(R) over `scenarios` (each one price per interval of
81/// `hours`).
82///
83/// # Errors
84/// [`PlanError::Solver`] if the solver does not report a solution; [`PlanError::Limits`] if the
85/// solution leaves a limit by more than the tolerance.
86#[expect(clippy::too_many_lines, reason = "one problem, built in one place")]
87pub fn solve(
88    storage: &Storage,
89    scenarios: &[Vec<f64>],
90    hours: f64,
91    beta: f64,
92) -> Result<Schedule, PlanError> {
93    let t_len = scenarios.first().map_or(0, Vec::len);
94    let s_len = scenarios.len();
95    if t_len == 0 || s_len == 0 {
96        return Err(PlanError::Solver("no scenarios".to_owned()));
97    }
98    let risky = beta > 0.0;
99    // Variables: c_t, d_t, e_t, then (risky) the net flow n_t = d_t − c_t, the day's discharge D,
100    // η and z_s. The scenario rows read n_t and D only: half as dense as with c_t and d_t.
101    let (c, d, e) = (0, t_len, 2 * t_len);
102    let net = 3 * t_len;
103    let total = net + t_len;
104    let eta = total + 1;
105    let z = eta + 1;
106    let n = if risky { z + s_len } else { 3 * t_len };
107    #[expect(clippy::cast_precision_loss, reason = "a few hundred scenarios")]
108    let s_f = s_len as f64;
109    let mean: Vec<f64> = (0..t_len)
110        .map(|t| scenarios.iter().map(|s| s[t]).sum::<f64>() / s_f)
111        .collect();
112    let (eta_c, eta_d, cost) = (
113        storage.eta_charge(),
114        storage.eta_discharge(),
115        storage.cycle_cost,
116    );
117    // Minimise the negative objective.
118    let mut q = vec![0.0; n];
119    for t in 0..t_len {
120        q[c + t] = (1.0 - beta) * mean[t] * hours;
121        q[d + t] = -(1.0 - beta) * (mean[t] - cost) * hours;
122    }
123    if risky {
124        q[eta] = -beta;
125        for s in 0..s_len {
126            q[z + s] = beta / (CVAR_ALPHA * s_f);
127        }
128    }
129    let (mut rows, mut cols, mut vals, mut b) = (Vec::new(), Vec::new(), Vec::new(), Vec::new());
130    let mut row = 0;
131    let mut put = |r: usize, col: usize, v: f64| {
132        rows.push(r);
133        cols.push(col);
134        vals.push(v);
135    };
136    // Energy balance (zero cone): e_t − e_{t−1} − η_c·Δ·c_t + Δ/η_d·d_t = (e_0 for t = 0).
137    for t in 0..t_len {
138        put(row, e + t, 1.0);
139        if t > 0 {
140            put(row, e + t - 1, -1.0);
141        }
142        put(row, c + t, -eta_c * hours);
143        put(row, d + t, hours / eta_d);
144        b.push(if t == 0 { storage.start_mwh() } else { 0.0 });
145        row += 1;
146    }
147    if risky {
148        // n_t − d_t + c_t = 0 and D − Σ d_t = 0.
149        for t in 0..t_len {
150            put(row, net + t, 1.0);
151            put(row, d + t, -1.0);
152            put(row, c + t, 1.0);
153            b.push(0.0);
154            row += 1;
155        }
156        put(row, total, 1.0);
157        for t in 0..t_len {
158            put(row, d + t, -1.0);
159        }
160        b.push(0.0);
161        row += 1;
162    }
163    let balance_rows = row;
164    // Inequalities (nonnegative cone, Ax ≤ b).
165    for t in 0..t_len {
166        put(row, c + t, -1.0);
167        b.push(0.0);
168        put(row + 1, d + t, -1.0);
169        b.push(0.0);
170        put(row + 2, c + t, 1.0);
171        put(row + 2, d + t, 1.0);
172        b.push(storage.power_mw);
173        put(row + 3, e + t, 1.0);
174        b.push(SOC_MAX * storage.energy_mwh);
175        put(row + 4, e + t, -1.0);
176        b.push(-SOC_MIN * storage.energy_mwh);
177        row += 5;
178    }
179    put(row, e + t_len - 1, -1.0);
180    b.push(-storage.start_mwh());
181    row += 1;
182    if risky {
183        // η − R_s − z_s ≤ 0 with R_s = Σ p·n_t·Δ − cost·Δ·D, and z_s ≥ 0.
184        for (s, prices) in scenarios.iter().enumerate() {
185            put(row, eta, 1.0);
186            for (t, p) in prices.iter().enumerate() {
187                put(row, net + t, -p * hours);
188            }
189            if cost != 0.0 {
190                put(row, total, cost * hours);
191            }
192            put(row, z + s, -1.0);
193            b.push(0.0);
194            put(row + 1, z + s, -1.0);
195            b.push(0.0);
196            row += 2;
197        }
198    }
199    let a = CscMatrix::new_from_triplets(row, n, rows, cols, vals);
200    let p = CscMatrix::zeros((n, n));
201    let cones: [SupportedConeT<f64>; 2] = [
202        ZeroConeT(balance_rows),
203        NonnegativeConeT(row - balance_rows),
204    ];
205    let settings = DefaultSettingsBuilder::default()
206        .verbose(false)
207        .max_iter(MAX_ITER)
208        .build()
209        .map_err(|e| PlanError::Solver(e.to_string()))?;
210    let mut solver = DefaultSolver::new(&p, &q, &a, &b, &cones, settings)
211        .map_err(|e| PlanError::Solver(format!("{e:?}")))?;
212    solver.solve();
213    let sol = &solver.solution;
214    // AlmostSolved: reduced accuracy, still a solution; the limit checks below decide.
215    if !matches!(
216        sol.status,
217        SolverStatus::Solved | SolverStatus::AlmostSolved
218    ) {
219        return Err(PlanError::Solver(format!("{:?}", sol.status)));
220    }
221    // Interior-point solutions sit within a tolerance of the bounds: clamp, but refuse real violations.
222    let tol = 1e-5 * (1.0 + storage.power_mw.max(storage.energy_mwh));
223    let clamp = |v: f64, lo: f64, hi: f64, what: &str| {
224        if v < lo - tol || v > hi + tol || !v.is_finite() {
225            Err(PlanError::Limits(format!(
226                "{what} = {v} outside [{lo}, {hi}]"
227            )))
228        } else {
229            Ok(v.clamp(lo, hi))
230        }
231    };
232    let small = 1e-4 * storage.power_mw;
233    let mut schedule = Schedule {
234        charge: Vec::with_capacity(t_len),
235        discharge: Vec::with_capacity(t_len),
236        soc: Vec::with_capacity(t_len),
237        water_value: sol.z[..t_len].to_vec(),
238    };
239    for t in 0..t_len {
240        let mut ct = clamp(sol.x[c + t], 0.0, storage.power_mw, "charge")?;
241        let mut dt = clamp(sol.x[d + t], 0.0, storage.power_mw, "discharge")?;
242        if ct < small {
243            ct = 0.0;
244        }
245        if dt < small {
246            dt = 0.0;
247        }
248        if ct + dt > storage.power_mw + tol {
249            return Err(PlanError::Limits(format!(
250                "charge + discharge = {} above {}",
251                ct + dt,
252                storage.power_mw
253            )));
254        }
255        schedule.charge.push(ct);
256        schedule.discharge.push(dt);
257    }
258    // The state of charge follows from the rounded flows, so it is exactly consistent with them.
259    let mut level = storage.start_mwh();
260    for t in 0..t_len {
261        level += eta_c * hours * schedule.charge[t] - hours / eta_d * schedule.discharge[t];
262        let lo = SOC_MIN * storage.energy_mwh;
263        let hi = SOC_MAX * storage.energy_mwh;
264        level = clamp(level, lo, hi, "state of charge")?;
265        schedule.soc.push(level);
266    }
267    Ok(schedule)
268}