flexpool-plan 0.5.0

flexpool day-ahead planning: price scenarios from forecast quantiles, a storage LP with a CVaR term, water values from the duals, limit orders and their paper execution. No I/O.
Documentation
//! Planning: scenarios, the LP's limits and duals, risk, orders, paper execution, no look-ahead.
#![expect(clippy::unwrap_used, reason = "tests")]

use flexpool_core::BusinessDay;
use flexpool_forecast::{Forecast, Interval, Model, builtin, error_lag1};
use flexpool_plan::{
    Market, Risk, SCENARIOS, SOC_MAX, SOC_MIN, Side, Storage, draw, evaluate, inverse_normal, plan,
    price_at, solve,
};
use flexpool_rules::RuleBook;
use flexpool_sim::{Replay, Scenario};
use time::macros::{date, datetime};
use time::{Date, OffsetDateTime};

const POOL: Storage = Storage {
    power_mw: 30.0,
    energy_mwh: 60.0,
    round_trip: 0.88,
    cycle_cost: 0.0,
};

fn replay_with(day: &str, history_days: u16) -> Replay {
    let text = format!(
        "name = \"t\"\nday = \"{day}\"\n[market]\nsource = \"synthetic\"\nseed = 7\nhistory_days = {history_days}\n"
    );
    Replay::new(
        Scenario::parse(&text).unwrap(),
        RuleBook::bundled().unwrap(),
        None,
    )
    .unwrap()
}

/// The blend forecast for `day` as of `at`, its correlation, and the scenarios.
fn inputs(r: &Replay, day: Date, at: OffsetDateTime) -> (Forecast, f64, Vec<Vec<f64>>, Market) {
    let rules = RuleBook::bundled().unwrap();
    let d = BusinessDay::new(day).unwrap();
    let view = r.series().at(at);
    let f = builtin(Model::Blend, &view, &d, 15).unwrap();
    let rho = error_lag1(Model::Blend, &view, &d, 15).unwrap();
    let market = Market::from_rules(&rules, day).unwrap();
    let s = draw(&f, rho, 42, market.lo, market.hi);
    (f, rho, s, market)
}

fn starts(f: &Forecast) -> Vec<OffsetDateTime> {
    f.intervals.iter().map(|i| i.start).collect()
}

fn check_limits(p: &flexpool_plan::PoolPlan, s: &Storage) {
    for st in &p.steps {
        assert!(st.charge_mw >= 0.0 && st.discharge_mw >= 0.0, "{st:?}");
        assert!(
            st.charge_mw + st.discharge_mw <= s.power_mw + 1e-9,
            "{st:?}"
        );
        assert!(
            st.soc_mwh >= SOC_MIN * s.energy_mwh - 1e-9
                && st.soc_mwh <= SOC_MAX * s.energy_mwh + 1e-9,
            "{st:?}"
        );
    }
}

#[test]
fn scenarios_reproduce_the_forecast_quantiles() {
    let q = [10.0, 40.0, 50.0, 70.0, 120.0];
    for (z, want) in [
        (-1.281_551_565_544_600_4, 10.0),
        (0.0, 50.0),
        (1.281_551_565_544_600_4, 120.0),
    ] {
        assert!((price_at(&q, z) - want).abs() < 1e-9);
    }
    assert!(
        price_at(&q, -3.0) < 10.0 && price_at(&q, 3.0) > 120.0,
        "linear tails"
    );
    assert!((inverse_normal(0.975) - 1.959_963_985).abs() < 1e-8);
    // Over all scenarios the share below each quantile is close to its level.
    let r = replay_with("2025-10-02", 28);
    let (f, rho, s, market) = inputs(&r, date!(2025 - 10 - 02), datetime!(2025-10-01 08:00 UTC));
    assert_eq!(s.len(), SCENARIOS);
    let mut below = [0usize; 5];
    for path in &s {
        for (t, p) in path.iter().enumerate() {
            for (k, b) in below.iter_mut().enumerate() {
                *b += usize::from(*p <= f.intervals[t].q[k]);
            }
        }
    }
    #[expect(clippy::cast_precision_loss, reason = "test counts")]
    let n = (s.len() * f.intervals.len()) as f64;
    for (k, level) in [0.1, 0.25, 0.5, 0.75, 0.9].iter().enumerate() {
        #[expect(clippy::cast_precision_loss, reason = "test counts")]
        let share = below[k] as f64 / n;
        assert!((share - level).abs() < 0.05, "level {level}: {share}");
    }
    assert_eq!(
        s,
        draw(&f, rho, 42, market.lo, market.hi),
        "deterministic for a seed"
    );
}

