flexpool-plan 0.3.0

flexpool day-ahead planning: price scenarios from forecast quantiles, a storage LP with a CVaR term, water values from the duals, limit orders and their paper execution. No I/O.
Documentation
//! The storage linear programme: expected revenue and CVaR, solved by Clarabel.

use clarabel::algebra::CscMatrix;
use clarabel::solver::{
    DefaultSettingsBuilder, DefaultSolver, IPSolver, NonnegativeConeT, SolverStatus,
    SupportedConeT, ZeroConeT,
};

use crate::PlanError;

/// The CVaR tail: the worst 10 % of scenarios.
pub const CVAR_ALPHA: f64 = 0.1;
/// State of charge window as shares of usable energy.
pub const SOC_MIN: f64 = 0.1;
/// Upper end of the window.
pub const SOC_MAX: f64 = 0.9;
/// Start (and minimum end) state of charge as a share of usable energy.
pub const SOC_START: f64 = 0.5;
/// Interior-point iteration bound: deterministic, unlike a time limit.
const MAX_ITER: u32 = 200;

/// One pool's batteries as one storage.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Storage {
    /// Rated power, MW (charge plus discharge never exceed it).
    pub power_mw: f64,
    /// Usable energy, MWh.
    pub energy_mwh: f64,
    /// Round-trip efficiency in (0, 1].
    pub round_trip: f64,
    /// Cost per MWh discharged, €/MWh.
    pub cycle_cost: f64,
}

impl Storage {
    /// Charge efficiency (√ round trip).
    #[must_use]
    pub fn eta_charge(&self) -> f64 {
        self.round_trip.sqrt()
    }

    /// Discharge efficiency (√ round trip).
    #[must_use]
    pub fn eta_discharge(&self) -> f64 {
        self.round_trip.sqrt()
    }

    /// The energy the plan starts with, MWh.
    #[must_use]
    pub fn start_mwh(&self) -> f64 {
        SOC_START * self.energy_mwh
    }
}

/// A solved schedule.
#[derive(Debug, Clone, PartialEq)]
pub struct Schedule {
    /// Charge per interval, MW.
    pub charge: Vec<f64>,
    /// Discharge per interval, MW.
    pub discharge: Vec<f64>,
    /// Energy at the end of each interval, MWh.
    pub soc: Vec<f64>,
    /// The value of one more MWh stored at the end of each interval, €/MWh (the energy-balance duals).
    pub water_value: Vec<f64>,
}

impl Schedule {
    /// Revenue of the schedule at `prices`, € (cycle cost included).
    #[must_use]
    pub fn revenue(&self, prices: &[f64], storage: &Storage, hours: f64) -> f64 {
        prices
            .iter()
            .zip(self.charge.iter().zip(&self.discharge))
            .map(|(p, (c, d))| ((p - storage.cycle_cost) * d - p * c) * hours)
            .sum()
    }
}

