Skip to main content

flexibility/
lib.rs

1//! # flexibility
2//!
3//! Grid flexibility as exact, replayable arithmetic. A grid operator caps what a site may draw, an
4//! aggregator plans what it will draw, both agree on what it would have drawn anyway (the
5//! *baseline*), and settle what was delivered. This crate computes all four in whole watts, in one
6//! sign convention, with a record of who set every bound and a digest both sides can recompute.
7//!
8//! It is the arithmetic, not a market, a protocol stack or a controller: limits, plans and meter
9//! values go in as arguments; watts, watt-seconds and receipts come out.
10//!
11//! ## The shapes
12//!
13//! - [`Power`] is whole watts, **positive for consumption, negative for feed-in** (UFTP 3.1
14//!   § 4.2.1). [`kw!`], [`w!`] and [`mw!`] are exact literals checked at compile time;
15//!   [`Deviation`] is power relative to a baseline, [`Energy`] is watt-seconds.
16//! - A [`Grid`] is a run of imbalance settlement periods (ISPs) in a time zone: a Central
17//!   European [`Grid::day`] has 92, 96 or 100 quarter hours. [`Grid::window`] turns local times
18//!   into a [`Window`] and refuses the ones a clock change skips or repeats. A [`Series`] holds one
19//!   value per ISP.
20//! - A [`Limit`] bounds power over a window; an [`Envelope`] is the strictest bound per ISP, each
21//!   naming its [`Provenance`]; a [`Schedule`] is checked against it. [`Envelope::explain`] says why
22//!   an ISP allows what it allows, and a [`Guarantee`] (the § 14a EnWG minimum) refuses any cap
23//!   below it.
24//! - An [`EnergyEnvelope`] adds bounds on a stored [`Level`] (a car's departure energy, a
25//!   battery's capacity) and gives a device's
26//!   [steady headroom](EnergyEnvelope::steady_headroom) over a window; [`pool`] sums devices,
27//!   says whether the result is exact, and checks a split.
28//! - A [`DeviationEnvelope`] is what a flexibility request asks for: [`Band`]s on the deviation
29//!   from a baseline, against which an offer's [`Misfit`]s are listed.
30//!
31//! ## Baselines and settlement
32//!
33//! - [`baseline`]: `dprognosis@1`, `schedule@1`, `mbma@1` and `xofy@1`, each with required
34//!   parameters and a [card](baseline::cards); a method id never changes its meaning.
35//! - [`settle`]: delivered flexibility and power deficiency per ISP, exactly as UFTP 3.1 § 2.6
36//!   computes them, at a recorded [`MeasurementPoint`]. A [`Settlement`] has a canonical text and a
37//!   `sha256:` [`Digest`] over RFC 8785 canonical JSON;
38//!   [`Settlement::from_canonical`] reads the other side's back and [`Settlement::diff`] names
39//!   where they part. [`Settlement::rebound`] reports what came back after the order.
40//! - [`accuracy`]: how well a method predicts a site, scored exactly.
41//!
42//! ## Protocols
43//!
44//! Each converter is a Cargo feature, off by default, lossless or refusing:
45//!
46//! | Feature | Protocol | Maps |
47//! |---|---|---|
48//! | `uftp` | UFTP 3.1 (Shapeshifter) | requests, offers, orders and settlement items |
49//! | `eebus` | EEBUS LPC and LPP | active and failsafe limits, timed or open-ended, both ways |
50//! | `s2` | S2 (EN 50491-12-2) | PEBC power envelopes, PPBC power sequences |
51//! | `openadr` | OpenADR 3 | import and export capacity limits, both ways; usage reports |
52//! | `csip` | CSIP-AUS (IEEE 2030.5) | dynamic operating envelopes at the connection point |
53//! | `iec104` | IEC 60870-5-104 | active-power set points, types 48–50, both ways |
54//! | `cls` | CLS.EEDI | control-box limits and failsafes, both ways |
55//! | `metering` | German metering rules | the § 14a minimum, Lastgang energy as power |
56//!
57//! ## Guarantees
58//!
59//! The crate reads no clock, file, network, environment or random source, and does no
60//! floating-point arithmetic: the same inputs give the same bytes on every machine. A float on the
61//! wire (S2, IEC 104) is read once, as the decimal written. What cannot be represented exactly is
62//! refused with an [`Error`] that names the values and offers a [`hint`](Error::hint), never
63//! rounded silently. Time is [`jiff`], with the time-zone database bundled.
64//!
65//! ```
66//! use flexibility::jiff::{civil::{date, time}, tz::TimeZone};
67//! use flexibility::*;
68//!
69//! let berlin = TimeZone::get("Europe/Berlin")?;
70//! let grid = Grid::day(date(2026, 12, 1), &berlin, IspDuration::FIFTEEN_MINUTES)?;
71//! let noon = grid.local(time(12, 0, 0, 0))?;
72//!
73//! // The grid operator caps consumption at 4.2 kW from 17:00 to 19:00 local time.
74//! let evening = grid.window(time(17, 0, 0, 0), time(19, 0, 0, 0))?;
75//! let dso = Provenance::new("dso.example", "order-42", noon);
76//! let envelope = Envelope::unbounded(grid.clone()).apply(&Limit::consumption_cap(evening, kw!(4.2), dso))?;
77//!
78//! // A car planned at 7.4 kW all evening breaks it in ISPs 69 to 76.
79//! let car = Provenance::new("agr.example", "plan-7", noon);
80//! let plan = Schedule::new(Series::filled(grid, kw!(7.4)), car);
81//! let violations = plan.check(&envelope)?;
82//! assert_eq!(violations.len(), 8);
83//! assert_eq!(
84//!     violations[0].to_string(),
85//!     "ISP 69 (17:00–17:15 +01:00): planned 7.4 kW above max 4.2 kW set by dso.example order-42"
86//! );
87//! # Ok::<(), Box<dyn std::error::Error>>(())
88//! ```
89
90#![forbid(unsafe_code)]
91
92// The README's example is compiled and run as a doctest.
93#[cfg(doctest)]
94#[doc = include_str!("../README.md")]
95struct ReadmeDoctests;
96
97pub mod accuracy;
98pub mod baseline;
99mod canon;
100#[cfg(feature = "cls")]
101pub mod cls;
102#[cfg(feature = "csip")]
103pub mod csip;
104#[cfg(feature = "eebus")]
105pub mod eebus;
106mod error;
107mod grid;
108#[cfg(feature = "iec104")]
109pub mod iec104;
110#[cfg(feature = "metering")]
111pub mod metering;
112#[cfg(feature = "openadr")]
113pub mod openadr;
114pub mod pool;
115mod power;
116mod rebound;
117mod relative;
118#[cfg(feature = "s2")]
119pub mod s2;
120mod series;
121mod settle;
122mod shape;
123mod storage;
124#[cfg(feature = "uftp")]
125pub mod uftp;
126
127pub use baseline::{Baseline, MethodId};
128pub use canon::{Digest, MAX_EXACT, MAX_RECEIPT_BYTES, canonical_series};
129pub use error::{Breach, Error};
130pub use grid::{Grid, IspDuration, IspLabel, MAX_ISPS, Window};
131#[doc(hidden)]
132pub use power::{__energy_literal, __literal};
133pub use power::{Deviation, Direction, Energy, Power, Rounding};
134pub use rebound::{Rebound, ReboundLine};
135pub use relative::{Band, DeviationEnvelope, Disposition, Misfit, MisfitKind};
136pub use series::Series;
137pub use settle::{DeviceId, Difference, Line, MeasurementPoint, Settlement, settle};
138pub use shape::{
139    Bounds, Broken, Envelope, Explanation, Guarantee, Headroom, Limit, Provenance, Schedule,
140    Violation,
141};
142pub use storage::{EnergyEnvelope, Level, LevelBroken, LevelViolation, Report};
143
144/// The `jiff` crate, whose `Timestamp`, `civil::Date`, `civil::Time` and `tz::TimeZone` appear
145/// in this crate's API.
146pub use jiff;
147
148/// A power literal in watts, exact and checked at compile time.
149///
150/// ```
151/// use flexibility::{w, Power};
152/// assert_eq!(w!(500), Power::from_watts(500));
153/// assert_eq!(w!(-3_000), Power::from_watts(-3_000));
154/// ```
155///
156/// A fraction of a watt does not compile:
157///
158/// ```compile_fail
159/// let _ = flexibility::w!(0.5);
160/// ```
161#[macro_export]
162macro_rules! w {
163    ($($literal:tt)+) => {
164        $crate::__power_literal!(0, "w!", $($literal)+)
165    };
166}
167
168/// A power literal in kilowatts, exact and checked at compile time: the macro reads the
169/// literal's *text*, never a float, so `kw!(4.2)` is exactly 4 200 W.
170///
171/// ```
172/// use flexibility::{kw, Power};
173/// assert_eq!(kw!(4.2), Power::from_watts(4_200));
174/// assert_eq!(kw!(-3), Power::from_watts(-3_000));
175/// assert_eq!(kw!(11), Power::from_watts(11_000));
176/// ```
177///
178/// A value that is not whole watts does not compile:
179///
180/// ```compile_fail
181/// let _ = flexibility::kw!(4.0001);
182/// ```
183#[macro_export]
184macro_rules! kw {
185    ($($literal:tt)+) => {
186        $crate::__power_literal!(3, "kw!", $($literal)+)
187    };
188}
189
190/// A power literal in megawatts, exact and checked at compile time.
191///
192/// ```
193/// use flexibility::{mw, Power};
194/// assert_eq!(mw!(1.5), Power::from_watts(1_500_000));
195/// ```
196#[macro_export]
197macro_rules! mw {
198    ($($literal:tt)+) => {
199        $crate::__power_literal!(6, "mw!", $($literal)+)
200    };
201}
202
203#[doc(hidden)]
204#[macro_export]
205macro_rules! __power_literal {
206    ($scale:expr, $name:literal, $($literal:tt)+) => {{
207        const POWER: $crate::Power = match $crate::__literal(stringify!($($literal)+), $scale) {
208            Some(power) => power,
209            None => panic!(concat!($name, ": not an exact number of whole watts")),
210        };
211        POWER
212    }};
213}
214
215/// An energy literal in watt-hours, exact and checked at compile time.
216///
217/// ```
218/// use flexibility::{wh, Energy};
219/// assert_eq!(wh!(500), Energy::from_watt_seconds(1_800_000));
220/// ```
221///
222/// A fraction of a watt-hour does not compile:
223///
224/// ```compile_fail
225/// let _ = flexibility::wh!(0.5);
226/// ```
227#[macro_export]
228macro_rules! wh {
229    ($($literal:tt)+) => {
230        $crate::__energy_literal!(0, "wh!", $($literal)+)
231    };
232}
233
234/// An energy literal in kilowatt-hours, exact and checked at compile time: `kwh!(30)` is
235/// 108 000 000 watt-seconds, `kwh!(1.5)` 1 500 Wh.
236///
237/// ```
238/// use flexibility::{kwh, Energy};
239/// assert_eq!(kwh!(1.5), Energy::from_watt_seconds(5_400_000));
240/// assert_eq!(kwh!(30).to_string(), "30 kWh");
241/// ```
242///
243/// ```compile_fail
244/// let _ = flexibility::kwh!(1.0001);
245/// ```
246#[macro_export]
247macro_rules! kwh {
248    ($($literal:tt)+) => {
249        $crate::__energy_literal!(3, "kwh!", $($literal)+)
250    };
251}
252
253/// An energy literal in megawatt-hours, exact and checked at compile time.
254///
255/// ```
256/// use flexibility::{mwh, kwh};
257/// assert_eq!(mwh!(1.2), kwh!(1_200));
258/// ```
259#[macro_export]
260macro_rules! mwh {
261    ($($literal:tt)+) => {
262        $crate::__energy_literal!(6, "mwh!", $($literal)+)
263    };
264}
265
266#[doc(hidden)]
267#[macro_export]
268macro_rules! __energy_literal {
269    ($scale:expr, $name:literal, $($literal:tt)+) => {{
270        const ENERGY: $crate::Energy = match $crate::__energy_literal(stringify!($($literal)+), $scale) {
271            Some(energy) => energy,
272            None => panic!(concat!($name, ": not an exact number of whole watt-hours")),
273        };
274        ENERGY
275    }};
276}