/// plan/SR-004: at any price — extreme, negative — the limits hold.
#[test]
fn sr_004_limits_hold_at_any_price() {
    let rules = RuleBook::bundled().unwrap();
    let market = Market::from_rules(&rules, date!(2025 - 10 - 02)).unwrap();
    let day = BusinessDay::new(date!(2025 - 10 - 02)).unwrap();
    let starts: Vec<OffsetDateTime> = (0..96)
        .map(|k| day.start() + time::Duration::minutes(15 * k))
        .collect();
    let wild: Vec<Vec<f64>> = (0..50)
        .map(|s| {
            (0..96)
                .map(|t| match (s + t) % 7 {
                    0 => -500.0,
                    1 => 4000.0,
                    2 => -120.0,
                    3 => 0.0,
                    _ => f64::from(u8::try_from((s * 13 + t * 7) % 200).unwrap()) - 50.0,
                })
                .collect()
        })
        .collect();
    for risk in Risk::ALL {
        for storage in [
            POOL,
            Storage {
                cycle_cost: 25.0,
                round_trip: 0.6,
                ..POOL
            },
        ] {
            let p = plan(&storage, &wild, &starts, 0.25, risk, &market).unwrap();
            check_limits(&p, &storage);
            for o in &p.orders {
                let limit: f64 = o.limit.try_into().unwrap();
                assert!((-500.0..=4000.0).contains(&limit), "{o:?}");
                let mw: f64 = o.mw.try_into().unwrap();
                assert!(mw > 0.0 && mw <= storage.power_mw, "{o:?}");
            }
            let end = p.steps.last().unwrap().soc_mwh;
            assert!(
                end >= storage.energy_mwh * 0.5 - 1e-6,
                "ends at least half full: {end}"
            );
        }
    }
}

/// R4: the duals are water values — where a flow is interior, the order limit equals the price.
#[test]
fn water_values_price_the_orders() {
    let storage = Storage {
        power_mw: 10.0,
        energy_mwh: 1.0,
        round_trip: 0.81,
        cycle_cost: 0.0,
    };
    let s = solve(&storage, &[vec![10.0, 100.0]], 0.25, 0.0).unwrap();
    assert!(
        s.charge[0] > 0.1 && s.charge[0] < 9.9,
        "interior charge {s:?}"
    );
    assert!(
        s.discharge[1] > 0.1 && s.discharge[1] < 9.9,
        "interior discharge {s:?}"
    );
    let (ec, ed) = (storage.eta_charge(), storage.eta_discharge());
    assert!(
        (s.water_value[0] * ec - 10.0).abs() < 1e-3,
        "buy limit = price: {s:?}"
    );
    assert!(
        (s.water_value[1] / ed - 100.0).abs() < 1e-3,
        "sell limit = price: {s:?}"
    );
}

/// SC-002: cautious has a CVaR at least as high and an expected revenue at most as high as neutral.
#[test]
fn sc_002_risk_trades_expectation_for_the_tail() {
    let r = replay_with("2025-10-02", 28);
    let (f, _, s, market) = inputs(&r, date!(2025 - 10 - 02), datetime!(2025-10-01 08:00 UTC));
    let st = starts(&f);
    let n = plan(&POOL, &s, &st, 0.25, Risk::Neutral, &market).unwrap();
    let b = plan(&POOL, &s, &st, 0.25, Risk::Balanced, &market).unwrap();
    let c = plan(&POOL, &s, &st, 0.25, Risk::Cautious, &market).unwrap();
    eprintln!(
        "neutral {:?}\nbalanced {:?}\ncautious {:?}",
        n.revenue, b.revenue, c.revenue
    );
    let eps = 1e-3 * n.revenue.expected.abs().max(1.0);
    assert!(c.revenue.cvar10 >= n.revenue.cvar10 - eps);
    assert!(c.revenue.expected <= n.revenue.expected + eps);
    assert!(
        n.revenue.expected > 0.0 && !n.idle,
        "the demo day has a spread to earn"
    );
    for p in [&n, &b, &c] {
        check_limits(p, &POOL);
        // Sells above, buys below the water value; every order at a unit with a flow.
        for o in &p.orders {
            let step = p.steps.iter().find(|x| x.start == o.start).unwrap();
            match o.side {
                Side::Sell => assert!(step.discharge_mw > step.charge_mw),
                Side::Buy => assert!(step.charge_mw > step.discharge_mw),
            }
        }
    }
}

/// SC-003: after publication the committed plan earns, never more than perfect foresight.
#[test]
fn sc_003_paper_result_is_bounded_by_perfect_foresight() {
    let r = replay_with("2025-10-02", 28);
    let day = date!(2025 - 10 - 02);
    let (f, _, s, market) = inputs(&r, day, datetime!(2025-10-01 10:00 UTC));
    let st = starts(&f);
    let p = plan(&POOL, &s, &st, 0.25, Risk::Balanced, &market).unwrap();
    let d = BusinessDay::new(day).unwrap();
    let after = r.series().at(datetime!(2025-10-01 11:00 UTC));
    let prices: Vec<f64> = after
        .range(d.start(), d.end())
        .into_iter()
        .map(|o| o.value.value().try_into().unwrap())
        .collect();
    assert_eq!(prices.len(), 96);
    let o = evaluate(&p, &POOL, &st, &prices, 0.25).unwrap();
    eprintln!(
        "paper {:.0} perfect {:.0} capture {:?}",
        o.paper, o.perfect, o.capture
    );
    assert!(o.paper > 0.0, "{o:?}");
    assert!(o.paper <= o.perfect + 1e-6);
    assert_eq!(o.fills.len(), p.orders.len());
}

