flexibility 0.1.2

Grid flexibility as exact, replayable arithmetic: limits, baselines, UFTP-exact settlement, and UFTP, EEBUS, S2, OpenADR, CSIP-AUS, IEC 104, CLS.EEDI converters.
Documentation
//! # flexibility
//!
//! Grid flexibility as exact, replayable arithmetic. A grid operator caps what a site may draw, an
//! aggregator plans what it will draw, both agree on what it would have drawn anyway (the
//! *baseline*), and settle what was delivered. This crate computes all four in whole watts, in one
//! sign convention, with a record of who set every bound and a digest both sides can recompute.
//!
//! It is the arithmetic, not a market, a protocol stack or a controller: limits, plans and meter
//! values go in as arguments; watts, watt-seconds and receipts come out.
//!
//! ## The shapes
//!
//! - [`Power`] is whole watts, **positive for consumption, negative for feed-in** (UFTP 3.1
//!   § 4.2.1). [`kw!`], [`w!`] and [`mw!`] are exact literals checked at compile time;
//!   [`Deviation`] is power relative to a baseline, [`Energy`] is watt-seconds.
//! - A [`Grid`] is a run of imbalance settlement periods (ISPs) in a time zone: a Central
//!   European [`Grid::day`] has 92, 96 or 100 quarter hours. [`Grid::window`] turns local times
//!   into a [`Window`] and refuses the ones a clock change skips or repeats. A [`Series`] holds one
//!   value per ISP.
//! - A [`Limit`] bounds power over a window; an [`Envelope`] is the strictest bound per ISP, each
//!   naming its [`Provenance`]; a [`Schedule`] is checked against it. [`Envelope::explain`] says why
//!   an ISP allows what it allows, and a [`Guarantee`] (the § 14a EnWG minimum) refuses any cap
//!   below it.
//! - An [`EnergyEnvelope`] adds bounds on a stored [`Level`] (a car's departure energy, a
//!   battery's capacity); [`pool`] sums devices and says whether the result is exact.
//! - A [`DeviationEnvelope`] is what a flexibility request asks for: [`Band`]s on the deviation
//!   from a baseline.
//!
//! ## Baselines and settlement
//!
//! - [`baseline`]: `dprognosis@1`, `schedule@1`, `mbma@1` and `xofy@1`, each with required
//!   parameters and a [card](baseline::cards); a method id never changes its meaning.
//! - [`settle`]: delivered flexibility and power deficiency per ISP, exactly as UFTP 3.1 § 2.6
//!   computes them, at a recorded [`MeasurementPoint`]. A [`Settlement`] has a canonical text and a
//!   `sha256:` [`Digest`] over RFC 8785 canonical JSON;
//!   [`Settlement::from_canonical`] reads the other side's back and [`Settlement::diff`] names
//!   where they part. [`Settlement::rebound`] reports what came back after the order.
//! - [`accuracy`]: how well a method predicts a site, scored exactly.
//!
//! ## Protocols
//!
//! Each converter is a Cargo feature, off by default, lossless or refusing:
//!
//! | Feature | Protocol | Maps |
//! |---|---|---|
//! | `uftp` | UFTP 3.1 (Shapeshifter) | requests, offers, orders and settlement items |
//! | `eebus` | EEBUS LPC and LPP | active and failsafe limits, both ways |
//! | `s2` | S2 (EN 50491-12-2) | PEBC power envelopes, PPBC power sequences |
//! | `openadr` | OpenADR 3 | import and export capacity limits, both ways; usage reports |
//! | `csip` | CSIP-AUS (IEEE 2030.5) | dynamic operating envelopes at the connection point |
//! | `iec104` | IEC 60870-5-104 | active-power set points, types 48–50, both ways |
//! | `cls` | CLS.EEDI | control-box limits and failsafes, both ways |
//! | `metering` | German metering rules | the § 14a minimum, Lastgang energy as power |
//!
//! ## Guarantees
//!
//! The crate reads no clock, file, network, environment or random source, and does no
//! floating-point arithmetic: the same inputs give the same bytes on every machine. A float on the
//! wire (S2, IEC 104) is read once, as the decimal written. What cannot be represented exactly is
//! refused with an [`Error`] that names the values and offers a [`hint`](Error::hint), never
//! rounded silently. Time is [`jiff`], with the time-zone database bundled.
//!
//! ```
//! use flexibility::jiff::{civil::{date, time}, tz::TimeZone};
//! use flexibility::*;
//!
//! let berlin = TimeZone::get("Europe/Berlin")?;
//! let grid = Grid::day(date(2026, 12, 1), &berlin, IspDuration::FIFTEEN_MINUTES)?;
//! let noon = grid.local(time(12, 0, 0, 0))?;
//!
//! // The grid operator caps consumption at 4.2 kW from 17:00 to 19:00 local time.
//! let evening = grid.window(time(17, 0, 0, 0), time(19, 0, 0, 0))?;
//! let dso = Provenance::new("dso.example", "order-42", noon);
//! let envelope = Envelope::unbounded(grid.clone()).apply(&Limit::consumption_cap(evening, kw!(4.2), dso))?;
//!
//! // A car planned at 7.4 kW all evening breaks it in ISPs 69 to 76.
//! let car = Provenance::new("agr.example", "plan-7", noon);
//! let plan = Schedule::new(Series::filled(grid, kw!(7.4)), car);
//! let violations = plan.check(&envelope)?;
//! assert_eq!(violations.len(), 8);
//! assert_eq!(
//!     violations[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"
//! );
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

#![forbid(unsafe_code)]

// The README's example is compiled and run as a doctest.
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
struct ReadmeDoctests;

