flexibility 0.3.0

Grid flexibility as exact, replayable arithmetic: limits, baselines, UFTP-exact settlement, and UFTP, EEBUS, S2, OpenADR, CSIP-AUS, IEC 104, CLS.EEDI converters.
Documentation
//! 007: pools — the aggregate, exact or outer, and the check of a given split.

mod common;

use common::{at, day};
use flexibility::pool::{self, Aggregate};
use flexibility::{
    Bounds, Deviation, Energy, EnergyEnvelope, Envelope, Error, Grid, Level, Limit, Power,
    Provenance, Schedule, Series, Window, kw, kwh, w,
};

fn who(reference: &str) -> Provenance {
    Provenance::new("agr.example", reference, at(0, 0))
}

fn boxed(grid: &Grid, min: Power, max: Power) -> EnergyEnvelope {
    let all = Window::new(grid.start(), grid.end()).unwrap();
    let env = Envelope::unbounded(grid.clone())
        .apply(&Limit::new(
            all,
            Bounds::new(Some(min), Some(max)).unwrap(),
            who("device"),
        ))
        .unwrap();
    EnergyEnvelope::new(env, kwh!(0))
}

fn plan(grid: &Grid, kw: &[Power]) -> Schedule {
    Schedule::new(Series::new(grid.clone(), kw.to_vec()).unwrap(), who("plan"))
}

fn grid() -> Grid {
    day().slice(69..=70).unwrap()
}

#[test]
fn power_boxes_sum_exactly() {
    let g = grid();
    let agg = pool::aggregate(
        &[boxed(&g, kw!(0), kw!(11)), boxed(&g, kw!(-3), kw!(3))],
        who("pool"),
    )
    .unwrap();
    assert!(agg.is_exact());
    assert_eq!(
        agg.envelope().power().bounds(69),
        Some(Bounds::new(Some(kw!(-3)), Some(kw!(14))).unwrap())
    );
    assert_eq!(agg.envelope().power().max_source(69), Some(&who("pool")));
    assert_eq!(agg.envelope().power().guarantees(), []);
}

#[test]
fn an_unbounded_side_stays_unbounded() {
    let g = grid();
    let all = Window::new(g.start(), g.end()).unwrap();
    let capped = EnergyEnvelope::new(
        Envelope::unbounded(g.clone())
            .apply(&Limit::consumption_cap(all, kw!(5), who("cap")))
            .unwrap(),
        kwh!(0),
    );
    let agg = pool::aggregate(&[capped, boxed(&g, kw!(0), kw!(5))], who("pool")).unwrap();
    assert_eq!(
        agg.envelope().power().bounds(69),
        Some(Bounds::at_most(kw!(10)))
    );
}

/// Car A must charge 10 kW in both ISPs to have 5 kWh; device B may take 0–10 kW, no storage.
/// The outer aggregate (0–20 kW, no level bound) accepts a pool plan of 0 then 20 kW, which no
/// split can follow: A would have to draw 10 kW in ISP 69 while B draws −10 kW.
#[test]
fn an_outer_aggregate_can_accept_a_plan_no_split_follows() {
    let g = grid();
    let a = boxed(&g, kw!(0), kw!(10))
        .level_at(g.end(), Level::at_least(kwh!(5)), who("departure"))
        .unwrap();
    let b = boxed(&g, kw!(0), kw!(10));
    let agg = pool::aggregate(&[a.clone(), b.clone()], who("pool")).unwrap();
    let Aggregate::Outer(env) = &agg else {
        panic!("A has a level bound")
    };
    let pool_plan = plan(&g, &[kw!(0), kw!(20)]);
    assert!(
        env.check(&pool_plan).unwrap().fits(),
        "inside the outer aggregate"
    );

    let split = pool::check_split(
        &pool_plan,
        &[
            (&a, &plan(&g, &[kw!(0), kw!(10)])),
            (&b, &plan(&g, &[kw!(0), kw!(10)])),
        ],
    )
    .unwrap();
    assert_eq!(split.sums, []);
    assert_eq!(split.devices.len(), 1);
    assert_eq!(split.devices[0].0, 0, "device 0, the car");
    assert_eq!(split.devices[0].1.level[0].level, kwh!(2.5));
}

