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
//! Strict import of a day's day-ahead prices from CSV (market-replay/SR-002).
//!
//! Format: a header `start_utc,price_eur_mwh`, then one row per market time unit of the day, the
//! start as RFC 3339 UTC and the price with a decimal point. Gaps, duplicates, misaligned starts,
//! non-numeric values and prices outside the limits in force are refused with their line number.
//! Nothing is interpolated.

use std::collections::BTreeSet;

use flexpool_core::{BusinessDay, EurPerMwh};
use time::format_description::well_known::Rfc3339;
use time::{Duration, OffsetDateTime};

/// One problem with a data file.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("line {line}: {message}")]
pub struct ImportProblem {
    /// 1-based line, 0 for the whole file.
    pub line: usize,
    /// What is wrong.
    pub message: String,
}

/// Parses `text` as the prices of `day` at `minutes` resolution within `limits`.
///
/// # Errors
/// Every problem found, in line order.
pub fn day_ahead_csv(
    text: &str,
    day: &BusinessDay,
    minutes: u16,
    limits: (EurPerMwh, EurPerMwh),
) -> Result<Vec<(OffsetDateTime, EurPerMwh)>, Vec<ImportProblem>> {
    let mut problems = Vec::new();
    let mut rows = Vec::new();
    let text = text.strip_prefix('\u{feff}').unwrap_or(text);
    let mut lines = text.lines().enumerate();
    match lines.next() {
        Some((_, h)) if h.trim() == "start_utc,price_eur_mwh" => {}
        _ => problems.push(ImportProblem {
            line: 1,
            message: "header must be `start_utc,price_eur_mwh`".into(),
        }),
    }
    let step = Duration::minutes(i64::from(minutes));
    let mut expected = BTreeSet::new();
    let mut t = day.start();
    while t < day.end() {
        expected.insert(t);
        t += step;
    }
    let mut seen = BTreeSet::new();
    for (i, raw) in lines {
        let line = i + 1;
        let raw = raw.trim();
        if raw.is_empty() {
            continue;
        }
        let Some((start, price)) = raw.split_once(',') else {
            problems.push(ImportProblem {
                line,
                message: format!("expected `start_utc,price_eur_mwh`, got {raw:?}"),
            });
            continue;
        };
        let start = match OffsetDateTime::parse(start.trim(), &Rfc3339) {
            Ok(s) => s.to_offset(time::UtcOffset::UTC),
            Err(_) => {
                problems.push(ImportProblem {
                    line,
                    message: format!("{start:?} is not an RFC 3339 instant"),
                });
                continue;
            }
        };
        let price = match flexpool_core::parse_plain(price.trim()) {
            Some(p) => EurPerMwh::new(p),
            None => {
                problems.push(ImportProblem {
                    line,
                    message: format!("{:?} is not a decimal price", price.trim()),
                });
                continue;
            }
        };
        if !expected.contains(&start) {
            problems.push(ImportProblem {
                line,
                message: format!(
                    "{start} is not a {minutes}-minute interval of {}",
                    day.date()
                ),
            });
        } else if !seen.insert(start) {
            problems.push(ImportProblem {
                line,
                message: format!("duplicate interval {start}"),
            });
        }
        if price < limits.0 || price > limits.1 {
            problems.push(ImportProblem {
                line,
                message: format!(
                    "price {price} is outside the limits {} … {} in force",
                    limits.0, limits.1
                ),
            });
        }
        rows.push((start, price));
    }
    for missing in expected.difference(&seen) {
        problems.push(ImportProblem {
            line: 0,
            message: format!("missing interval {missing}"),
        });
    }
    if problems.is_empty() {
        rows.sort_by_key(|(s, _)| *s);
        Ok(rows)
    } else {
        Err(problems)
    }
}