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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
//! Generated cases: combination algebra and freedom from panics.

mod common;

use flexibility::MeasurementPoint;
use flexibility::jiff::tz::TimeZone;
use flexibility::jiff::{SignedDuration, Timestamp};
use flexibility::{
    Bounds, Envelope, Grid, IspDuration, Limit, Power, Provenance, Schedule, Series, Window,
};
use proptest::prelude::*;

const ISPS: u32 = 8;

fn grid() -> Grid {
    Grid::new(
        Timestamp::UNIX_EPOCH,
        IspDuration::FIFTEEN_MINUTES,
        ISPS,
        TimeZone::UTC,
    )
    .unwrap()
}

fn bounds() -> impl Strategy<Value = Bounds> {
    (
        proptest::option::of(-10_000_i64..10_000),
        proptest::option::of(-10_000_i64..10_000),
    )
        .prop_map(|(a, b)| {
            let (min, max) = match (a, b) {
                (Some(a), Some(b)) => (Some(a.min(b)), Some(a.max(b))),
                other => other,
            };
            Bounds::new(min.map(Power::from_watts), max.map(Power::from_watts)).unwrap()
        })
}

/// An envelope from up to three limits; `None` if they conflict.
fn envelope(tag: &'static str) -> impl Strategy<Value = Option<Envelope>> {
    proptest::collection::vec((0_i64..120, 1_i64..120, bounds()), 0..3).prop_map(move |limits| {
        let mut env = Envelope::unbounded(grid());
        for (i, (from, len, b)) in limits.into_iter().enumerate() {
            let from_t = Timestamp::UNIX_EPOCH + SignedDuration::from_mins(from);
            let until = from_t + SignedDuration::from_mins(len);
            let p = Provenance::new(tag, i.to_string(), Timestamp::UNIX_EPOCH);
            env = env
                .apply(&Limit::new(Window::new(from_t, until).ok()?, b, p))
                .ok()?;
        }
        Some(env)
    })
}

fn all_bounds(e: &Envelope) -> Vec<Bounds> {
    (1..=ISPS).map(|i| e.bounds(i).unwrap()).collect()
}

proptest! {
    #![proptest_config(ProptestConfig::with_cases(1_000))]

    // units-and-shapes/SR-001: commutative on bounds, and never wider than either input.
    #[test]
    fn combine_is_commutative_and_never_widens(a in envelope("a"), b in envelope("b")) {
        let (Some(a), Some(b)) = (a, b) else { return Ok(()) };
        match (a.combine(&b), b.combine(&a)) {
            (Ok(ab), Ok(ba)) => {
                prop_assert_eq!(all_bounds(&ab), all_bounds(&ba));
                for isp in 1..=ISPS {
                    let c = ab.bounds(isp).unwrap();
                    for side in [a.bounds(isp).unwrap(), b.bounds(isp).unwrap()] {
                        if let Some(m) = side.max() { prop_assert!(c.max().is_some_and(|x| x <= m)); }
                        if let Some(m) = side.min() { prop_assert!(c.min().is_some_and(|x| x >= m)); }
                    }
                }
            }
            (Err(x), Err(y)) => prop_assert_eq!(x, y),
            _ => prop_assert!(false, "one order failed, the other did not"),
        }
    }

    #[test]
    fn combine_is_associative(a in envelope("a"), b in envelope("b"), c in envelope("c")) {
        let (Some(a), Some(b), Some(c)) = (a, b, c) else { return Ok(()) };
        let left = a.combine(&b).and_then(|ab| ab.combine(&c));
        let right = b.combine(&c).and_then(|bc| a.combine(&bc));
        match (left, right) {
            (Ok(l), Ok(r)) => prop_assert_eq!(all_bounds(&l), all_bounds(&r)),
            (Err(_), Err(_)) => {}
            _ => prop_assert!(false, "associativity broke on failure"),
        }
    }

    // units-and-shapes/SR-006: no public operation panics on extreme input.
    #[test]
    fn nothing_panics(
        x in any::<i64>(), y in any::<i64>(), m in any::<u64>(),
        start in any::<i64>(), minutes in any::<u16>(), count in any::<u32>(),
        isp in any::<u32>(), from in any::<i64>(), until in any::<i64>(),
    ) {
        let (p, q) = (Power::from_watts(x), Power::from_watts(y));
        let _ = (p.checked_add(q), p.checked_sub(q), p.checked_neg(), p.magnitude(), p.direction());
        let _ = (Power::consumption(m), Power::feed_in(m), Bounds::new(Some(p), Some(q)));
        let t = |s: i64| Timestamp::from_second(s.rem_euclid(253_402_207_200) - 62_135_596_800).unwrap_or(Timestamp::UNIX_EPOCH);
        let _ = IspDuration::from_minutes(minutes);
        let isp_len = IspDuration::from_minutes(minutes).unwrap_or(IspDuration::FIFTEEN_MINUTES);
        if let Ok(g) = Grid::new(t(start), isp_len, count % 2_000, TimeZone::UTC) {
            let _ = (g.interval(isp), g.isp_at(t(from)), Window::new(t(from), t(until)).ok().and_then(|w| g.isps(w)), g.end());
            let env = Envelope::unbounded(g.clone());
            let prov = Provenance::new("p", "r", t(start));
            if let Ok(b) = Bounds::new(Some(p.min(q)), Some(p.max(q)))
                && let Ok(win) = Window::new(t(from), t(until))
                && let l = Limit::new(win, b, prov.clone())
            {
                let _ = l.isps(&g);
                if let Ok(e) = env.apply(&l) {
                    let _ = (e.bounds(isp), e.max_source(isp), e.min_source(isp));
                    let plan = Schedule::new(Series::filled(g, p), prov);
                    let _ = plan.check(&e);
                }
            }
        }
    }
}