#[test]
fn a_split_that_misses_the_pool_plan_is_named() {
    let g = grid();
    let (a, b) = (boxed(&g, kw!(0), kw!(11)), boxed(&g, kw!(0), kw!(11)));
    let pool_plan = plan(&g, &[kw!(10), kw!(10)]);
    let ok = pool::check_split(
        &pool_plan,
        &[
            (&a, &plan(&g, &[kw!(5), kw!(4)])),
            (&b, &plan(&g, &[kw!(5), kw!(6)])),
        ],
    )
    .unwrap();
    assert!(ok.fits());
    let short = pool::check_split(
        &pool_plan,
        &[
            (&a, &plan(&g, &[kw!(5), kw!(4)])),
            (&b, &plan(&g, &[w!(4999), kw!(6)])),
        ],
    )
    .unwrap();
    assert_eq!(short.sums.len(), 1);
    assert_eq!(
        (short.sums[0].label.isp(), short.sums[0].devices),
        (69, w!(9999))
    );
    assert_eq!(
        short.sums[0].to_string(),
        "ISP 69 (17:00–17:15 +01:00): pool plans 10 kW, devices sum to 9.999 kW"
    );
}

#[test]
fn a_pool_needs_devices_on_one_grid() {
    assert!(matches!(
        pool::aggregate(&[], who("pool")),
        Err(Error::NoData { .. })
    ));
    let other = day().slice(71..=72).unwrap();
    assert!(matches!(
        pool::aggregate(
            &[
                boxed(&grid(), kw!(0), kw!(1)),
                boxed(&other, kw!(0), kw!(1))
            ],
            who("pool")
        ),
        Err(Error::GridMismatch { .. })
    ));
}

// 018: what Exact promises, and the steady headroom a split is weighed by.

/// 10 kWh battery kept between 1 and 9 kWh, ±5 kW, holding 5 kWh, on a two-hour grid.
fn battery(levels: bool) -> (Grid, EnergyEnvelope) {
    let g = day().slice(69..=76).unwrap();
    let mut b = boxed(&g, kw!(-5), kw!(5));
    b = EnergyEnvelope::new(b.power().clone(), kwh!(5));
    if levels {
        b = b
            .level_always(Level::between(kwh!(1), kwh!(9)).unwrap(), who("soc"))
            .unwrap();
    }
    (g, b)
}

fn hours(g: &Grid, first: u32, isps: u32) -> Window {
    let from = g.interval(first).unwrap().from();
    Window::new(from, g.interval(first + isps - 1).unwrap().until()).unwrap()
}

#[allow(clippy::unnecessary_wraps)] // compared with `Headroom`'s optional sides
fn dev(watts: i64) -> Option<Deviation> {
    Some(Deviation::from_watts(watts))
}

#[test]
fn storage_without_level_bounds_is_exact_and_with_them_outer() {
    let (_, blind) = battery(false);
    let (_, held) = battery(true);
    assert!(pool::aggregate(&[blind], who("pool")).unwrap().is_exact());
    assert!(!pool::aggregate(&[held], who("pool")).unwrap().is_exact());
}

#[test]
fn steady_headroom_is_held_by_stored_energy_over_long_windows_and_power_over_short() {
    let (g, b) = battery(true);
    let idle = plan(&g, &[kw!(0); 8]);
    let h = b.steady_headroom(&idle, hours(&g, 69, 4)).unwrap().unwrap();
    assert_eq!(
        (h.down, h.up),
        (dev(-4_000), dev(4_000)),
        "4 kWh each way over an hour"
    );
    let h = b.steady_headroom(&idle, hours(&g, 69, 2)).unwrap().unwrap();
    assert_eq!(
        (h.down, h.up),
        (dev(-5_000), dev(5_000)),
        "the inverter, over 30 minutes"
    );

    // One watt more breaks a level bound.
    let over = plan(
        &g,
        &[
            w!(4_001),
            w!(4_001),
            w!(4_001),
            w!(4_001),
            kw!(0),
            kw!(0),
            kw!(0),
            kw!(0),
        ],
    );
    assert!(!b.check(&over).unwrap().fits());
}

