flexibility 0.1.1

Grid flexibility as exact, replayable arithmetic: limits, baselines, UFTP-exact settlement, and UFTP, EEBUS, S2, OpenADR, IEC 104 converters.
Documentation
//! User stories 3 and 4: limits, envelopes, schedules and provenance.

mod common;

use common::{agr, at, day, dso, fuse, win};
use flexibility::{Bounds, Broken, Envelope, Error, Limit, Power, Schedule, Series, Window};

fn w(watts: i64) -> Power {
    Power::from_watts(watts)
}

fn evening_cap() -> Limit {
    Limit::consumption_cap(win(17, 0, 19, 0), w(4_200), dso())
}

#[test]
fn a_cap_constrains_exactly_its_isps() {
    let env = Envelope::unbounded(day()).apply(&evening_cap()).unwrap();
    for isp in 1..=96 {
        let max = env.bounds(isp).unwrap().max();
        if (69..=76).contains(&isp) {
            assert_eq!(max, Some(w(4_200)), "ISP {isp}");
        } else {
            assert_eq!(max, None, "ISP {isp}");
        }
    }
}

#[test]
fn combination_takes_the_stricter_bound() {
    let site = Limit::new(
        win(0, 0, 23, 0),
        Bounds::new(Some(w(-6_000)), Some(w(11_000))).unwrap(),
        fuse(),
    );
    let export = Limit::feed_in_cap(win(10, 0, 14, 0), w(3_000), dso()).unwrap();
    let a = Envelope::unbounded(day()).apply(&site).unwrap();
    let b = Envelope::unbounded(day())
        .apply(&export)
        .unwrap()
        .apply(&evening_cap())
        .unwrap();
    let c = a.combine(&b).unwrap();
    assert_eq!(
        c.bounds(1),
        Some(Bounds::new(Some(w(-6_000)), Some(w(11_000))).unwrap())
    );
    assert_eq!(
        c.bounds(45),
        Some(Bounds::new(Some(w(-3_000)), Some(w(11_000))).unwrap())
    );
    assert_eq!(
        c.bounds(70),
        Some(Bounds::new(Some(w(-6_000)), Some(w(4_200))).unwrap())
    );
    assert_eq!(c.bounds(96), Some(Bounds::UNBOUNDED));
}

#[test]
fn an_empty_range_is_an_error_naming_the_isp() {
    let floor = Limit::new(win(17, 15, 17, 45), Bounds::at_least(w(5_000)), fuse());
    let env = Envelope::unbounded(day()).apply(&evening_cap()).unwrap();
    let err = env.apply(&floor).unwrap_err();
    let Error::EmptyRange { isp, min, max } = &err else {
        panic!("expected EmptyRange, got {err}")
    };
    assert_eq!((isp.isp(), *min, *max), (70, w(5_000), w(4_200)));
    assert!(
        err.to_string().contains("ISP 70 (17:15–17:30 +01:00)"),
        "{err}"
    );
}

#[test]
fn a_partial_overlap_constrains_the_isp() {
    let cap = Limit::consumption_cap(win(17, 5, 17, 20), w(1_000), dso());
    assert_eq!(cap.isps(&day()), Some(69..=70));
    let env = Envelope::unbounded(day()).apply(&cap).unwrap();
    assert_eq!(env.bounds(69).unwrap().max(), Some(w(1_000)));
    assert_eq!(env.bounds(70).unwrap().max(), Some(w(1_000)));
    assert_eq!(env.bounds(71).unwrap().max(), None);
}

#[test]
fn a_limit_outside_the_grid_changes_nothing_and_says_so() {
    let next = |t: flexibility::jiff::Timestamp| {
        t.checked_add(flexibility::jiff::SignedDuration::from_hours(24))
            .unwrap()
    };
    let tomorrow = Limit::consumption_cap(
        Window::new(next(at(17, 0)), next(at(19, 0))).unwrap(),
        w(1_000),
        dso(),
    );
    assert_eq!(tomorrow.isps(&day()), None);
    let env = Envelope::unbounded(day());
    assert_eq!(env.apply(&tomorrow).unwrap(), env);
}

#[test]
fn limits_and_bounds_refuse_nonsense() {
    assert_eq!(
        Bounds::new(Some(w(2)), Some(w(1))).unwrap_err(),
        Error::InvertedBounds {
            min: w(2),
            max: w(1)
        }
    );
    assert!(matches!(
        Window::new(at(19, 0), at(17, 0)).unwrap_err(),
        Error::EmptyWindow { .. }
    ));
    assert!(Window::new(at(17, 0), at(17, 0)).is_err());
}

