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
//! The `s2` converter: PEBC power envelopes ↔ limits, PPBC power sequences → schedules.
#![cfg(feature = "s2")]

mod common;

use common::{at, day};
use flexibility::jiff::Timestamp;
use flexibility::s2::{self, wire};
use flexibility::{
    Bounds, Envelope, Error, Grid, IspDuration, Limit, Power, Provenance, Rounding, Window, kw, w,
};
use proptest::prelude::*;
use wire::types::pebc::{Instruction, PowerEnvelope, PowerEnvelopeElement};
use wire::types::ppbc::{PowerSequence, PowerSequenceElement};
use wire::types::{CommodityQuantity, Duration, Id, PowerForecastValue};

const L1: CommodityQuantity = CommodityQuantity::ElectricPowerL1;

/// The S2 specification's own PV example (s2-ws-json, `pv.PEBC.Instruction.json`, Apache-2.0):
/// a curtailable array that may feed in at most 2 kW on L1 for an hour.
const PV_INSTRUCTION: &str = r#"{
  "message_type": "PEBC.Instruction",
  "message_id": "xxx",
  "id": "envelope1",
  "execution_time": "2024-08-24T15:00:00Z",
  "abnormal_condition": false,
  "power_constraints_id": "powerConstraint1",
  "power_envelopes": [
    {
      "id": "pe_xxx",
      "commodity_quantity": "ELECTRIC.POWER.L1",
      "power_envelope_elements": [
        { "duration": 3600000, "upper_limit": 0, "lower_limit": -2000.0 }
      ]
    }
  ]
}"#;

fn cem() -> Provenance {
    Provenance::new("ems.example", "envelope1", at(12, 0))
}

fn instruction(start: Timestamp, elements: Vec<PowerEnvelopeElement>) -> Instruction {
    Instruction {
        message_id: Id::new_const("m-1"),
        id: Id::new_const("i-1"),
        execution_time: start.into(),
        abnormal_condition: false,
        power_constraints_id: Id::new_const("pc-1"),
        power_envelopes: vec![PowerEnvelope {
            id: Id::new_const("pe-1"),
            commodity_quantity: L1,
            power_envelope_elements: elements,
        }],
    }
}

fn applied(grid: Grid, limits: &[Limit]) -> Envelope {
    limits
        .iter()
        .try_fold(Envelope::unbounded(grid), |e, l| e.apply(l))
        .unwrap()
}

#[test]
fn the_specification_pv_example_is_a_feed_in_cap() {
    let wire::Message::PebcInstruction(instruction) = wire::decode(PV_INSTRUCTION).unwrap() else {
        panic!("a PEBC.Instruction");
    };
    let limits = s2::limits(&instruction, L1, &cem()).unwrap();
    assert_eq!(limits.len(), 1);
    // Production is negative in S2 and here: feed in at most 2 kW, consume nothing.
    assert_eq!(
        limits[0].bounds(),
        Bounds::new(Some(kw!(-2)), Some(w!(0))).unwrap()
    );
    let from: Timestamp = "2024-08-24T15:00:00Z".parse().unwrap();
    assert_eq!(
        limits[0].window(),
        Window::new(from, "2024-08-24T16:00:00Z".parse().unwrap()).unwrap()
    );
}

#[test]
fn a_consumption_cap_keeps_its_sign() {
    // A heat pump held below 3 kW: consumption is positive in S2 and here.
    let i = instruction(
        at(17, 0),
        vec![PowerEnvelopeElement::new(
            Duration::from_secs(900),
            0.0,
            3_000.0,
        )],
    );
    let limits = s2::limits(&i, L1, &cem()).unwrap();
    assert_eq!(limits[0].bounds().max(), Some(kw!(3)));
    assert_eq!(limits[0].bounds().min(), Some(w!(0)));
}

#[test]
fn elements_follow_each_other_from_the_execution_time() {
    let i = instruction(
        at(17, 0),
        vec![
            PowerEnvelopeElement::new(Duration::from_secs(1_800), -4_000.0, 0.0),
            PowerEnvelopeElement::new(Duration::from_secs(900), -10_000.0, 0.0),
        ],
    );
    let limits = s2::limits(&i, L1, &cem()).unwrap();
    assert_eq!(
        limits[0].window(),
        Window::new(at(17, 0), at(17, 30)).unwrap()
    );
    assert_eq!(
        limits[1].window(),
        Window::new(at(17, 30), at(17, 45)).unwrap()
    );
    let e = applied(day(), &limits);
    assert_eq!(e.bounds(70).unwrap().min(), Some(kw!(-4)));
    assert_eq!(e.bounds(71).unwrap().min(), Some(kw!(-10)));
    assert_eq!(e.min_source(71).unwrap().reference(), "envelope1");
}

