flexpool-sim 0.2.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
//! One scenario day replayed: rules, clock and bitemporal market data together.

use std::fmt::Write as _;

use flexpool_core::{BusinessDay, EurPerMwh};
use flexpool_rules::{Entry, RuleBook};
use rust_decimal::Decimal;
use time::OffsetDateTime;

use crate::clock::{Clock, Event, EventKind};
use crate::import::{self, ImportProblem};
use crate::scenario::{MarketSource, Scenario};
use crate::series::{Series, View};
use crate::synthetic;

/// An instant as Berlin local time with its offset, e.g. `2025-10-01 12:00 +02:00` — how
/// operators read gate times.
#[must_use]
pub fn berlin(t: OffsetDateTime) -> String {
    let local = flexpool_core::calendar::to_berlin(t);
    let fmt = time::macros::format_description!(
        "[year]-[month]-[day] [hour]:[minute] [offset_hour sign:mandatory]:[offset_minute]"
    );
    local.format(fmt).unwrap_or_else(|_| t.to_string())
}

/// Why a replay could not be built.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum ReplayError {
    /// A rule needed for the day is missing.
    #[error(transparent)]
    Rule(#[from] flexpool_rules::Missing),
    /// The calendar does not cover the day.
    #[error(transparent)]
    Calendar(#[from] flexpool_core::CalendarError),
    /// The data file is invalid.
    #[error("data file: {}", .0.iter().map(ToString::to_string).collect::<Vec<_>>().join("; "))]
    Data(Vec<ImportProblem>),
    /// A data file source but no data text was given.
    #[error("the scenario names a data file but none was loaded")]
    NoData,
}

/// The day-ahead result as known at an instant.
#[derive(Debug, Clone, serde::Serialize)]
pub struct DayAhead<'a> {
    /// The delivery day.
    pub day: time::Date,
    /// Market time unit in minutes.
    pub mtu_minutes: u16,
    /// The rule entry that set the time unit.
    pub mtu_rule: &'a Entry,
    /// When the prices became known.
    #[serde(with = "time::serde::rfc3339")]
    pub known_at: OffsetDateTime,
    /// The prices in time order.
    pub prices: Vec<&'a crate::series::Observation>,
}

/// A replayed scenario day.
#[derive(Debug, Clone)]
pub struct Replay {
    scenario: Scenario,
    rules: RuleBook,
    clock: Clock,
    prices: Series,
    day: BusinessDay,
    mtu: u16,
    publication: OffsetDateTime,
}

impl Replay {
    /// Builds the replay of `scenario`. `data` is the text of the scenario's data file, if any.
    ///
    /// # Errors
    /// [`ReplayError`] if a rule is missing for the day or the data is invalid.
    pub fn new(
        scenario: Scenario,
        rules: RuleBook,
        data: Option<&str>,
    ) -> Result<Self, ReplayError> {
        let day = BusinessDay::new(scenario.day)?;
        let (mtu, _) = rules.da_mtu(day.date())?;
        let (min, max, _) = rules.da_price_limits(day.date())?;
        let (step, _) = rules.granularity("da.price-granularity", day.date())?;
        let (publication, _) = rules.gate("da.publication", day.date())?;
        let rows = match &scenario.market {
            MarketSource::Synthetic { seed, .. } => {
                synthetic::day_ahead(&day, mtu, *seed, step, (min, max))
            }
            MarketSource::File { .. } => {
                let text = data.ok_or(ReplayError::NoData)?;
                import::day_ahead_csv(text, &day, mtu, (min, max)).map_err(ReplayError::Data)?
            }
        };
        let mut prices = Series::new();
        for (start, price) in rows {
            // One version per interval in a fresh series: insertion cannot fail.
            let _ = prices.insert(start, mtu, price, publication);
        }
        // Earlier days, each with its own rules (hourly before the 15-minute go-live) and known
        // from its own publication: the history forecasts learn from — never ahead of the clock.
        if let MarketSource::Synthetic { seed, history_days } = &scenario.market {
            let mut date = day.date();
            for _ in 0..*history_days {
                let Some(earlier) = date.previous_day() else {
                    break;
                };
                date = earlier;
                let Ok(d) = BusinessDay::new(date) else { break };
                let (Ok((m, _)), Ok((lo, hi, _)), Ok((st, _)), Ok((published, _))) = (
                    rules.da_mtu(date),
                    rules.da_price_limits(date),
                    rules.granularity("da.price-granularity", date),
                    rules.gate("da.publication", date),
                ) else {
                    break; // before the rules' validity: no history is invented
                };
                for (start, price) in synthetic::day_ahead(&d, m, *seed, st, (lo, hi)) {
                    let _ = prices.insert(start, m, price, published);
                }
            }
        }
        let mut events = vec![
            Event {
                at: publication,
                kind: EventKind::Published("da.prices".into()),
            },
            Event {
                at: day.start(),
                kind: EventKind::DayStarted,
            },
            Event {
                at: day.end(),
                kind: EventKind::DayEnded,
            },
        ];
        for gate in ["da.gate", "ida1.gate", "ida2.gate", "ida3.gate"] {
            if let Ok((at, _)) = rules.gate(gate, day.date()) {
                events.push(Event {
                    at,
                    kind: EventKind::GateClosed(gate.into()),
                });
            }
        }
        let clock = Clock::new(scenario.start, scenario.end, events);
        Ok(Self {
            scenario,
            rules,
            clock,
            prices,
            day,
            mtu,
            publication,
        })
    }