#[test]
fn a_schedule_inside_its_envelope_has_no_violations() {
    let env = Envelope::unbounded(day()).apply(&evening_cap()).unwrap();
    let plan = Schedule::new(Series::filled(day(), w(4_200)), agr());
    assert_eq!(plan.check(&env).unwrap(), Vec::new());
}

#[test]
fn every_violation_is_reported_with_its_source() {
    let env = Envelope::unbounded(day()).apply(&evening_cap()).unwrap();
    let mut values = vec![w(1_000); 96];
    values[69] = w(5_000); // ISP 70
    values[70] = w(7_400); // ISP 71
    let plan = Schedule::new(Series::new(day(), values).unwrap(), agr());
    let v = plan.check(&env).unwrap();
    assert_eq!(v.len(), 2);
    assert_eq!(
        (v[0].label.isp(), v[0].planned, v[0].broken),
        (70, w(5_000), Broken::AboveMax(w(4_200)))
    );
    assert_eq!((v[1].label.isp(), v[1].planned), (71, w(7_400)));
    assert_eq!(v[0].source, dso());
}

#[test]
fn feed_in_below_a_feed_in_cap_is_a_violation() {
    let export = Limit::feed_in_cap(win(10, 0, 14, 0), w(3_000), dso()).unwrap();
    let env = Envelope::unbounded(day()).apply(&export).unwrap();
    let plan = Schedule::new(Series::filled(day(), Power::feed_in(4_000).unwrap()), agr());
    let v = plan.check(&env).unwrap();
    assert_eq!(v.len(), 16);
    assert_eq!(v[0].broken, Broken::BelowMin(w(-3_000)));
}

#[test]
fn combined_envelopes_keep_every_provenance_and_each_bounds_source() {
    let site = Limit::consumption_cap(win(0, 0, 23, 0), w(11_000), fuse());
    let env = Envelope::unbounded(day())
        .apply(&site)
        .unwrap()
        .apply(&evening_cap())
        .unwrap();
    assert_eq!(env.provenances(), &[fuse(), dso()]);
    assert_eq!(env.max_source(1), Some(&fuse()));
    assert_eq!(env.max_source(70), Some(&dso()));
    assert_eq!(env.min_source(70), None);
}

// --- 002 user stories 3 to 5: explain, headroom, guarantees ------------------------------------

use flexibility::{Guarantee, Provenance, kw};

fn three_limits() -> Envelope {
    Envelope::unbounded(day())
        .apply(&Limit::consumption_cap(win(0, 0, 23, 0), kw!(11), fuse()))
        .unwrap()
        .apply(&evening_cap())
        .unwrap()
        .apply(&Limit::consumption_cap(win(16, 0, 20, 0), kw!(7.4), agr()))
        .unwrap()
}

#[test]
fn explain_names_the_source_and_every_shadowed_limit() {
    let why = three_limits().explain(69).unwrap();
    assert_eq!(why.bounds.max(), Some(kw!(4.2)));
    assert_eq!(why.max_source, Some(dso()));
    assert_eq!(why.min_source, None);
    assert_eq!(
        why.shadowed,
        vec![
            (Bounds::at_most(kw!(11)), fuse()),
            (Bounds::at_most(kw!(7.4)), agr())
        ]
    );
    let text = why.to_string();
    assert!(
        text.starts_with("ISP 69 (17:00–17:15 +01:00): max 4.2 kW (dso.example order-42)"),
        "{text}"
    );
    assert!(
        text.contains("shadowed: max 11 kW (site.example main-fuse)"),
        "{text}"
    );
}

#[test]
fn explain_an_unconstrained_isp_and_one_off_the_grid() {
    let env = three_limits();
    let free = env.explain(95).unwrap();
    assert_eq!(free.bounds, Bounds::UNBOUNDED);
    assert!(free.shadowed.is_empty() && free.max_source.is_none());
    assert!(free.to_string().ends_with("unbounded"));
    assert_eq!(env.explain(0), None);
    assert_eq!(env.explain(97), None);
}

