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
//! A DSO asks for 10–30 kW less from 17:00 to 18:15; an aggregator answers with three home
//! batteries of 5, 10 and 15 kWh. Split by inverter power, the small battery runs below its
//! reserve; split by steady headroom, every battery holds. The pool cannot hold 10 kW until
//! 18:15, so the offer leaves the last quarter hour out. Run with
//! `cargo run --example offer_from_a_pool`.

use flexibility::jiff::civil::{date, time};
use flexibility::jiff::tz::TimeZone;
use flexibility::pool::{self, SplitReport};
use flexibility::{
    Band, Deviation, DeviationEnvelope, Disposition, Energy, EnergyEnvelope, Envelope, Error, Grid,
    IspDuration, Level, Limit, MisfitKind, Power, Provenance, Schedule, Series, Window, kw, kwh,
};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let berlin = TimeZone::get("Europe/Berlin")?;
    let day = Grid::day(date(2026, 12, 1), &berlin, IspDuration::FIFTEEN_MINUTES)?;
    let evening = day.slice(69..=76)?; // 17:00–19:00
    let who = |r: &str| Provenance::new("agr.example", r, evening.start());

    // Requested: 10 to 30 kW less in ISPs 69–73 (17:00–18:15).
    let need = Band::new(
        Deviation::from_watts(-30_000),
        Deviation::from_watts(-10_000),
        Disposition::Requested,
    )?;
    let bands = evening.numbers().map(|isp| (isp <= 73).then_some(need));
    let request = DeviationEnvelope::new(
        Series::new(evening.clone(), bands.collect())?,
        Provenance::new("dso.example", "request-7", evening.start()),
    );

    // Each battery: ±5 kW, kept between 10 % and 90 %, half full, planned idle.
    let all = Window::new(evening.start(), evening.end())?;
    let inverter = Envelope::unbounded(evening.clone()).apply(&Limit::band(
        all,
        kw!(-5),
        kw!(5),
        who("inverter"),
    )?)?;
    let battery = |capacity: Energy| {
        let at = |percent| Energy::from_watt_seconds(capacity.watt_seconds() * percent / 100);
        EnergyEnvelope::new(inverter.clone(), at(50))
            .level_always(Level::between(at(10), at(90))?, who("soc"))
    };
    let batteries = [battery(kwh!(5))?, battery(kwh!(10))?, battery(kwh!(15))?];
    let idle = Schedule::new(Series::filled(evening.clone(), kw!(0)), who("plan"));

    // How much less each can hold, steadily, until 18:00 and until 18:15.
    let down = |until| -> Result<Vec<i64>, Error> {
        let window = Window::new(evening.start(), evening.local(until)?)?;
        batteries
            .iter()
            .map(|b| {
                let h = b.steady_headroom(&idle, window)?.ok_or(Error::NoData {
                    what: "no steady deviation fits",
                })?;
                Ok(-h.down.map_or(0, Deviation::watts))
            })
            .collect()
    };
    let hour = down(time(18, 0, 0, 0))?;
    let longer = down(time(18, 15, 0, 0))?;
    println!("steady headroom down until 18:00: {hour:?} W; until 18:15: {longer:?} W");
    assert_eq!(hour, [2_000, 4_000, 5_000]);
    assert!(longer.iter().sum::<i64>() < 10_000);

    // Offer 11 kW less until 18:00, split in proportion to two different weights.
    let total = 11_000;
    let less_until_18 = |watts: i64| -> Result<Schedule, Error> {
        let values = evening
            .numbers()
            .map(|isp| Power::from_watts(if isp <= 72 { -watts } else { 0 }));
        Ok(Schedule::new(
            Series::new(evening.clone(), values.collect())?,
            who("plan"),
        ))
    };
    let split_by = |weights: [i64; 3]| -> Result<SplitReport, Error> {
        let sum: i64 = weights.iter().sum();
        let mut shares = weights.map(|w| total * w / sum);
        shares[0] += total - shares.iter().sum::<i64>(); // whole watts: the remainder
        let plans = shares.map(less_until_18);
        let plans: Vec<Schedule> = plans.into_iter().collect::<Result<_, _>>()?;
        let split: Vec<_> = batteries.iter().zip(&plans).collect();
        pool::check_split(&less_until_18(total)?, &split)
    };
    let by_power = split_by([5_000; 3])?;
    for (battery, report) in &by_power.devices {
        println!("by power, battery {battery}: {}", report.level[0]);
    }
    assert!(!by_power.fits());
    assert!(split_by([hour[0], hour[1], hour[2]])?.fits());
    println!("by steady headroom: every battery holds");

    // The offer names ISPs 69–72 and leaves 73 out.
    let named = (69..=73).map(|isp| (isp <= 72).then_some(Deviation::from_watts(-total)));
    let offer = Series::new(day.slice(69..=73)?, named.collect())?;
    let misfits = request.check(&offer)?;
    for m in &misfits {
        println!("{m}");
    }
    assert!(matches!(
        misfits.as_slice(),
        [m] if m.label.isp() == 73 && matches!(m.kind, MisfitKind::NotOffered { .. })
    ));
    Ok(())
}