proptest! {
    #![proptest_config(ProptestConfig::with_cases(2_000))]

    // ergonomics-and-explain/SR-002, SC-002: display then parse is the identity, over all i64.
    #[test]
    fn power_text_round_trips(watts in any::<i64>()) {
        let p = Power::from_watts(watts);
        prop_assert_eq!(p.to_string().parse::<Power>().unwrap(), p);
        prop_assert_eq!(format!("{p:#}").parse::<Power>().unwrap(), p);
        let d = flexibility::Deviation::from_watts(watts);
        prop_assert_eq!(d.to_string().parse::<flexibility::Deviation>().unwrap(), d);
    }

    // ergonomics-and-explain/SR-004: a deviation added back gives the power it came from.
    #[test]
    fn deviation_adds_back(a in any::<i64>(), b in any::<i64>()) {
        let (a, b) = (Power::from_watts(a), Power::from_watts(b));
        if let Ok(d) = a.deviation_from(b) {
            prop_assert_eq!(b.checked_add_deviation(d).unwrap(), a);
        }
    }

    // ergonomics-and-explain/SR-007: the new operations never panic.
    #[test]
    fn new_operations_never_panic(text in "\\PC{0,80}", x in any::<i64>(), minutes in 1_u16..=1440, isp in any::<u32>()) {
        let _ = text.parse::<Power>();
        let _ = text.parse::<flexibility::Deviation>();
        let p = Power::from_watts(x);
        let len = IspDuration::from_minutes(minutes).unwrap_or(IspDuration::FIFTEEN_MINUTES);
        let _ = (p.energy(len), p.to_string(), format!("{p:#}"));
        let e = flexibility::Energy::from_watt_seconds(x);
        let _ = (e.to_string(), Power::average(e, len, flexibility::Rounding::Exact));
        let _ = Power::average(e, len, flexibility::Rounding::HalfAwayFromZero);
        let g = grid();
        let _ = (g.label(isp), g.label(isp).map(|l| l.to_string()));
        let env = Envelope::unbounded(g.clone());
        let _ = env.explain(isp).map(|e| e.to_string());
        let _ = env.headroom(&Schedule::new(Series::filled(g, p), Provenance::new("p", "r", Timestamp::UNIX_EPOCH)));
    }
}

mod settlement_properties {
    use super::*;
    use flexibility::baseline::{self, Adjustment, XofY};
    use flexibility::{Deviation, settle};

