1mod 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#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
23pub enum PlanError {
24 #[error("the optimiser found no solution: {0}")]
26 Solver(String),
27 #[error("no market rule: {0}")]
29 Rules(String),
30 #[error("the plan breaks a limit: {0}")]
32 Limits(String),
33}
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)]
37#[serde(rename_all = "lowercase")]
38pub enum Risk {
39 Neutral,
41 Balanced,
43 Cautious,
45}
46
47impl Risk {
48 pub const ALL: [Self; 3] = [Self::Neutral, Self::Balanced, Self::Cautious];
50
51 #[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 #[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 #[must_use]
73 pub fn parse(s: &str) -> Option<Self> {
74 Self::ALL.into_iter().find(|r| r.name() == s)
75 }
76}
77
78#[derive(Debug, Clone, PartialEq, Serialize)]
80pub struct Step {
81 #[serde(with = "time::serde::rfc3339")]
83 pub start: OffsetDateTime,
84 pub charge_mw: f64,
86 pub discharge_mw: f64,
88 pub soc_mwh: f64,
90 pub water_value: f64,
92 pub expected_price: f64,
94 pub low: f64,
96 pub high: f64,
98}
99
100#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
102pub struct Revenue {
103 pub expected: f64,
105 pub p10: f64,
107 pub p90: f64,
109 pub cvar10: f64,
111}
112
113#[derive(Debug, Clone, PartialEq, Serialize)]
115pub struct PoolPlan {
116 pub steps: Vec<Step>,
118 pub orders: Vec<Order>,
120 pub revenue: Revenue,
122 pub idle: bool,
124}
125
126pub 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 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#[derive(Debug, Clone, PartialEq, Serialize)]
207pub struct Outcome {
208 pub fills: Vec<Fill>,
210 pub paper: f64,
212 pub perfect: f64,
214 pub capture: Option<f64>,
216}
217
218pub 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}