Skip to main content

flexpool_plan/
lib.rs

1//! flexpool day-ahead planning: from a forecast to a schedule, water values and limit orders per
2//! battery pool, and their paper result.
3//!
4//! Pure: a forecast, its error correlation, the storage and the market rules in; a plan out. The
5//! linear programme maximises (1 − β)·E(revenue) + β·CVaR 10 % over Gaussian-copula scenarios
6//! (Rockafellar–Uryasev), solved by Clarabel; the energy-balance duals are the water values the
7//! orders are priced from. `f64` stays inside; order volumes and prices leave through
8//! [`flexpool_core::quantize()`].
9
10mod lp;
11mod orders;
12mod scenarios;
13
14use serde::Serialize;
15use time::OffsetDateTime;
16
17pub use lp::{CVAR_ALPHA, SOC_MAX, SOC_MIN, SOC_START, Schedule, Storage, solve};
18pub use orders::{Fill, Market, Order, Side, execute, orders};
19pub use scenarios::{SCENARIOS, draw, inverse_normal, price_at};
20
21/// Why there is no plan.
22#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
23pub enum PlanError {
24    /// The solver did not report a solution.
25    #[error("the optimiser found no solution: {0}")]
26    Solver(String),
27    /// A market rule is missing for the day.
28    #[error("no market rule: {0}")]
29    Rules(String),
30    /// The solution leaves a hard limit.
31    #[error("the plan breaks a limit: {0}")]
32    Limits(String),
33}
34
35/// How much weight the worst 10 % of scenarios get.
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)]
37#[serde(rename_all = "lowercase")]
38pub enum Risk {
39    /// Expected revenue only (β = 0).
40    Neutral,
41    /// Half expected revenue, half CVaR (β = 0.5) — the default.
42    Balanced,
43    /// Mostly CVaR (β = 0.9).
44    Cautious,
45}
46
47impl Risk {
48    /// Every setting.
49    pub const ALL: [Self; 3] = [Self::Neutral, Self::Balanced, Self::Cautious];
50
51    /// β, the CVaR weight.
52    #[must_use]
53    pub const fn beta(self) -> f64 {
54        match self {
55            Self::Neutral => 0.0,
56            Self::Balanced => 0.5,
57            Self::Cautious => 0.9,
58        }
59    }
60
61    /// Its name.
62    #[must_use]
63    pub const fn name(self) -> &'static str {
64        match self {
65            Self::Neutral => "neutral",
66            Self::Balanced => "balanced",
67            Self::Cautious => "cautious",
68        }
69    }
70
71    /// Parses a name.
72    #[must_use]
73    pub fn parse(s: &str) -> Option<Self> {
74        Self::ALL.into_iter().find(|r| r.name() == s)
75    }
76}
77
78/// One market time unit of a pool's plan.
79#[derive(Debug, Clone, PartialEq, Serialize)]
80pub struct Step {
81    /// Start (UTC).
82    #[serde(with = "time::serde::rfc3339")]
83    pub start: OffsetDateTime,
84    /// Charge, MW.
85    pub charge_mw: f64,
86    /// Discharge, MW.
87    pub discharge_mw: f64,
88    /// Energy at the end, MWh.
89    pub soc_mwh: f64,
90    /// Value of one more MWh stored, €/MWh.
91    pub water_value: f64,
92    /// Mean scenario price, €/MWh.
93    pub expected_price: f64,
94    /// Lowest scenario price, €/MWh — a sell's protective limit.
95    pub low: f64,
96    /// Highest scenario price, €/MWh — a buy's protective limit.
97    pub high: f64,
98}
99
100/// Revenue across the scenarios, €.
101#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
102pub struct Revenue {
103    /// Mean.
104    pub expected: f64,
105    /// 10 % quantile.
106    pub p10: f64,
107    /// 90 % quantile.
108    pub p90: f64,
109    /// Mean of the worst 10 %.
110    pub cvar10: f64,
111}
112
113/// A pool's plan.
114#[derive(Debug, Clone, PartialEq, Serialize)]
115pub struct PoolPlan {
116    /// One per market time unit.
117    pub steps: Vec<Step>,
118    /// The orders.
119    pub orders: Vec<Order>,
120    /// Revenue across scenarios.
121    pub revenue: Revenue,
122    /// Nothing to earn after losses: the storage stays idle.
123    pub idle: bool,
124}
125
126/// A plan for `storage` over `scenarios` (one price per unit of `hours`, units starting at `starts`).
127///
128/// # Errors
129/// [`PlanError`] when the problem has no checked solution.
130pub fn plan(
131    storage: &Storage,
132    scenarios: &[Vec<f64>],
133    starts: &[OffsetDateTime],
134    hours: f64,
135    risk: Risk,
136    market: &Market,
137) -> Result<PoolPlan, PlanError> {
138    let schedule = solve(storage, scenarios, hours, risk.beta())?;
139    #[expect(clippy::cast_precision_loss, reason = "a few hundred scenarios")]
140    let s = scenarios.len() as f64;
141    let expected: Vec<f64> = (0..starts.len())
142        .map(|t| scenarios.iter().map(|p| p[t]).sum::<f64>() / s)
143        .collect();
144    let mut revenues: Vec<f64> = scenarios
145        .iter()
146        .map(|p| schedule.revenue(p, storage, hours))
147        .collect();
148    revenues.sort_by(f64::total_cmp);
149    let at = |level: f64| {
150        #[expect(
151            clippy::cast_possible_truncation,
152            clippy::cast_sign_loss,
153            clippy::cast_precision_loss,
154            reason = "an index into a few hundred revenues"
155        )]
156        let i = ((revenues.len() - 1) as f64 * level).round() as usize;
157        revenues[i]
158    };
159    #[expect(
160        clippy::cast_possible_truncation,
161        clippy::cast_sign_loss,
162        clippy::cast_precision_loss,
163        reason = "a count of a few hundred"
164    )]
165    let tail = ((revenues.len() as f64 * CVAR_ALPHA).ceil() as usize).max(1);
166    #[expect(clippy::cast_precision_loss, reason = "a count of a few hundred")]
167    let cvar10 = revenues[..tail].iter().sum::<f64>() / tail as f64;
168    let revenue = Revenue {
169        expected: revenues.iter().sum::<f64>() / s,
170        p10: at(0.1),
171        p90: at(0.9),
172        cvar10,
173    };
174    // The range of prices the scenarios consider possible per unit: the orders' protective limits.
175    let band: Vec<(f64, f64)> = (0..starts.len())
176        .map(|t| {
177            let mut ps: Vec<f64> = scenarios.iter().map(|p| p[t]).collect();
178            ps.sort_by(f64::total_cmp);
179            (ps[0], ps[ps.len() - 1])
180        })
181        .collect();
182    let orders = orders(&schedule, starts, &expected, &band, market)?;
183    let steps = starts
184        .iter()
185        .enumerate()
186        .map(|(t, start)| Step {
187            start: *start,
188            charge_mw: schedule.charge[t],
189            discharge_mw: schedule.discharge[t],
190            soc_mwh: schedule.soc[t],
191            water_value: schedule.water_value[t],
192            expected_price: expected[t],
193            low: band[t].0,
194            high: band[t].1,
195        })
196        .collect();
197    Ok(PoolPlan {
198        idle: orders.is_empty(),
199        steps,
200        orders,
201        revenue,
202    })
203}
204
205/// How a committed plan did against the published prices.
206#[derive(Debug, Clone, PartialEq, Serialize)]
207pub struct Outcome {
208    /// Each order after the auction.
209    pub fills: Vec<Fill>,
210    /// Paper revenue of the orders, €.
211    pub paper: f64,
212    /// The best schedule had the prices been known, €.
213    pub perfect: f64,
214    /// paper ÷ perfect, when perfect is positive.
215    pub capture: Option<f64>,
216}
217
218/// Executes `plan` on paper against `prices` and compares it with perfect foresight.
219///
220/// # Errors
221/// [`PlanError`] if the perfect-foresight problem cannot be solved.
222pub fn evaluate(
223    plan: &PoolPlan,
224    storage: &Storage,
225    starts: &[OffsetDateTime],
226    prices: &[f64],
227    hours: f64,
228) -> Result<Outcome, PlanError> {
229    let (fills, paper) = execute(&plan.orders, starts, prices, storage, hours);
230    let best = solve(storage, &[prices.to_vec()], hours, 0.0)?;
231    let perfect = best.revenue(prices, storage, hours);
232    Ok(Outcome {
233        fills,
234        paper,
235        perfect,
236        capture: (perfect > 1e-6).then(|| paper / perfect),
237    })
238}