Skip to main content

flexpool_sim/
series.rs

1//! Bitemporal series: every value knows the interval it is about and the instant it became known.
2//!
3//! A [`View`] is fixed to a decision instant and returns, per interval, the latest revision known
4//! at that instant. An interval whose every version became known later is refused with
5//! [`LookAhead`]. This is what makes a replay honest: a decision at 12:00 cannot read a price
6//! published at 12:57.
7
8use std::collections::BTreeMap;
9
10use flexpool_core::EurPerMwh;
11use serde::Serialize;
12use time::OffsetDateTime;
13
14/// One value about one interval, as known from `known_at`.
15#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
16pub struct Observation {
17    /// Interval start (UTC).
18    #[serde(with = "time::serde::rfc3339")]
19    pub start: OffsetDateTime,
20    /// Interval length in minutes.
21    pub minutes: u16,
22    /// The value.
23    pub value: EurPerMwh,
24    /// From when this version was known.
25    #[serde(with = "time::serde::rfc3339")]
26    pub known_at: OffsetDateTime,
27    /// 0 for the first version, then 1, 2, …
28    pub revision: u32,
29}
30
31/// A read of a value that was not yet known at the view's instant.
32#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
33#[error(
34    "look-ahead: the value for {start} is known only from {known_at}, after the decision instant {at}"
35)]
36pub struct LookAhead {
37    /// The interval asked for.
38    pub start: OffsetDateTime,
39    /// The earliest instant any version of it is known.
40    pub known_at: OffsetDateTime,
41    /// The view's decision instant.
42    pub at: OffsetDateTime,
43}
44
45/// An insertion that would rewrite history.
46#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
47#[error("a revision of {start} must be known after {previous}, got {known_at}")]
48pub struct NotLater {
49    /// The interval.
50    pub start: OffsetDateTime,
51    /// The last version's knowledge instant.
52    pub previous: OffsetDateTime,
53    /// The rejected knowledge instant.
54    pub known_at: OffsetDateTime,
55}
56
57/// A bitemporal series keyed by interval start.
58#[derive(Debug, Clone, Default)]
59pub struct Series {
60    versions: BTreeMap<OffsetDateTime, Vec<Observation>>,
61}
62
63impl Series {
64    /// An empty series.
65    #[must_use]
66    pub fn new() -> Self {
67        Self::default()
68    }
69
70    /// Adds a version; its revision number is assigned. History only grows forward.
71    ///
72    /// # Errors
73    /// [`NotLater`] if a version of the interval known at the same or a later instant exists.
74    pub fn insert(
75        &mut self,
76        start: OffsetDateTime,
77        minutes: u16,
78        value: EurPerMwh,
79        known_at: OffsetDateTime,
80    ) -> Result<(), NotLater> {
81        let list = self.versions.entry(start).or_default();
82        if let Some(last) = list.last()
83            && known_at <= last.known_at
84        {
85            return Err(NotLater {
86                start,
87                previous: last.known_at,
88                known_at,
89            });
90        }
91        let revision = u32::try_from(list.len()).unwrap_or(u32::MAX);
92        list.push(Observation {
93            start,
94            minutes,
95            value,
96            known_at,
97            revision,
98        });
99        Ok(())
100    }
101
102    /// A read view fixed to the decision instant `at`.
103    #[must_use]
104    pub fn at(&self, at: OffsetDateTime) -> View<'_> {
105        View { series: self, at }
106    }
107}
108
109/// A read view of a [`Series`] at a decision instant.
110#[derive(Debug, Clone, Copy)]
111pub struct View<'a> {
112    series: &'a Series,
113    at: OffsetDateTime,
114}
115
116impl<'a> View<'a> {
117    /// The decision instant.
118    #[must_use]
119    pub const fn instant(&self) -> OffsetDateTime {
120        self.at
121    }
122
123    /// The latest version of the interval starting at `start` known at the decision instant.
124    ///
125    /// # Errors
126    /// [`LookAhead`] if versions exist but none was known yet. `Ok(None)` if the interval has no
127    /// version at all.
128    pub fn get(&self, start: OffsetDateTime) -> Result<Option<&'a Observation>, LookAhead> {
129        let series: &'a Series = self.series;
130        let Some(list) = series.versions.get(&start) else {
131            return Ok(None);
132        };
133        match list.iter().rev().find(|o| o.known_at <= self.at) {
134            Some(o) => Ok(Some(o)),
135            None => Err(LookAhead {
136                start,
137                known_at: list[0].known_at,
138                at: self.at,
139            }),
140        }
141    }
142
143    /// The interval that *contains* `instant` (an hourly price for a quarter-hour instant), latest
144    /// version known at the decision instant.
145    ///
146    /// # Errors
147    /// [`LookAhead`] if that interval exists but no version was known yet. `Ok(None)` if no interval
148    /// covers the instant.
149    pub fn containing(
150        &self,
151        instant: OffsetDateTime,
152    ) -> Result<Option<&'a Observation>, LookAhead> {
153        let series: &'a Series = self.series;
154        let Some((start, list)) = series.versions.range(..=instant).next_back() else {
155            return Ok(None);
156        };
157        let covers = list
158            .first()
159            .is_some_and(|o| instant < o.start + time::Duration::minutes(i64::from(o.minutes)));
160        if !covers {
161            return Ok(None);
162        }
163        match list.iter().rev().find(|o| o.known_at <= self.at) {
164            Some(o) => Ok(Some(o)),
165            None => Err(LookAhead {
166                start: *start,
167                known_at: list[0].known_at,
168                at: self.at,
169            }),
170        }
171    }
172
173    /// Every interval in `[from, to)` with its latest version known at the decision instant;
174    /// intervals not yet known are left out.
175    #[must_use]
176    pub fn range(&self, from: OffsetDateTime, to: OffsetDateTime) -> Vec<&'a Observation> {
177        let (series, at): (&'a Series, _) = (self.series, self.at);
178        series
179            .versions
180            .range(from..to)
181            .filter_map(|(_, list)| list.iter().rev().find(|o| o.known_at <= at))
182            .collect()
183    }
184}