flexpool-plan 0.4.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
//! flexpool day-ahead planning: from a forecast to a schedule, water values and limit orders per
//! battery pool, and their paper result.
//!
//! Pure: a forecast, its error correlation, the storage and the market rules in; a plan out. The
//! linear programme maximises (1 − β)·E(revenue) + β·CVaR 10 % over Gaussian-copula scenarios
//! (Rockafellar–Uryasev), solved by Clarabel; the energy-balance duals are the water values the
//! orders are priced from. `f64` stays inside; order volumes and prices leave through
//! [`flexpool_core::quantize()`].

mod lp;
mod orders;
mod scenarios;

use serde::Serialize;
use time::OffsetDateTime;

pub use lp::{CVAR_ALPHA, SOC_MAX, SOC_MIN, SOC_START, Schedule, Storage, solve};
pub use orders::{Fill, Market, Order, Side, execute, orders};
pub use scenarios::{SCENARIOS, draw, inverse_normal, price_at};

/// Why there is no plan.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum PlanError {
    /// The solver did not report a solution.
    #[error("the optimiser found no solution: {0}")]
    Solver(String),
    /// A market rule is missing for the day.
    #[error("no market rule: {0}")]
    Rules(String),
    /// The solution leaves a hard limit.
    #[error("the plan breaks a limit: {0}")]
    Limits(String),
}

/// How much weight the worst 10 % of scenarios get.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Risk {
    /// Expected revenue only (β = 0).
    Neutral,
    /// Half expected revenue, half CVaR (β = 0.5) — the default.
    Balanced,
    /// Mostly CVaR (β = 0.9).
    Cautious,
}

impl Risk {
    /// Every setting.
    pub const ALL: [Self; 3] = [Self::Neutral, Self::Balanced, Self::Cautious];

    /// β, the CVaR weight.
    #[must_use]
    pub const fn beta(self) -> f64 {
        match self {
            Self::Neutral => 0.0,
            Self::Balanced => 0.5,
            Self::Cautious => 0.9,
        }
    }

    /// Its name.
    #[must_use]
    pub const fn name(self) -> &'static str {
        match self {
            Self::Neutral => "neutral",
            Self::Balanced => "balanced",
            Self::Cautious => "cautious",
        }
    }

    /// Parses a name.
    #[must_use]
    pub fn parse(s: &str) -> Option<Self> {
        Self::ALL.into_iter().find(|r| r.name() == s)
    }
}

/// One market time unit of a pool's plan.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Step {
    /// Start (UTC).
    #[serde(with = "time::serde::rfc3339")]
    pub start: OffsetDateTime,
    /// Charge, MW.
    pub charge_mw: f64,
    /// Discharge, MW.
    pub discharge_mw: f64,
    /// Energy at the end, MWh.
    pub soc_mwh: f64,
    /// Value of one more MWh stored, €/MWh.
    pub water_value: f64,
    /// Mean scenario price, €/MWh.
    pub expected_price: f64,
    /// Lowest scenario price, €/MWh — a sell's protective limit.
    pub low: f64,
    /// Highest scenario price, €/MWh — a buy's protective limit.
    pub high: f64,
}

/// Revenue across the scenarios, €.
#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
pub struct Revenue {
    /// Mean.
    pub expected: f64,
    /// 10 % quantile.
    pub p10: f64,
    /// 90 % quantile.
    pub p90: f64,
    /// Mean of the worst 10 %.
    pub cvar10: f64,
}

/// A pool's plan.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct PoolPlan {
    /// One per market time unit.
    pub steps: Vec<Step>,
    /// The orders.
    pub orders: Vec<Order>,
    /// Revenue across scenarios.
    pub revenue: Revenue,
    /// Nothing to earn after losses: the storage stays idle.
    pub idle: bool,
}