#[test]
fn a_fraction_of_a_watt_another_quantity_or_inverted_bounds_is_refused() {
    let half = instruction(
        at(17, 0),
        vec![PowerEnvelopeElement::new(
            Duration::from_secs(900),
            -4_000.5,
            0.0,
        )],
    );
    let err = s2::limits(&half, L1, &cem()).unwrap_err();
    assert!(
        matches!(
            err,
            Error::Unrepresentable {
                protocol: "S2",
                field: "lower_limit",
                ..
            }
        ),
        "{err}"
    );
    assert!(err.to_string().contains("-4000.5"), "{err}");
    let ok = instruction(
        at(17, 0),
        vec![PowerEnvelopeElement::new(
            Duration::from_secs(900),
            -4_000.0,
            0.0,
        )],
    );
    assert!(matches!(
        s2::limits(&ok, CommodityQuantity::ElectricPowerL2, &cem()),
        Err(Error::NoData { .. })
    ));
    let inverted = instruction(
        at(17, 0),
        vec![PowerEnvelopeElement::new(
            Duration::from_secs(900),
            1.0,
            0.0,
        )],
    );
    assert!(matches!(
        s2::limits(&inverted, L1, &cem()),
        Err(Error::InvertedBounds { .. })
    ));
    let nan = instruction(
        at(17, 0),
        vec![PowerEnvelopeElement::new(
            Duration::from_secs(900),
            f64::NAN,
            0.0,
        )],
    );
    assert!(matches!(
        s2::limits(&nan, L1, &cem()),
        Err(Error::Unrepresentable { .. })
    ));
}

#[test]
fn an_envelope_becomes_one_element_per_run_of_equal_bounds() {
    let grid = day().slice(69..=72).unwrap();
    let all = Window::new(grid.start(), grid.end()).unwrap();
    let cap = Limit::new(
        all,
        Bounds::new(Some(kw!(-4)), Some(kw!(11))).unwrap(),
        cem(),
    );
    let tighter = Limit::consumption_cap(grid.interval(72).unwrap(), kw!(6), cem());
    let e = applied(grid, &[cap, tighter]);
    let pe = s2::power_envelope(&e, Id::new_const("pe-2"), L1).unwrap();
    let elements: Vec<(u64, String, String)> = pe
        .power_envelope_elements
        .iter()
        .map(|el| {
            (
                el.duration.as_millis(),
                el.lower_limit.to_string(),
                el.upper_limit.to_string(),
            )
        })
        .collect();
    assert_eq!(
        elements,
        [
            (2_700_000, "-4000".into(), "11000".into()),
            (900_000, "-4000".into(), "6000".into())
        ]
    );
}

#[test]
fn an_open_side_cannot_be_sent() {
    let grid = day().slice(69..=70).unwrap();
    let all = Window::new(grid.start(), grid.end()).unwrap();
    let e = applied(grid, &[Limit::consumption_cap(all, kw!(11), cem())]);
    let err = s2::power_envelope(&e, Id::new_const("pe-3"), L1).unwrap_err();
    assert!(err.to_string().contains("open side"), "{err}");
}

fn sequence(elements: &[(u64, f64)]) -> PowerSequence {
    PowerSequence {
        id: Id::new_const("seq-1"),
        elements: elements
            .iter()
            .map(|&(secs, watts)| PowerSequenceElement {
                duration: Duration::from_secs(secs),
                power_values: vec![PowerForecastValue::expected(watts, L1)],
            })
            .collect(),
        is_interruptible: false,
        max_pause_before: None,
        abnormal_condition_only: false,
    }
}

#[test]
fn a_power_sequence_is_a_schedule_on_the_isps_it_covers() {
    let seq = sequence(&[(1_800, 2_000.0), (900, 1_500.5)]);
    let err = s2::schedule(&seq, L1, at(17, 0), &day(), Rounding::Exact, cem()).unwrap_err();
    assert!(err.to_string().contains("1500.5"), "{err}");
    let plan = s2::schedule(
        &seq,
        L1,
        at(17, 0),
        &day(),
        Rounding::HalfAwayFromZero,
        cem(),
    )
    .unwrap();
    assert_eq!(*plan.series().grid().numbers().start(), 69);
    let watts: Vec<i64> = plan.series().values().iter().map(|p| p.watts()).collect();
    assert_eq!(watts, [2_000, 2_000, 1_501]);
}