/// Solves max (1 − β)·E(R) + β·CVaR₀.₁(R) over `scenarios` (each one price per interval of
/// `hours`).
///
/// # Errors
/// [`PlanError::Solver`] if the solver does not report a solution; [`PlanError::Limits`] if the
/// solution leaves a limit by more than the tolerance.
#[expect(clippy::too_many_lines, reason = "one problem, built in one place")]
pub fn solve(
    storage: &Storage,
    scenarios: &[Vec<f64>],
    hours: f64,
    beta: f64,
) -> Result<Schedule, PlanError> {
    let t_len = scenarios.first().map_or(0, Vec::len);
    let s_len = scenarios.len();
    if t_len == 0 || s_len == 0 {
        return Err(PlanError::Solver("no scenarios".to_owned()));
    }
    let risky = beta > 0.0;
    // Variables: c_t, d_t, e_t, then (risky) the net flow n_t = d_t − c_t, the day's discharge D,
    // η and z_s. The scenario rows read n_t and D only: half as dense as with c_t and d_t.
    let (c, d, e) = (0, t_len, 2 * t_len);
    let net = 3 * t_len;
    let total = net + t_len;
    let eta = total + 1;
    let z = eta + 1;
    let n = if risky { z + s_len } else { 3 * t_len };
    #[expect(clippy::cast_precision_loss, reason = "a few hundred scenarios")]
    let s_f = s_len as f64;
    let mean: Vec<f64> = (0..t_len)
        .map(|t| scenarios.iter().map(|s| s[t]).sum::<f64>() / s_f)
        .collect();
    let (eta_c, eta_d, cost) = (
        storage.eta_charge(),
        storage.eta_discharge(),
        storage.cycle_cost,
    );
    // Minimise the negative objective.
    let mut q = vec![0.0; n];
    for t in 0..t_len {
        q[c + t] = (1.0 - beta) * mean[t] * hours;
        q[d + t] = -(1.0 - beta) * (mean[t] - cost) * hours;
    }
    if risky {
        q[eta] = -beta;
        for s in 0..s_len {
            q[z + s] = beta / (CVAR_ALPHA * s_f);
        }
    }
    let (mut rows, mut cols, mut vals, mut b) = (Vec::new(), Vec::new(), Vec::new(), Vec::new());
    let mut row = 0;
    let mut put = |r: usize, col: usize, v: f64| {
        rows.push(r);
        cols.push(col);
        vals.push(v);
    };
    // Energy balance (zero cone): e_t − e_{t−1} − η_c·Δ·c_t + Δ/η_d·d_t = (e_0 for t = 0).
    for t in 0..t_len {
        put(row, e + t, 1.0);
        if t > 0 {
            put(row, e + t - 1, -1.0);
        }
        put(row, c + t, -eta_c * hours);
        put(row, d + t, hours / eta_d);
        b.push(if t == 0 { storage.start_mwh() } else { 0.0 });
        row += 1;
    }
    if risky {
        // n_t − d_t + c_t = 0 and D − Σ d_t = 0.
        for t in 0..t_len {
            put(row, net + t, 1.0);
            put(row, d + t, -1.0);
            put(row, c + t, 1.0);
            b.push(0.0);
            row += 1;
        }
        put(row, total, 1.0);
        for t in 0..t_len {
            put(row, d + t, -1.0);
        }
        b.push(0.0);
        row += 1;
    }
    let balance_rows = row;
    // Inequalities (nonnegative cone, Ax ≤ b).
    for t in 0..t_len {
        put(row, c + t, -1.0);
        b.push(0.0);
        put(row + 1, d + t, -1.0);
        b.push(0.0);
        put(row + 2, c + t, 1.0);
        put(row + 2, d + t, 1.0);
        b.push(storage.power_mw);
        put(row + 3, e + t, 1.0);
        b.push(SOC_MAX * storage.energy_mwh);
        put(row + 4, e + t, -1.0);
        b.push(-SOC_MIN * storage.energy_mwh);
        row += 5;
    }
    put(row, e + t_len - 1, -1.0);
    b.push(-storage.start_mwh());
    row += 1;
    if risky {
        // η − R_s − z_s ≤ 0 with R_s = Σ p·n_t·Δ − cost·Δ·D, and z_s ≥ 0.
        for (s, prices) in scenarios.iter().enumerate() {
            put(row, eta, 1.0);
            for (t, p) in prices.iter().enumerate() {
                put(row, net + t, -p * hours);
            }
            if cost != 0.0 {
                put(row, total, cost * hours);
            }
            put(row, z + s, -1.0);
            b.push(0.0);
            put(row + 1, z + s, -1.0);
            b.push(0.0);
            row += 2;
        }
    }
    let a = CscMatrix::new_from_triplets(row, n, rows, cols, vals);
    let p = CscMatrix::zeros((n, n));
    let cones: [SupportedConeT<f64>; 2] = [
        ZeroConeT(balance_rows),
        NonnegativeConeT(row - balance_rows),
    ];
    let settings = DefaultSettingsBuilder::default()
        .verbose(false)
        .max_iter(MAX_ITER)
        .build()
        .map_err(|e| PlanError::Solver(e.to_string()))?;
    let mut solver = DefaultSolver::new(&p, &q, &a, &b, &cones, settings)
        .map_err(|e| PlanError::Solver(format!("{e:?}")))?;
    solver.solve();
    let sol = &solver.solution;
    // AlmostSolved: reduced accuracy, still a solution; the limit checks below decide.
    if !matches!(
        sol.status,
        SolverStatus::Solved | SolverStatus::AlmostSolved
    ) {
        return Err(PlanError::Solver(format!("{:?}", sol.status)));
    }
    // Interior-point solutions sit within a tolerance of the bounds: clamp, but refuse real violations.
    let tol = 1e-5 * (1.0 + storage.power_mw.max(storage.energy_mwh));
    let clamp = |v: f64, lo: f64, hi: f64, what: &str| {
        if v < lo - tol || v > hi + tol || !v.is_finite() {
            Err(PlanError::Limits(format!(
                "{what} = {v} outside [{lo}, {hi}]"
            )))
        } else {
            Ok(v.clamp(lo, hi))
        }
    };
    let small = 1e-4 * storage.power_mw;
    let mut schedule = Schedule {
        charge: Vec::with_capacity(t_len),
        discharge: Vec::with_capacity(t_len),
        soc: Vec::with_capacity(t_len),
        water_value: sol.z[..t_len].to_vec(),
    };
    for t in 0..t_len {
        let mut ct = clamp(sol.x[c + t], 0.0, storage.power_mw, "charge")?;
        let mut dt = clamp(sol.x[d + t], 0.0, storage.power_mw, "discharge")?;
        if ct < small {
            ct = 0.0;
        }
        if dt < small {
            dt = 0.0;
        }
        if ct + dt > storage.power_mw + tol {
            return Err(PlanError::Limits(format!(
                "charge + discharge = {} above {}",
                ct + dt,
                storage.power_mw
            )));
        }
        schedule.charge.push(ct);
        schedule.discharge.push(dt);
    }
    // The state of charge follows from the rounded flows, so it is exactly consistent with them.
    let mut level = storage.start_mwh();
    for t in 0..t_len {
        level += eta_c * hours * schedule.charge[t] - hours / eta_d * schedule.discharge[t];
        let lo = SOC_MIN * storage.energy_mwh;
        let hi = SOC_MAX * storage.energy_mwh;
        level = clamp(level, lo, hi, "state of charge")?;
        schedule.soc.push(level);
    }
    Ok(schedule)
}