/// A plan for `storage` over `scenarios` (one price per unit of `hours`, units starting at `starts`).
///
/// # Errors
/// [`PlanError`] when the problem has no checked solution.
pub fn plan(
    storage: &Storage,
    scenarios: &[Vec<f64>],
    starts: &[OffsetDateTime],
    hours: f64,
    risk: Risk,
    market: &Market,
) -> Result<PoolPlan, PlanError> {
    let schedule = solve(storage, scenarios, hours, risk.beta())?;
    #[expect(clippy::cast_precision_loss, reason = "a few hundred scenarios")]
    let s = scenarios.len() as f64;
    let expected: Vec<f64> = (0..starts.len())
        .map(|t| scenarios.iter().map(|p| p[t]).sum::<f64>() / s)
        .collect();
    let mut revenues: Vec<f64> = scenarios
        .iter()
        .map(|p| schedule.revenue(p, storage, hours))
        .collect();
    revenues.sort_by(f64::total_cmp);
    let at = |level: f64| {
        #[expect(
            clippy::cast_possible_truncation,
            clippy::cast_sign_loss,
            clippy::cast_precision_loss,
            reason = "an index into a few hundred revenues"
        )]
        let i = ((revenues.len() - 1) as f64 * level).round() as usize;
        revenues[i]
    };
    #[expect(
        clippy::cast_possible_truncation,
        clippy::cast_sign_loss,
        clippy::cast_precision_loss,
        reason = "a count of a few hundred"
    )]
    let tail = ((revenues.len() as f64 * CVAR_ALPHA).ceil() as usize).max(1);
    #[expect(clippy::cast_precision_loss, reason = "a count of a few hundred")]
    let cvar10 = revenues[..tail].iter().sum::<f64>() / tail as f64;
    let revenue = Revenue {
        expected: revenues.iter().sum::<f64>() / s,
        p10: at(0.1),
        p90: at(0.9),
        cvar10,
    };
    // The range of prices the scenarios consider possible per unit: the orders' protective limits.
    let band: Vec<(f64, f64)> = (0..starts.len())
        .map(|t| {
            let mut ps: Vec<f64> = scenarios.iter().map(|p| p[t]).collect();
            ps.sort_by(f64::total_cmp);
            (ps[0], ps[ps.len() - 1])
        })
        .collect();
    let orders = orders(&schedule, starts, &expected, &band, market)?;
    let steps = starts
        .iter()
        .enumerate()
        .map(|(t, start)| Step {
            start: *start,
            charge_mw: schedule.charge[t],
            discharge_mw: schedule.discharge[t],
            soc_mwh: schedule.soc[t],
            water_value: schedule.water_value[t],
            expected_price: expected[t],
            low: band[t].0,
            high: band[t].1,
        })
        .collect();
    Ok(PoolPlan {
        idle: orders.is_empty(),
        steps,
        orders,
        revenue,
    })
}

/// How a committed plan did against the published prices.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Outcome {
    /// Each order after the auction.
    pub fills: Vec<Fill>,
    /// Paper revenue of the orders, €.
    pub paper: f64,
    /// The best schedule had the prices been known, €.
    pub perfect: f64,
    /// paper ÷ perfect, when perfect is positive.
    pub capture: Option<f64>,
}

/// Executes `plan` on paper against `prices` and compares it with perfect foresight.
///
/// # Errors
/// [`PlanError`] if the perfect-foresight problem cannot be solved.
pub fn evaluate(
    plan: &PoolPlan,
    storage: &Storage,
    starts: &[OffsetDateTime],
    prices: &[f64],
    hours: f64,
) -> Result<Outcome, PlanError> {
    let (fills, paper) = execute(&plan.orders, starts, prices, storage, hours);
    let best = solve(storage, &[prices.to_vec()], hours, 0.0)?;
    let perfect = best.revenue(prices, storage, hours);
    Ok(Outcome {
        fills,
        paper,
        perfect,
        capture: (perfect > 1e-6).then(|| paper / perfect),
    })
}