    fn one(base: i64, actual: i64, order: i64) -> (i64, i64) {
        let g = Grid::new(
            Timestamp::UNIX_EPOCH,
            IspDuration::FIFTEEN_MINUTES,
            1,
            TimeZone::UTC,
        )
        .unwrap();
        let all = Window::new(g.start(), g.end()).unwrap();
        let p = Provenance::new("p", "r", Timestamp::UNIX_EPOCH);
        let b = baseline::dprognosis(
            &Schedule::new(Series::filled(g.clone(), Power::from_watts(base)), p),
            all,
        )
        .unwrap();
        let s = settle(
            &b,
            &Series::filled(g.clone(), Power::from_watts(actual)),
            &Series::filled(g, Deviation::from_watts(order)),
            MeasurementPoint::ConnectionPoint,
        )
        .unwrap();
        (
            s.lines()[0].delivered.watts(),
            s.lines()[0].deficiency.watts(),
        )
    }

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(2_000))]

        // baselines-and-settlement/SR-001, SC-002: conservation and mirror symmetry.
        #[test]
        fn delivered_and_deficiency_conserve_the_order(b in -50_000i64..50_000, a in -50_000i64..50_000, o in -20_000i64..20_000) {
            let (delivered, deficiency) = one(b, a, o);
            let r = (a - b) * o.signum();
            prop_assert_eq!(delivered.abs() + deficiency, o.abs() + (-r).max(0) * i64::from(o != 0));
            prop_assert!(delivered.abs() <= o.abs());
            prop_assert!(deficiency >= 0);
            prop_assert!(delivered == 0 || delivered.signum() == o.signum());
            prop_assert_eq!(one(-b, -a, -o), (-delivered, deficiency));
        }

        // baselines-and-settlement/SR-004: X-of-Y does not depend on the order of the days.
        #[test]
        fn xofy_is_order_independent(levels in proptest::collection::vec(0i64..5, 4), x in 1u32..=4, rotate in 0usize..4) {
            let berlin = TimeZone::get("Europe/Berlin").unwrap();
            let d = |n: i8| flexibility::jiff::civil::date(2026, 11, n);
            let day = Grid::day(d(30), &berlin, IspDuration::FIFTEEN_MINUTES).unwrap();
            let history: Vec<_> = levels.iter().enumerate().map(|(i, &l)| {
                let g = Grid::day(d(20 + i8::try_from(i).unwrap()), &berlin, IspDuration::FIFTEEN_MINUTES).unwrap();
                Series::filled(g, Power::from_watts(l * 1_000))
            }).collect();
            let mut shuffled = history.clone();
            shuffled.rotate_left(rotate);
            let event = Window::new(day.start(), day.end()).unwrap();
            let p = XofY { x, y: 4, adjustment: Adjustment::None };
            let a = baseline::xofy(&day, event, &history, None, p).unwrap();
            let b = baseline::xofy(&day, event, &shuffled, None, p).unwrap();
            prop_assert_eq!(a.digest(), b.digest());
        }

        // baselines-and-settlement/SR-003: different provenance strings give different texts.
        #[test]
        fn canonical_text_is_injective_on_strings(a in "\\PC{0,12}", b in "\\PC{0,12}") {
            let g = grid();
            let all = Window::new(g.start(), g.end()).unwrap();
            let s = |issuer: &str| {
                let p = Provenance::new(issuer, "r", Timestamp::UNIX_EPOCH);
                baseline::schedule(&Schedule::new(Series::filled(g.clone(), Power::ZERO), p), all).unwrap().canonical()
            };
            prop_assert_eq!(s(&a) == s(&b), a == b);
        }

        // baselines-and-settlement/SR-007: settlement never panics.
        #[test]
        fn settlement_never_panics(b in any::<i64>(), a in any::<i64>(), o in any::<i64>()) {
            let g = Grid::new(Timestamp::UNIX_EPOCH, IspDuration::FIFTEEN_MINUTES, 1, TimeZone::UTC).unwrap();
            let all = Window::new(g.start(), g.end()).unwrap();
            let p = Provenance::new("p", "r", Timestamp::UNIX_EPOCH);
            // Beyond ±2^53 W the baseline is refused (canon@1 integers are exact); never a panic.
            let Ok(base) = baseline::dprognosis(&Schedule::new(Series::filled(g.clone(), Power::from_watts(b)), p), all) else {
                return Ok(());
            };
            let _ = settle(&base, &Series::filled(g.clone(), Power::from_watts(a)), &Series::filled(g.clone(), Deviation::from_watts(o)), MeasurementPoint::ConnectionPoint);
            let _ = flexibility::accuracy::score([(base.series(), &Series::filled(g, Power::from_watts(a)))]);
        }
    }
}