#[test]
fn a_flat_forecast_leaves_the_storage_idle() {
    let day = BusinessDay::new(date!(2025 - 10 - 02)).unwrap();
    let f = Forecast {
        day: day.date(),
        model: "flat".into(),
        issued_at: datetime!(2025-10-01 08:00 UTC),
        minutes: 15,
        intervals: (0..96)
            .map(|k| Interval {
                start: day.start() + time::Duration::minutes(15 * k),
                q: [80.0; 5],
            })
            .collect(),
    };
    let market = Market::from_rules(&RuleBook::bundled().unwrap(), day.date()).unwrap();
    let s = draw(&f, 0.9, 1, market.lo, market.hi);
    let p = plan(&POOL, &s, &starts(&f), 0.25, Risk::Neutral, &market).unwrap();
    assert!(p.idle && p.orders.is_empty(), "{:?}", p.orders);
}

/// Edge case: the autumn DST day has 100 quarter hours, and the plan has as many steps.
#[test]
fn dst_days_have_their_own_length() {
    let r = replay_with("2025-10-26", 28);
    let (f, _, s, market) = inputs(&r, date!(2025 - 10 - 26), datetime!(2025-10-25 08:00 UTC));
    let p = plan(&POOL, &s, &starts(&f), 0.25, Risk::Balanced, &market).unwrap();
    assert_eq!(p.steps.len(), 100);
    check_limits(&p, &POOL);
}

/// plan/SR-003, SC-004: a plan before publication is the same with and without the day's prices.
#[test]
fn sr_003_plans_never_look_ahead() {
    let with_day = replay_with("2025-10-02", 29);
    let without = replay_with("2025-10-01", 28);
    let day = date!(2025 - 10 - 02);
    let at = datetime!(2025-10-01 08:00 UTC);
    let (fa, ra, sa, market) = inputs(&with_day, day, at);
    let (fb, rb, sb, _) = inputs(&without, day, at);
    assert_eq!((fa.clone(), ra), (fb, rb));
    let a = plan(&POOL, &sa, &starts(&fa), 0.25, Risk::Balanced, &market).unwrap();
    let b = plan(&POOL, &sb, &starts(&fa), 0.25, Risk::Balanced, &market).unwrap();
    assert_eq!(a, b);
}

/// SC-001: one pool's plan in under a second (release and debug builds alike in CI).
#[test]
fn sc_001_a_plan_takes_under_a_second() {
    let r = replay_with("2025-10-02", 28);
    let started = std::time::Instant::now();
    let (f, _, s, market) = inputs(&r, date!(2025 - 10 - 02), datetime!(2025-10-01 08:00 UTC));
    let mid = started.elapsed();
    let _ = plan(&POOL, &s, &starts(&f), 0.25, Risk::Cautious, &market).unwrap();
    let took = started.elapsed();
    eprintln!("inputs {mid:?}");
    eprintln!("plan took {took:?}");
    assert!(took.as_secs_f64() < 1.0, "{took:?}");
}

/// Backtest: over 14 past days, each planned at its own gate, the orders capture at
/// least 85 % of perfect foresight (the reference day set: seed 7, 2025-09-18 … 2025-10-01).
#[test]
fn backtest_captures_most_of_perfect_foresight() {
    let rules = RuleBook::bundled().unwrap();
    let r = replay_with("2025-10-02", 44);
    let (mut paper, mut perfect) = (0.0, 0.0);
    for back in 1..=14 {
        let day = date!(2025 - 10 - 02) - time::Duration::days(back);
        let d = BusinessDay::new(day).unwrap();
        let gate = rules.gate("da.gate", day).unwrap().0;
        let (minutes, _) = rules.da_mtu(day).unwrap();
        let view = r.series().at(gate);
        let f = builtin(Model::Blend, &view, &d, minutes).unwrap();
        let rho = error_lag1(Model::Blend, &view, &d, minutes).unwrap();
        let market = Market::from_rules(&rules, day).unwrap();
        let s = draw(&f, rho, u64::try_from(back).unwrap(), market.lo, market.hi);
        let hours = f64::from(minutes) / 60.0;
        let p = plan(&POOL, &s, &starts(&f), hours, Risk::Balanced, &market).unwrap();
        let prices: Vec<f64> = r
            .series()
            .at(gate + time::Duration::days(2))
            .range(d.start(), d.end())
            .into_iter()
            .map(|o| o.value.value().try_into().unwrap())
            .collect();
        let o = evaluate(&p, &POOL, &starts(&f), &prices, hours).unwrap();
        paper += o.paper;
        perfect += o.perfect;
    }
    eprintln!(
        "14 days: paper {paper:.0} perfect {perfect:.0} capture {:.3}",
        paper / perfect
    );
    assert!(paper / perfect >= 0.85, "capture {}", paper / perfect);
}