#[test]
fn power_bounds_alone_give_the_tightest_isp() {
    let (g, b) = battery(false);
    let p = plan(
        &g,
        &[
            kw!(0),
            kw!(3),
            kw!(-1),
            kw!(0),
            kw!(0),
            kw!(0),
            kw!(0),
            kw!(0),
        ],
    );
    let h = b.steady_headroom(&p, hours(&g, 69, 3)).unwrap().unwrap();
    assert_eq!((h.down, h.up), (dev(-4_000), dev(2_000)));
}

#[test]
fn a_bound_after_the_window_still_holds_the_energy_moved() {
    let (g, b) = battery(false);
    let b = b
        .level_at(g.end(), Level::at_least(kwh!(4)), who("reserve"))
        .unwrap();
    let h = b
        .steady_headroom(&plan(&g, &[kw!(0); 8]), hours(&g, 69, 1))
        .unwrap()
        .unwrap();
    assert_eq!(
        h.down,
        dev(-4_000),
        "1 kWh above the reserve, in a quarter hour"
    );
    assert_eq!(h.up, dev(5_000));
}

#[test]
fn level_bounds_round_inward() {
    let (g, b) = battery(false);
    // 1 Ws of room over 900 s: no whole watt fits upward, 0 W does.
    let b = b
        .level_at(
            g.end(),
            Level::at_most(Energy::from_watt_seconds(kwh!(5).watt_seconds() + 1)),
            who("cap"),
        )
        .unwrap();
    let h = b
        .steady_headroom(&plan(&g, &[kw!(0); 8]), hours(&g, 69, 1))
        .unwrap()
        .unwrap();
    assert_eq!(h.up, dev(0));
}

#[test]
fn a_plan_outside_gives_the_way_back_and_no_way_gives_none() {
    let (g, b) = battery(true);
    let full = plan(&g, &[kw!(5); 8]); // 5 kWh + 10 kWh: far above 9 kWh
    let h = b.steady_headroom(&full, hours(&g, 69, 8)).unwrap().unwrap();
    assert_eq!(h.up, dev(-3_000), "only a lower plan fits");
    // Power wants at least -5 kW + 5 kW = 0 W more; the level needs less: none fits.
    let b = EnergyEnvelope::new(
        Envelope::unbounded(g.clone())
            .apply(
                &Limit::band(
                    Window::new(g.start(), g.end()).unwrap(),
                    kw!(5),
                    kw!(6),
                    who("must-run"),
                )
                .unwrap(),
            )
            .unwrap(),
        kwh!(5),
    )
    .level_always(Level::between(kwh!(1), kwh!(9)).unwrap(), who("soc"))
    .unwrap();
    assert_eq!(b.steady_headroom(&full, hours(&g, 69, 8)).unwrap(), None);
}

#[test]
fn a_window_off_the_grid_or_a_plan_on_another_is_refused() {
    let (g, b) = battery(true);
    let idle = plan(&g, &[kw!(0); 8]);
    let mid = Window::new(at(17, 5), at(18, 0)).unwrap();
    assert!(matches!(
        b.steady_headroom(&idle, mid),
        Err(Error::NotABoundary { .. })
    ));
    let later = Window::new(at(23, 0), at(23, 15)).unwrap();
    assert!(matches!(
        b.steady_headroom(&idle, later),
        Err(Error::NotABoundary { .. })
    ));
    let other = plan(&grid(), &[kw!(0); 2]);
    assert!(matches!(
        b.steady_headroom(&other, hours(&g, 69, 1)),
        Err(Error::GridMismatch { .. })
    ));
}