// --- 007 storage and pools -----------------------------------------------------------------------

mod pools {
    use super::*;
    use flexibility::pool;
    use flexibility::{Energy, EnergyEnvelope, Level};

    const N: u32 = 3;

    fn g() -> Grid {
        Grid::new(
            Timestamp::UNIX_EPOCH,
            IspDuration::FIFTEEN_MINUTES,
            N,
            TimeZone::UTC,
        )
        .unwrap()
    }

    fn who() -> Provenance {
        Provenance::new("p", "q", Timestamp::UNIX_EPOCH)
    }

    /// A device whose plan fits by construction: power bounds around the plan, level bounds
    /// around the levels the plan reaches, each side present or absent at random.
    fn device() -> impl Strategy<Value = (EnergyEnvelope, Schedule)> {
        (
            proptest::collection::vec(-4_000_i64..4_000, N as usize),
            0_i64..10_000_000,
            proptest::collection::vec(
                (0_i64..1_000, 0_i64..1_000, any::<bool>(), any::<bool>()),
                N as usize,
            ),
            proptest::collection::vec(
                (0_i64..900_000, 0_i64..900_000, any::<bool>(), any::<bool>()),
                N as usize,
            ),
        )
            .prop_map(|(watts, initial, slack, level_slack)| {
                let grid = g();
                let mut env = Envelope::unbounded(grid.clone());
                let mut level = initial;
                let mut storage_bounds = Vec::new();
                for (i, &w) in watts.iter().enumerate() {
                    let n = u32::try_from(i).unwrap() + 1;
                    let (lo, hi, has_lo, has_hi) = slack[i];
                    let b = Bounds::new(
                        has_lo.then(|| Power::from_watts(w - lo)),
                        has_hi.then(|| Power::from_watts(w + hi)),
                    )
                    .unwrap();
                    env = env
                        .apply(&Limit::new(grid.interval(n).unwrap(), b, who()))
                        .unwrap();
                    level += w * 900;
                    let (lo, hi, has_lo, has_hi) = level_slack[i];
                    storage_bounds.push((
                        grid.interval(n).unwrap().until(),
                        Level::new(
                            has_lo.then(|| Energy::from_watt_seconds(level - lo)),
                            has_hi.then(|| Energy::from_watt_seconds(level + hi)),
                        )
                        .unwrap(),
                    ));
                }
                let mut e = EnergyEnvelope::new(env, Energy::from_watt_seconds(initial));
                for (at, l) in storage_bounds {
                    e = e.level_at(at, l, who()).unwrap();
                }
                let plan = Schedule::new(
                    Series::new(grid, watts.into_iter().map(Power::from_watts).collect()).unwrap(),
                    who(),
                );
                (e, plan)
            })
    }

