Skip to main content

flexpool_sim/
replay.rs

1//! One scenario day replayed: rules, clock and bitemporal market data together.
2
3use std::fmt::Write as _;
4
5use flexpool_core::{BusinessDay, EurPerMwh};
6use flexpool_rules::{Entry, RuleBook};
7use rust_decimal::Decimal;
8use time::OffsetDateTime;
9
10use crate::clock::{Clock, Event, EventKind};
11use crate::import::{self, ImportProblem};
12use crate::scenario::{MarketSource, Scenario};
13use crate::series::{Series, View};
14use crate::synthetic;
15
16/// An instant as Berlin local time with its offset, e.g. `2025-10-01 12:00 +02:00` — how
17/// operators read gate times.
18#[must_use]
19pub fn berlin(t: OffsetDateTime) -> String {
20    let local = flexpool_core::calendar::to_berlin(t);
21    let fmt = time::macros::format_description!(
22        "[year]-[month]-[day] [hour]:[minute] [offset_hour sign:mandatory]:[offset_minute]"
23    );
24    local.format(fmt).unwrap_or_else(|_| t.to_string())
25}
26
27/// Why a replay could not be built.
28#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
29pub enum ReplayError {
30    /// A rule needed for the day is missing.
31    #[error(transparent)]
32    Rule(#[from] flexpool_rules::Missing),
33    /// The calendar does not cover the day.
34    #[error(transparent)]
35    Calendar(#[from] flexpool_core::CalendarError),
36    /// The data file is invalid.
37    #[error("data file: {}", .0.iter().map(ToString::to_string).collect::<Vec<_>>().join("; "))]
38    Data(Vec<ImportProblem>),
39    /// A data file source but no data text was given.
40    #[error("the scenario names a data file but none was loaded")]
41    NoData,
42}
43
44/// The day-ahead result as known at an instant.
45#[derive(Debug, Clone, serde::Serialize)]
46pub struct DayAhead<'a> {
47    /// The delivery day.
48    pub day: time::Date,
49    /// Market time unit in minutes.
50    pub mtu_minutes: u16,
51    /// The rule entry that set the time unit.
52    pub mtu_rule: &'a Entry,
53    /// When the prices became known.
54    #[serde(with = "time::serde::rfc3339")]
55    pub known_at: OffsetDateTime,
56    /// The prices in time order.
57    pub prices: Vec<&'a crate::series::Observation>,
58}
59
60/// A replayed scenario day.
61#[derive(Debug, Clone)]
62pub struct Replay {
63    scenario: Scenario,
64    rules: RuleBook,
65    clock: Clock,
66    prices: Series,
67    day: BusinessDay,
68    mtu: u16,
69    publication: OffsetDateTime,
70}
71
72impl Replay {
73    /// Builds the replay of `scenario`. `data` is the text of the scenario's data file, if any.
74    ///
75    /// # Errors
76    /// [`ReplayError`] if a rule is missing for the day or the data is invalid.
77    pub fn new(
78        scenario: Scenario,
79        rules: RuleBook,
80        data: Option<&str>,
81    ) -> Result<Self, ReplayError> {
82        let day = BusinessDay::new(scenario.day)?;
83        let (mtu, _) = rules.da_mtu(day.date())?;
84        let (min, max, _) = rules.da_price_limits(day.date())?;
85        let (step, _) = rules.granularity("da.price-granularity", day.date())?;
86        let (publication, _) = rules.gate("da.publication", day.date())?;
87        let rows = match &scenario.market {
88            MarketSource::Synthetic { seed, .. } => {
89                synthetic::day_ahead(&day, mtu, *seed, step, (min, max))
90            }
91            MarketSource::File { .. } => {
92                let text = data.ok_or(ReplayError::NoData)?;
93                import::day_ahead_csv(text, &day, mtu, (min, max)).map_err(ReplayError::Data)?
94            }
95        };
96        let mut prices = Series::new();
97        for (start, price) in rows {
98            // One version per interval in a fresh series: insertion cannot fail.
99            let _ = prices.insert(start, mtu, price, publication);
100        }
101        // Earlier days, each with its own rules (hourly before the 15-minute go-live) and known
102        // from its own publication: the history forecasts learn from — never ahead of the clock.
103        if let MarketSource::Synthetic { seed, history_days } = &scenario.market {
104            let mut date = day.date();
105            for _ in 0..*history_days {
106                let Some(earlier) = date.previous_day() else {
107                    break;
108                };
109                date = earlier;
110                let Ok(d) = BusinessDay::new(date) else { break };
111                let (Ok((m, _)), Ok((lo, hi, _)), Ok((st, _)), Ok((published, _))) = (
112                    rules.da_mtu(date),
113                    rules.da_price_limits(date),
114                    rules.granularity("da.price-granularity", date),
115                    rules.gate("da.publication", date),
116                ) else {
117                    break; // before the rules' validity: no history is invented
118                };
119                for (start, price) in synthetic::day_ahead(&d, m, *seed, st, (lo, hi)) {
120                    let _ = prices.insert(start, m, price, published);
121                }
122            }
123        }
124        let mut events = vec![
125            Event {
126                at: publication,
127                kind: EventKind::Published("da.prices".into()),
128            },
129            Event {
130                at: day.start(),
131                kind: EventKind::DayStarted,
132            },
133            Event {
134                at: day.end(),
135                kind: EventKind::DayEnded,
136            },
137        ];
138        for gate in ["da.gate", "ida1.gate", "ida2.gate", "ida3.gate"] {
139            if let Ok((at, _)) = rules.gate(gate, day.date()) {
140                events.push(Event {
141                    at,
142                    kind: EventKind::GateClosed(gate.into()),
143                });
144            }
145        }
146        let clock = Clock::new(scenario.start, scenario.end, events);
147        Ok(Self {
148            scenario,
149            rules,
150            clock,
151            prices,
152            day,
153            mtu,
154            publication,
155        })
156    }
157
158    /// The scenario.
159    #[must_use]
160    pub const fn scenario(&self) -> &Scenario {
161        &self.scenario
162    }
163
164    /// The rules.
165    #[must_use]
166    pub const fn rules(&self) -> &RuleBook {
167        &self.rules
168    }
169
170    /// The clock.
171    #[must_use]
172    pub const fn clock(&self) -> &Clock {
173        &self.clock
174    }
175
176    /// The clock, to move it.
177    pub const fn clock_mut(&mut self) -> &mut Clock {
178        &mut self.clock
179    }
180
181    /// The bitemporal day-ahead prices: the replayed day and its history.
182    #[must_use]
183    pub const fn series(&self) -> &Series {
184        &self.prices
185    }
186
187    /// The delivery day replayed.
188    #[must_use]
189    pub const fn business_day(&self) -> &BusinessDay {
190        &self.day
191    }
192
193    /// A view of the market data at the clock's instant.
194    #[must_use]
195    pub fn view(&self) -> View<'_> {
196        self.prices.at(self.clock.now())
197    }
198
199    /// When the day-ahead prices are published.
200    #[must_use]
201    pub const fn publication(&self) -> OffsetDateTime {
202        self.publication
203    }
204
205    /// The day-ahead result as known now, or `None` before publication.
206    #[must_use]
207    pub fn day_ahead(&self) -> Option<DayAhead<'_>> {
208        let prices = self.view().range(self.day.start(), self.day.end());
209        if prices.is_empty() {
210            return None;
211        }
212        let mtu_rule = self.rules.da_mtu(self.day.date()).ok()?.1;
213        Some(DayAhead {
214            day: self.day.date(),
215            mtu_minutes: self.mtu,
216            mtu_rule,
217            known_at: self.publication,
218            prices,
219        })
220    }
221
222    /// Runs to the end and returns a deterministic summary.
223    #[must_use]
224    pub fn run_to_end(mut self) -> String {
225        let mut out = String::new();
226        let s = &self.scenario;
227        let mtu_entry = self.rules.da_mtu(self.day.date()).map(|(_, e)| e.clone());
228        let _ = writeln!(out, "scenario  {}\nday       {}", s.name, s.day);
229        if let Ok(e) = &mtu_entry {
230            let status = self
231                .rules
232                .source_of(e)
233                .map_or("?".to_owned(), |src| src.status.to_string());
234            let _ = writeln!(
235                out,
236                "mtu       {} min  (rule {} from {}, source {} [{status}])",
237                self.mtu, e.id, e.valid_from, e.source
238            );
239        }
240        let _ = writeln!(out, "start     {}\nevents", berlin(self.clock.now()));
241        while !self.clock.finished() {
242            for e in self.clock.advance_next() {
243                let what = match &e.kind {
244                    EventKind::GateClosed(id) => format!("gate closed  {id}"),
245                    EventKind::Published(id) => format!("published    {id}"),
246                    EventKind::DayStarted => "day started".to_owned(),
247                    EventKind::DayEnded => "day ended".to_owned(),
248                };
249                let _ = writeln!(out, "  {}  {what}", berlin(e.at));
250            }
251        }
252        if let Some(da) = self.day_ahead() {
253            let values: Vec<Decimal> = da.prices.iter().map(|o| o.value.value()).collect();
254            let n = Decimal::from(values.len());
255            let min = values.iter().min().copied().unwrap_or_default();
256            let max = values.iter().max().copied().unwrap_or_default();
257            let mean = values
258                .iter()
259                .sum::<Decimal>()
260                .checked_div(n)
261                .unwrap_or_default()
262                .round_dp(2);
263            let negative = values
264                .iter()
265                .filter(|v| v.is_sign_negative() && !v.is_zero())
266                .count();
267            let _ = writeln!(
268                out,
269                "prices    {} intervals  min {}  mean {}  max {}  negative {}",
270                values.len(),
271                EurPerMwh::new(min),
272                EurPerMwh::new(mean),
273                EurPerMwh::new(max),
274                negative
275            );
276        }
277        let _ = writeln!(out, "end       {}", berlin(self.clock.now()));
278        out
279    }
280}