flexibility 0.2.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
//! 006: the ยง 14a minimum and Lastgang energy from `metering`.
#![cfg(feature = "metering")]

mod common;

use common::{day, day_of, dso};
use flexibility::MeasurementPoint;
use flexibility::jiff::civil::date;
use flexibility::metering::{self, wire};
use flexibility::{
    Deviation, Error, Grid, IspDuration, Power, Rounding, Schedule, Series, Window, baseline,
    settle, w,
};
use wire::dec;
use wire::grid::para14a::{
    Anlage, Para14aConfig, SteuVeFallgruppe, mindestleistung_direktansteuerung,
    steuerbare_verbrauchseinrichtungen,
};
use wire::prelude::Decimal;

use wire::{DayBoundary, MeterInterval, ObisCode, QualityFlag, Resolution};

/// A Lastgang on `channel` with one value per ISP of `grid`, all of `quality`.
fn lastgang(grid: &Grid, channel: ObisCode, kwh: &[Decimal], quality: QualityFlag) -> wire::Series {
    let intervals = grid
        .numbers()
        .zip(kwh)
        .map(|(isp, &v)| {
            let iv = grid.interval(isp).unwrap();
            MeterInterval::new(iv.from(), iv.until(), v, quality)
                .unwrap()
                .with_obis(channel)
        })
        .collect();
    wire::Series::new(Resolution::QUARTER_HOUR, DayBoundary::Strom, intervals).unwrap()
}

fn import(grid: &Grid, kwh: &[Decimal]) -> wire::Series {
    lastgang(
        grid,
        ObisCode::STROM_BEZUG_LASTGANG,
        kwh,
        QualityFlag::Measured,
    )
}

fn export(grid: &Grid, kwh: &[Decimal]) -> wire::Series {
    lastgang(
        grid,
        ObisCode::STROM_EINSPEISUNG_LASTGANG,
        kwh,
        QualityFlag::Measured,
    )
}

fn watts(s: &Series<Power>) -> Vec<i64> {
    s.values().iter().map(|p| p.watts()).collect()
}

#[test]
fn the_14a_minimum_is_a_guarantee_rounded_up() {
    let cfg = Para14aConfig::VERMUTUNG;
    let g = day();
    let all = Window::new(g.start(), g.end()).unwrap();
    let minimum = |fallgruppe, kw| {
        let steuve = steuerbare_verbrauchseinrichtungen(&[Anlage::new(fallgruppe, kw)]).unwrap();
        let m = mindestleistung_direktansteuerung(&steuve[0], &cfg);
        metering::guarantee(m, all, dso()).unwrap().power()
    };
    assert_eq!(minimum(SteuVeFallgruppe::Ladepunkt, dec!(11)), w!(4200));
    assert_eq!(
        minimum(SteuVeFallgruppe::Waermepumpe, dec!(20.001)),
        w!(8001),
        "0,4 ร— 20,001 kW = 8 000,4 W, kept to the watt above"
    );
}

#[test]
fn quarters_of_energy_are_average_power() {
    let g = day().slice(69..=70).unwrap();
    let p = metering::power(&[&import(&g, &[dec!(1.05), dec!(0)])], &g, Rounding::Exact).unwrap();
    assert_eq!(watts(&p), [4_200, 0]);
    assert_eq!(p.grid(), &g);
}

#[test]
fn import_and_export_are_netted_then_rounded_once() {
    let g = day().slice(69..=70).unwrap();
    let net = metering::power(
        &[
            &import(&g, &[dec!(1.0), dec!(0.00035)]),
            &export(&g, &[dec!(0.25), dec!(0.00015)]),
        ],
        &g,
        Rounding::HalfAwayFromZero,
    )
    .unwrap();
    // 4 000 โˆ’ 1 000 W; and 1.4 โˆ’ 0.6 = 0.8 W โ†’ 1 W (rounding each first would give 1 โˆ’ 1 = 0).
    assert_eq!(watts(&net), [3_000, 1]);
}

#[test]
fn a_fraction_of_a_watt_needs_a_named_rounding() {
    let g = day().slice(69..=69).unwrap();
    let tiny = [&import(&g, &[dec!(0.0001)])];
    assert!(matches!(
        metering::power(&tiny, &g, Rounding::Exact),
        Err(Error::Inexact { .. })
    ));
    assert_eq!(
        watts(&metering::power(&tiny, &g, Rounding::HalfAwayFromZero).unwrap()),
        [0]
    );
}

#[test]
fn a_gap_a_faulty_quarter_or_a_wrong_channel_is_refused() {
    let g = day().slice(69..=70).unwrap();
    let short = import(&g.slice(69..=69).unwrap(), &[dec!(1)]);
    let err = metering::power(&[&short], &g, Rounding::Exact).unwrap_err();
    assert!(
        matches!(
            err,
            Error::Unrepresentable {
                protocol: "metering",
                field: "interval",
                ..
            }
        ),
        "{err}"
    );
    assert!(
        err.to_string()
            .contains("missing electricity quarter at 2026-12-01T16:15:00Z"),
        "{err}"
    );

    let faulty = lastgang(
        &g,
        ObisCode::STROM_BEZUG_LASTGANG,
        &[dec!(1), dec!(1)],
        QualityFlag::Faulty,
    );
    assert!(matches!(
        metering::power(&[&faulty], &g, Rounding::Exact),
        Err(Error::Unrepresentable {
            field: "interval",
            ..
        })
    ));

    let register = lastgang(
        &g,
        ObisCode::STROM_BEZUG_TOTAL,
        &[dec!(1), dec!(1)],
        QualityFlag::Measured,
    );
    let err = metering::power(&[&register], &g, Rounding::Exact).unwrap_err();
    assert!(
        matches!(
            err,
            Error::Unrepresentable {
                field: "channel",
                ..
            }
        ),
        "{err}"
    );

    let hourly = Grid::new(
        g.start(),
        IspDuration::from_minutes(60).unwrap(),
        1,
        common::berlin(),
    )
    .unwrap();
    assert!(matches!(
        metering::power(
            &[&import(&g, &[dec!(1), dec!(1)])],
            &hourly,
            Rounding::Exact
        ),
        Err(Error::Mismatch { .. })
    ));
}

#[test]
fn a_dst_day_maps_quarter_for_quarter() {
    let short = day_of(date(2026, 3, 29));
    assert_eq!(short.count(), 92);
    let kwh = vec![dec!(0.25); 92];
    assert_eq!(
        watts(&metering::power(&[&import(&short, &kwh)], &short, Rounding::Exact).unwrap()),
        vec![1_000; 92]
    );
}

#[test]
fn a_settlement_from_lastgang_equals_one_from_hand_entered_power() {
    let g = day().slice(69..=72).unwrap();
    let all = Window::new(g.start(), g.end()).unwrap();
    let base = baseline::dprognosis(
        &Schedule::new(Series::filled(g.clone(), w!(4000)), dso()),
        all,
    )
    .unwrap();
    let ordered = Series::filled(g.clone(), Deviation::from_watts(-2_000));
    let metered = metering::power(
        &[&import(&g, &[dec!(0.5), dec!(0.6), dec!(0.75), dec!(1)])],
        &g,
        Rounding::Exact,
    )
    .unwrap();
    let by_hand = Series::new(g, vec![w!(2000), w!(2400), w!(3000), w!(4000)]).unwrap();
    assert_eq!(
        settle(&base, &metered, &ordered, MeasurementPoint::ConnectionPoint)
            .unwrap()
            .digest(),
        settle(&base, &by_hand, &ordered, MeasurementPoint::ConnectionPoint)
            .unwrap()
            .digest()
    );
}