pub mod accuracy;
pub mod baseline;
mod canon;
#[cfg(feature = "cls")]
pub mod cls;
#[cfg(feature = "csip")]
pub mod csip;
#[cfg(feature = "eebus")]
pub mod eebus;
mod error;
mod grid;
#[cfg(feature = "iec104")]
pub mod iec104;
#[cfg(feature = "metering")]
pub mod metering;
#[cfg(feature = "openadr")]
pub mod openadr;
pub mod pool;
mod power;
mod rebound;
mod relative;
#[cfg(feature = "s2")]
pub mod s2;
mod series;
mod settle;
mod shape;
mod storage;
#[cfg(feature = "uftp")]
pub mod uftp;

pub use baseline::{Baseline, MethodId};
pub use canon::{Digest, MAX_EXACT, MAX_RECEIPT_BYTES, canonical_series};
pub use error::{Breach, Error};
pub use grid::{Grid, IspDuration, IspLabel, MAX_ISPS, Window};
#[doc(hidden)]
pub use power::{__energy_literal, __literal};
pub use power::{Deviation, Direction, Energy, Power, Rounding};
pub use rebound::{Rebound, ReboundLine};
pub use relative::{Band, DeviationEnvelope, Disposition, Misfit};
pub use series::Series;
pub use settle::{DeviceId, Difference, Line, MeasurementPoint, Settlement, settle};
pub use shape::{
    Bounds, Broken, Envelope, Explanation, Guarantee, Headroom, Limit, Provenance, Schedule,
    Violation,
};
pub use storage::{EnergyEnvelope, Level, LevelBroken, LevelViolation, Report};

/// The `jiff` crate, whose `Timestamp`, `civil::Date`, `civil::Time` and `tz::TimeZone` appear
/// in this crate's API.
pub use jiff;

/// A power literal in watts, exact and checked at compile time.
///
/// ```
/// use flexibility::{w, Power};
/// assert_eq!(w!(500), Power::from_watts(500));
/// assert_eq!(w!(-3_000), Power::from_watts(-3_000));
/// ```
///
/// A fraction of a watt does not compile:
///
/// ```compile_fail
/// let _ = flexibility::w!(0.5);
/// ```
#[macro_export]
macro_rules! w {
    ($($literal:tt)+) => {
        $crate::__power_literal!(0, "w!", $($literal)+)
    };
}

/// A power literal in kilowatts, exact and checked at compile time: the macro reads the
/// literal's *text*, never a float, so `kw!(4.2)` is exactly 4 200 W.
///
/// ```
/// use flexibility::{kw, Power};
/// assert_eq!(kw!(4.2), Power::from_watts(4_200));
/// assert_eq!(kw!(-3), Power::from_watts(-3_000));
/// assert_eq!(kw!(11), Power::from_watts(11_000));
/// ```
///
/// A value that is not whole watts does not compile:
///
/// ```compile_fail
/// let _ = flexibility::kw!(4.0001);
/// ```
#[macro_export]
macro_rules! kw {
    ($($literal:tt)+) => {
        $crate::__power_literal!(3, "kw!", $($literal)+)
    };
}

/// A power literal in megawatts, exact and checked at compile time.
///
/// ```
/// use flexibility::{mw, Power};
/// assert_eq!(mw!(1.5), Power::from_watts(1_500_000));
/// ```
#[macro_export]
macro_rules! mw {
    ($($literal:tt)+) => {
        $crate::__power_literal!(6, "mw!", $($literal)+)
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! __power_literal {
    ($scale:expr, $name:literal, $($literal:tt)+) => {{
        const POWER: $crate::Power = match $crate::__literal(stringify!($($literal)+), $scale) {
            Some(power) => power,
            None => panic!(concat!($name, ": not an exact number of whole watts")),
        };
        POWER
    }};
}

/// An energy literal in watt-hours, exact and checked at compile time.
///
/// ```
/// use flexibility::{wh, Energy};
/// assert_eq!(wh!(500), Energy::from_watt_seconds(1_800_000));
/// ```
///
/// A fraction of a watt-hour does not compile:
///
/// ```compile_fail
/// let _ = flexibility::wh!(0.5);
/// ```
#[macro_export]
macro_rules! wh {
    ($($literal:tt)+) => {
        $crate::__energy_literal!(0, "wh!", $($literal)+)
    };
}

/// An energy literal in kilowatt-hours, exact and checked at compile time: `kwh!(30)` is
/// 108 000 000 watt-seconds, `kwh!(1.5)` 1 500 Wh.
///
/// ```
/// use flexibility::{kwh, Energy};
/// assert_eq!(kwh!(1.5), Energy::from_watt_seconds(5_400_000));
/// assert_eq!(kwh!(30).to_string(), "30 kWh");
/// ```
///
/// ```compile_fail
/// let _ = flexibility::kwh!(1.0001);
/// ```
#[macro_export]
macro_rules! kwh {
    ($($literal:tt)+) => {
        $crate::__energy_literal!(3, "kwh!", $($literal)+)
    };
}

/// An energy literal in megawatt-hours, exact and checked at compile time.
///
/// ```
/// use flexibility::{mwh, kwh};
/// assert_eq!(mwh!(1.2), kwh!(1_200));
/// ```
#[macro_export]
macro_rules! mwh {
    ($($literal:tt)+) => {
        $crate::__energy_literal!(6, "mwh!", $($literal)+)
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! __energy_literal {
    ($scale:expr, $name:literal, $($literal:tt)+) => {{
        const ENERGY: $crate::Energy = match $crate::__energy_literal(stringify!($($literal)+), $scale) {
            Some(energy) => energy,
            None => panic!(concat!($name, ": not an exact number of whole watt-hours")),
        };
        ENERGY
    }};
}