#[test]
fn headroom_is_the_signed_room_to_each_bound() {
    let env = Envelope::unbounded(day()).apply(&evening_cap()).unwrap();
    let low = Schedule::new(Series::filled(day(), kw!(2)), agr());
    let room = env.headroom(&low).unwrap();
    assert_eq!(room.get(69).unwrap().up.unwrap().to_string(), "+2.2 kW");
    assert_eq!(room.get(69).unwrap().down, None);
    assert_eq!(room.get(1).unwrap().up, None);
    let high = Schedule::new(Series::filled(day(), kw!(7.4)), agr());
    assert_eq!(
        env.headroom(&high)
            .unwrap()
            .get(69)
            .unwrap()
            .up
            .unwrap()
            .to_string(),
        "-3.2 kW"
    );
    let other = Schedule::new(
        Series::filled(
            common::day_of(flexibility::jiff::civil::date(2026, 12, 2)),
            kw!(1),
        ),
        agr(),
    );
    assert!(matches!(
        env.headroom(&other),
        Err(Error::GridMismatch { .. })
    ));
}

fn rule() -> Provenance {
    Provenance::new("bnetza", "§ 14a minimum", at(0, 0))
}

fn guaranteed() -> Envelope {
    let all_day = win(0, 0, 23, 45);
    Envelope::unbounded(day())
        .guarantee(&Guarantee::consumption(all_day, kw!(4.2), rule()).unwrap())
        .unwrap()
}

#[test]
fn a_guarantee_refuses_a_cap_below_it() {
    let err = guaranteed()
        .apply(&Limit::consumption_cap(win(17, 0, 19, 0), kw!(3), dso()))
        .unwrap_err();
    let Error::GuaranteeBreached(b) = &err else {
        panic!("{err}")
    };
    assert_eq!((b.isp.isp(), b.bound, b.guaranteed), (69, kw!(3), kw!(4.2)));
    assert_eq!((&b.limit, &b.guarantee), (&dso(), &rule()));
    assert!(
        err.to_string()
            .contains("breaks the guarantee of 4.2 kW (bnetza § 14a minimum)"),
        "{err}"
    );
    assert!(guaranteed().apply(&evening_cap()).is_ok());
}

#[test]
fn a_feed_in_guarantee_refuses_a_tighter_feed_in_cap() {
    let env = Envelope::unbounded(day())
        .guarantee(&Guarantee::feed_in(win(10, 0, 14, 0), kw!(2), rule()).unwrap())
        .unwrap();
    assert!(
        env.apply(&Limit::feed_in_cap(win(11, 0, 12, 0), kw!(1), dso()).unwrap())
            .is_err()
    );
    assert!(
        env.apply(&Limit::feed_in_cap(win(11, 0, 12, 0), kw!(2), dso()).unwrap())
            .is_ok()
    );
}

#[test]
fn guarantees_survive_combination_in_either_order() {
    let capped = Envelope::unbounded(day())
        .apply(&Limit::consumption_cap(win(17, 0, 19, 0), kw!(3), dso()))
        .unwrap();
    assert!(guaranteed().combine(&capped).is_err());
    assert!(capped.combine(&guaranteed()).is_err());
    let ok = guaranteed()
        .combine(&Envelope::unbounded(day()).apply(&evening_cap()).unwrap())
        .unwrap();
    assert_eq!(ok.guarantees().len(), 1);
    assert!(
        ok.apply(&Limit::consumption_cap(win(18, 0, 18, 15), kw!(1), dso()))
            .is_err()
    );
}

#[test]
fn a_guarantee_already_broken_is_refused_and_negative_amounts_too() {
    let capped = Envelope::unbounded(day())
        .apply(&Limit::consumption_cap(win(17, 0, 19, 0), kw!(3), dso()))
        .unwrap();
    let g = Guarantee::consumption(win(0, 0, 23, 45), kw!(4.2), rule()).unwrap();
    assert!(matches!(
        capped.guarantee(&g),
        Err(Error::GuaranteeBreached(_))
    ));
    assert!(matches!(
        Guarantee::consumption(win(0, 0, 1, 0), kw!(-1), rule()),
        Err(Error::NegativeAmount { .. })
    ));
    assert!(matches!(
        Limit::feed_in_cap(win(0, 0, 1, 0), kw!(-1), dso()),
        Err(Error::NegativeAmount { .. })
    ));
}

#[test]
fn a_violation_reads_as_a_sentence() {
    let env = Envelope::unbounded(day()).apply(&evening_cap()).unwrap();
    let plan = Schedule::new(Series::filled(day(), kw!(7.4)), agr());
    assert_eq!(
        plan.check(&env).unwrap()[0].to_string(),
        "ISP 69 (17:00–17:15 +01:00): planned 7.4 kW above max 4.2 kW set by dso.example order-42"
    );
}