flexpool-sim 0.5.0

flexpool replay: bitemporal series with decision-time views, synthetic and imported market days, scenarios and a forward-only test clock. No I/O, no real clock.
Documentation
//! Bitemporal series: every value knows the interval it is about and the instant it became known.
//!
//! A [`View`] is fixed to a decision instant and returns, per interval, the latest revision known
//! at that instant. An interval whose every version became known later is refused with
//! [`LookAhead`]. This is what makes a replay honest: a decision at 12:00 cannot read a price
//! published at 12:57.

use std::collections::BTreeMap;

use flexpool_core::EurPerMwh;
use serde::Serialize;
use time::OffsetDateTime;

/// One value about one interval, as known from `known_at`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Observation {
    /// Interval start (UTC).
    #[serde(with = "time::serde::rfc3339")]
    pub start: OffsetDateTime,
    /// Interval length in minutes.
    pub minutes: u16,
    /// The value.
    pub value: EurPerMwh,
    /// From when this version was known.
    #[serde(with = "time::serde::rfc3339")]
    pub known_at: OffsetDateTime,
    /// 0 for the first version, then 1, 2, …
    pub revision: u32,
}

/// A read of a value that was not yet known at the view's instant.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error(
    "look-ahead: the value for {start} is known only from {known_at}, after the decision instant {at}"
)]
pub struct LookAhead {
    /// The interval asked for.
    pub start: OffsetDateTime,
    /// The earliest instant any version of it is known.
    pub known_at: OffsetDateTime,
    /// The view's decision instant.
    pub at: OffsetDateTime,
}

/// An insertion that would rewrite history.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("a revision of {start} must be known after {previous}, got {known_at}")]
pub struct NotLater {
    /// The interval.
    pub start: OffsetDateTime,
    /// The last version's knowledge instant.
    pub previous: OffsetDateTime,
    /// The rejected knowledge instant.
    pub known_at: OffsetDateTime,
}

/// A bitemporal series keyed by interval start.
#[derive(Debug, Clone, Default)]
pub struct Series {
    versions: BTreeMap<OffsetDateTime, Vec<Observation>>,
}

impl Series {
    /// An empty series.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds a version; its revision number is assigned. History only grows forward.
    ///
    /// # Errors
    /// [`NotLater`] if a version of the interval known at the same or a later instant exists.
    pub fn insert(
        &mut self,
        start: OffsetDateTime,
        minutes: u16,
        value: EurPerMwh,
        known_at: OffsetDateTime,
    ) -> Result<(), NotLater> {
        let list = self.versions.entry(start).or_default();
        if let Some(last) = list.last()
            && known_at <= last.known_at
        {
            return Err(NotLater {
                start,
                previous: last.known_at,
                known_at,
            });
        }
        let revision = u32::try_from(list.len()).unwrap_or(u32::MAX);
        list.push(Observation {
            start,
            minutes,
            value,
            known_at,
            revision,
        });
        Ok(())
    }

    /// A read view fixed to the decision instant `at`.
    #[must_use]
    pub fn at(&self, at: OffsetDateTime) -> View<'_> {
        View { series: self, at }
    }
}

/// A read view of a [`Series`] at a decision instant.
#[derive(Debug, Clone, Copy)]
pub struct View<'a> {
    series: &'a Series,
    at: OffsetDateTime,
}

impl<'a> View<'a> {
    /// The decision instant.
    #[must_use]
    pub const fn instant(&self) -> OffsetDateTime {
        self.at
    }

    /// The latest version of the interval starting at `start` known at the decision instant.
    ///
    /// # Errors
    /// [`LookAhead`] if versions exist but none was known yet. `Ok(None)` if the interval has no
    /// version at all.
    pub fn get(&self, start: OffsetDateTime) -> Result<Option<&'a Observation>, LookAhead> {
        let series: &'a Series = self.series;
        let Some(list) = series.versions.get(&start) else {
            return Ok(None);
        };
        match list.iter().rev().find(|o| o.known_at <= self.at) {
            Some(o) => Ok(Some(o)),
            None => Err(LookAhead {
                start,
                known_at: list[0].known_at,
                at: self.at,
            }),
        }
    }

    /// The interval that *contains* `instant` (an hourly price for a quarter-hour instant), latest
    /// version known at the decision instant.
    ///
    /// # Errors
    /// [`LookAhead`] if that interval exists but no version was known yet. `Ok(None)` if no interval
    /// covers the instant.
    pub fn containing(
        &self,
        instant: OffsetDateTime,
    ) -> Result<Option<&'a Observation>, LookAhead> {
        let series: &'a Series = self.series;
        let Some((start, list)) = series.versions.range(..=instant).next_back() else {
            return Ok(None);
        };
        let covers = list
            .first()
            .is_some_and(|o| instant < o.start + time::Duration::minutes(i64::from(o.minutes)));
        if !covers {
            return Ok(None);
        }
        match list.iter().rev().find(|o| o.known_at <= self.at) {
            Some(o) => Ok(Some(o)),
            None => Err(LookAhead {
                start: *start,
                known_at: list[0].known_at,
                at: self.at,
            }),
        }
    }

    /// Every interval in `[from, to)` with its latest version known at the decision instant;
    /// intervals not yet known are left out.
    #[must_use]
    pub fn range(&self, from: OffsetDateTime, to: OffsetDateTime) -> Vec<&'a Observation> {
        let (series, at): (&'a Series, _) = (self.series, self.at);
        series
            .versions
            .range(from..to)
            .filter_map(|(_, list)| list.iter().rev().find(|o| o.known_at <= at))
            .collect()
    }
}