    /// The scenario.
    #[must_use]
    pub const fn scenario(&self) -> &Scenario {
        &self.scenario
    }

    /// The rules.
    #[must_use]
    pub const fn rules(&self) -> &RuleBook {
        &self.rules
    }

    /// The clock.
    #[must_use]
    pub const fn clock(&self) -> &Clock {
        &self.clock
    }

    /// The clock, to move it.
    pub const fn clock_mut(&mut self) -> &mut Clock {
        &mut self.clock
    }

    /// The bitemporal day-ahead prices: the replayed day and its history.
    #[must_use]
    pub const fn series(&self) -> &Series {
        &self.prices
    }

    /// The delivery day replayed.
    #[must_use]
    pub const fn business_day(&self) -> &BusinessDay {
        &self.day
    }

    /// A view of the market data at the clock's instant.
    #[must_use]
    pub fn view(&self) -> View<'_> {
        self.prices.at(self.clock.now())
    }

    /// When the day-ahead prices are published.
    #[must_use]
    pub const fn publication(&self) -> OffsetDateTime {
        self.publication
    }

    /// The day-ahead result as known now, or `None` before publication.
    #[must_use]
    pub fn day_ahead(&self) -> Option<DayAhead<'_>> {
        let prices = self.view().range(self.day.start(), self.day.end());
        if prices.is_empty() {
            return None;
        }
        let mtu_rule = self.rules.da_mtu(self.day.date()).ok()?.1;
        Some(DayAhead {
            day: self.day.date(),
            mtu_minutes: self.mtu,
            mtu_rule,
            known_at: self.publication,
            prices,
        })
    }

    /// Runs to the end and returns a deterministic summary.
    #[must_use]
    pub fn run_to_end(mut self) -> String {
        let mut out = String::new();
        let s = &self.scenario;
        let mtu_entry = self.rules.da_mtu(self.day.date()).map(|(_, e)| e.clone());
        let _ = writeln!(out, "scenario  {}\nday       {}", s.name, s.day);
        if let Ok(e) = &mtu_entry {
            let status = self
                .rules
                .source_of(e)
                .map_or("?".to_owned(), |src| src.status.to_string());
            let _ = writeln!(
                out,
                "mtu       {} min  (rule {} from {}, source {} [{status}])",
                self.mtu, e.id, e.valid_from, e.source
            );
        }
        let _ = writeln!(out, "start     {}\nevents", berlin(self.clock.now()));
        while !self.clock.finished() {
            for e in self.clock.advance_next() {
                let what = match &e.kind {
                    EventKind::GateClosed(id) => format!("gate closed  {id}"),
                    EventKind::Published(id) => format!("published    {id}"),
                    EventKind::DayStarted => "day started".to_owned(),
                    EventKind::DayEnded => "day ended".to_owned(),
                };
                let _ = writeln!(out, "  {}  {what}", berlin(e.at));
            }
        }
        if let Some(da) = self.day_ahead() {
            let values: Vec<Decimal> = da.prices.iter().map(|o| o.value.value()).collect();
            let n = Decimal::from(values.len());
            let min = values.iter().min().copied().unwrap_or_default();
            let max = values.iter().max().copied().unwrap_or_default();
            let mean = values
                .iter()
                .sum::<Decimal>()
                .checked_div(n)
                .unwrap_or_default()
                .round_dp(2);
            let negative = values
                .iter()
                .filter(|v| v.is_sign_negative() && !v.is_zero())
                .count();
            let _ = writeln!(
                out,
                "prices    {} intervals  min {}  mean {}  max {}  negative {}",
                values.len(),
                EurPerMwh::new(min),
                EurPerMwh::new(mean),
                EurPerMwh::new(max),
                negative
            );
        }
        let _ = writeln!(out, "end       {}", berlin(self.clock.now()));
        out
    }
}