    proptest! {
        // SC-002: every combination of device plans that each fit sums to a plan that fits the
        // (outer) aggregate, and the split check of that split passes.
        #[test]
        fn the_aggregate_contains_every_valid_split(devices in proptest::collection::vec(device(), 1..4)) {
            let envs: Vec<_> = devices.iter().map(|(e, _)| e.clone()).collect();
            let agg = pool::aggregate(&envs, who()).unwrap();
            let sum = (0..N as usize)
                .map(|k| Power::from_watts(devices.iter().map(|(_, p)| p.series().values()[k].watts()).sum()))
                .collect();
            let pool_plan = Schedule::new(Series::new(g(), sum).unwrap(), who());
            prop_assert!(agg.envelope().check(&pool_plan).unwrap().fits());
            let split: Vec<_> = devices.iter().map(|(e, p)| (e, p)).collect();
            prop_assert!(pool::check_split(&pool_plan, &split).unwrap().fits());
        }

        // SC-003: for power boxes, a pool plan fits the exact aggregate exactly when some split
        // across the two devices fits (brute force over device A's power, in steps of 1 W).
        #[test]
        fn boxes_aggregate_exactly(
            a in (-20_i64..20, 0_i64..20), b in (-20_i64..20, 0_i64..20), p in -60_i64..60,
        ) {
            let grid = Grid::new(Timestamp::UNIX_EPOCH, IspDuration::FIFTEEN_MINUTES, 1, TimeZone::UTC).unwrap();
            let all = Window::new(grid.start(), grid.end()).unwrap();
            let boxed = |(lo, width): (i64, i64)| {
                let b = Bounds::new(Some(Power::from_watts(lo)), Some(Power::from_watts(lo + width))).unwrap();
                EnergyEnvelope::new(Envelope::unbounded(grid.clone()).apply(&Limit::new(all, b, who())).unwrap(), Energy::ZERO)
            };
            let agg = pool::aggregate(&[boxed(a), boxed(b)], who()).unwrap();
            prop_assert!(agg.is_exact());
            let pool_plan = Schedule::new(Series::filled(grid.clone(), Power::from_watts(p)), who());
            let fits = agg.envelope().check(&pool_plan).unwrap().fits();
            let some_split = (a.0..=a.0 + a.1).any(|x| (b.0..=b.0 + b.1).contains(&(p - x)));
            prop_assert_eq!(fits, some_split);
        }
    }
}

// --- 008 reading a received settlement -----------------------------------------------------------

mod receipts {
    use super::*;
    use flexibility::{Deviation, Settlement, baseline, settle};

    fn settled(base: i64, actual: &[i64], order: i64) -> Settlement {
        let g = Grid::new(
            Timestamp::UNIX_EPOCH,
            IspDuration::FIFTEEN_MINUTES,
            u32::try_from(actual.len()).unwrap(),
            TimeZone::UTC,
        )
        .unwrap();
        let who = Provenance::new("p", "q", Timestamp::UNIX_EPOCH);
        let all = Window::new(g.start(), g.end()).unwrap();
        let b = baseline::dprognosis(
            &Schedule::new(Series::filled(g.clone(), Power::from_watts(base)), who),
            all,
        )
        .unwrap();
        let a = Series::new(
            g.clone(),
            actual.iter().map(|&w| Power::from_watts(w)).collect(),
        )
        .unwrap();
        settle(
            &b,
            &a,
            &Series::filled(g, Deviation::from_watts(order)),
            MeasurementPoint::ConnectionPoint,
        )
        .unwrap()
    }

    proptest! {
        // SC-001: every settlement reads back equal from its canonical text.
        #[test]
        fn every_settlement_reads_back(base in -1_000_000i64..1_000_000, actual in proptest::collection::vec(-1_000_000i64..1_000_000, 1..6), order in -500_000i64..500_000) {
            let s = settled(base, &actual, order);
            prop_assert_eq!(Settlement::from_canonical(&s.canonical(), TimeZone::UTC).unwrap(), s);
        }

        // SC-002: a single-byte change is refused or reads as a settlement with another digest.
        #[test]
        fn a_changed_byte_never_keeps_the_digest(actual in proptest::collection::vec(-100_000i64..100_000, 1..4), at in any::<prop::sample::Index>(), byte in 0x20u8..0x7f) {
            let s = settled(50_000, &actual, -20_000);
            let mut bytes = s.canonical().into_bytes();
            let i = at.index(bytes.len());
            prop_assume!(bytes[i] != byte);
            bytes[i] = byte;
            if let Ok(text) = String::from_utf8(bytes)
                && let Ok(read) = Settlement::from_canonical(&text, TimeZone::UTC)
            {
                prop_assert_ne!(read.digest(), s.digest());
            }
        }

        // SC-003: arbitrary text never panics the reader.
        #[test]
        fn arbitrary_text_never_panics(text in "\\PC{0,200}", prefix in "[\\[{\"0-9,:-]{0,40}") {
            let _ = Settlement::from_canonical(&text, TimeZone::UTC);
            let _ = Settlement::from_canonical(&format!("{prefix}{text}"), TimeZone::UTC);
        }
    }
}