#[test]
fn a_sequence_off_the_isp_boundaries_is_refused() {
    let short = sequence(&[(600, 2_000.0)]);
    assert!(s2::schedule(&short, L1, at(17, 0), &day(), Rounding::Exact, cem()).is_err());
    let late = sequence(&[(900, 2_000.0)]);
    assert!(s2::schedule(&late, L1, at(17, 5), &day(), Rounding::Exact, cem()).is_err());
    let outside = sequence(&[(900, 2_000.0)]);
    let grid = Grid::new(at(17, 0), IspDuration::FIFTEEN_MINUTES, 1, common::berlin()).unwrap();
    assert!(s2::schedule(&outside, L1, at(17, 15), &grid, Rounding::Exact, cem()).is_err());
    let empty = sequence(&[]);
    assert!(matches!(
        s2::schedule(&empty, L1, at(17, 0), &day(), Rounding::Exact, cem()),
        Err(Error::NoData { .. })
    ));
}

proptest! {
    /// What both can carry round-trips: an envelope bounded on both sides → S2 → limits → the
    /// same envelope.
    #[test]
    fn a_two_sided_envelope_round_trips(bounds in prop::collection::vec((-50_000i64..=0, 0i64..=50_000), 1..8)) {
        let grid = day().slice(69..=68 + u32::try_from(bounds.len()).unwrap()).unwrap();
        let limits: Vec<Limit> = grid
            .numbers()
            .zip(&bounds)
            .map(|(isp, &(lo, hi))| {
                Limit::new(grid.interval(isp).unwrap(), Bounds::new(Some(Power::from_watts(lo)), Some(Power::from_watts(hi))).unwrap(), cem())
            })
            .collect();
        let ours = applied(grid.clone(), &limits);
        let pe = s2::power_envelope(&ours, Id::new_const("pe-4"), L1).unwrap();
        let mut i = instruction(grid.start(), vec![]);
        i.power_envelopes = vec![pe];
        let back = applied(grid.clone(), &s2::limits(&i, L1, &cem()).unwrap());
        for isp in grid.numbers() {
            prop_assert_eq!(back.bounds(isp), ours.bounds(isp));
        }
    }
}

fn phases(values: &[(CommodityQuantity, f64)]) -> PowerSequence {
    PowerSequence {
        id: Id::new_const("seq-3"),
        elements: vec![PowerSequenceElement {
            duration: Duration::from_secs(900),
            power_values: values
                .iter()
                .map(|&(q, v)| PowerForecastValue::expected(v, q))
                .collect(),
        }],
        is_interruptible: false,
        max_pause_before: None,
        abnormal_condition_only: false,
    }
}

#[test]
fn the_electric_total_is_the_symmetric_value_or_the_phases_summed_exactly() {
    use CommodityQuantity::{
        ElectricPower3PhaseSymmetric as SYM, ElectricPowerL1 as P1, ElectricPowerL2 as P2,
        ElectricPowerL3 as P3,
    };
    let total = |values: &[(CommodityQuantity, f64)], rounding| {
        s2::schedule(
            &phases(values),
            s2::Read::ElectricTotal,
            at(17, 0),
            &day(),
            rounding,
            cem(),
        )
        .map(|s| s.series().values()[0])
    };
    assert_eq!(total(&[(SYM, 11_000.0)], Rounding::Exact).unwrap(), kw!(11));
    assert_eq!(
        total(
            &[(P1, 1_000.0), (P2, 2_000.0), (P3, 3_000.0)],
            Rounding::Exact
        )
        .unwrap(),
        kw!(6)
    );
    // 1000.1 + 2000.2 + 3000.3 is 6000.6 exactly (in f64 it is not): one rounding, at the end.
    assert!(
        total(
            &[(P1, 1_000.1), (P2, 2_000.2), (P3, 3_000.3)],
            Rounding::Exact
        )
        .is_err()
    );
    assert_eq!(
        total(
            &[(P1, 1_000.1), (P2, 2_000.2), (P3, 3_000.3)],
            Rounding::HalfAwayFromZero
        )
        .unwrap(),
        w!(6001)
    );
    assert_eq!(
        total(&[(P1, 0.3), (P2, 0.3), (P3, 0.4)], Rounding::Exact).unwrap(),
        w!(1)
    );
    for bad in [
        &[(SYM, 3_000.0), (P1, 1_000.0)][..],
        &[(P1, 1.0), (P1, 2.0)][..],
        &[][..],
    ] {
        assert!(total(bad, Rounding::Exact).is_err(), "{bad:?}");
    }
}