flexibility 0.4.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
//! 006: EEBUS LPC and LPP limits.
#![cfg(feature = "eebus")]

mod common;

use std::time::Duration;

use common::{at, day, dso};
use flexibility::eebus::ScaledNumber;
use flexibility::eebus::{self, Direction, LimitWrite};
use flexibility::jiff::Timestamp;
use flexibility::{Envelope, Error, Guarantee, Limit, Power, Rounding, Window, kw, w};
use proptest::prelude::*;

const TWO_HOURS: Duration = Duration::from_secs(7_200);

fn horizon() -> Timestamp {
    day().end()
}

#[test]
fn an_lpc_limit_is_a_consumption_cap_for_its_duration() {
    let write = LimitWrite::active_for(4_200, TWO_HOURS);
    let cap = eebus::limit(
        Direction::Consumption,
        &write,
        at(17, 0),
        horizon(),
        Rounding::Exact,
        dso(),
    )
    .unwrap()
    .unwrap();
    assert_eq!(cap.bounds().max(), Some(kw!(4.2)));
    assert_eq!(cap.bounds().min(), None);
    assert_eq!(cap.window(), Window::new(at(17, 0), at(19, 0)).unwrap());
    assert_eq!(cap.provenance(), &dso());
}

#[test]
fn an_lpp_limit_is_a_feed_in_cap() {
    // The EEBUS sign table: LPP takes a magnitude; the wire limit is ≤ 0 [LPP-001].
    let write = LimitWrite::active(3_000);
    let cap = eebus::limit(
        Direction::Production,
        &write,
        at(12, 0),
        horizon(),
        Rounding::Exact,
        dso(),
    )
    .unwrap()
    .unwrap();
    assert_eq!(cap.bounds().min(), Some(kw!(-3)));
    assert_eq!(cap.bounds().max(), None);
    assert_eq!(
        cap.window().until(),
        horizon(),
        "no duration: the caller's horizon"
    );
}

#[test]
fn a_deactivated_write_sets_no_limit() {
    assert_eq!(
        eebus::limit(
            Direction::Consumption,
            &LimitWrite::deactivated(),
            at(17, 0),
            horizon(),
            Rounding::Exact,
            dso()
        )
        .unwrap(),
        None
    );
}

#[test]
fn fractions_and_negative_values_are_refused() {
    for value in [ScaledNumber::new(42_005, -1), ScaledNumber::whole(-1)] {
        let write = LimitWrite::active(value);
        let err = eebus::limit(
            Direction::Consumption,
            &write,
            at(17, 0),
            horizon(),
            Rounding::Exact,
            dso(),
        )
        .unwrap_err();
        assert!(
            matches!(
                err,
                Error::Unrepresentable {
                    protocol: "EEBUS",
                    field: "limit",
                    ..
                }
            ),
            "{err}"
        );
    }
    assert!(err_text(ScaledNumber::new(42_005, -1)).contains("4200.5"));
    // A whole watt written in milliwatts is a whole watt.
    let milli = LimitWrite::active(ScaledNumber::new(4_200_000, -3));
    let cap = eebus::limit(
        Direction::Consumption,
        &milli,
        at(17, 0),
        horizon(),
        Rounding::Exact,
        dso(),
    )
    .unwrap()
    .unwrap();
    assert_eq!(cap.bounds().max(), Some(w!(4200)));
}

fn err_text(value: ScaledNumber) -> String {
    eebus::limit(
        Direction::Consumption,
        &LimitWrite::active(value),
        at(17, 0),
        horizon(),
        Rounding::Exact,
        dso(),
    )
    .unwrap_err()
    .to_string()
}

#[test]
fn a_duration_past_the_time_range_is_refused() {
    let write = LimitWrite::active_for(1, Duration::MAX);
    assert!(matches!(
        eebus::limit(
            Direction::Consumption,
            &write,
            at(17, 0),
            horizon(),
            Rounding::Exact,
            dso()
        ),
        Err(Error::Unrepresentable {
            field: "duration",
            ..
        })
    ));
}

#[test]
fn a_failsafe_below_the_guarantee_is_refused() {
    let g = day();
    let all = Window::new(g.start(), g.end()).unwrap();
    let rule = flexibility::Provenance::new("bnetza.de", "§ 14a minimum", Timestamp::UNIX_EPOCH);
    let site = Envelope::unbounded(g)
        .guarantee(&Guarantee::consumption(all, kw!(4.2), rule).unwrap())
        .unwrap();
    let fallback = Window::new(at(17, 0), at(19, 0)).unwrap();
    let ok = eebus::failsafe(
        Direction::Consumption,
        4_200,
        fallback,
        Rounding::Exact,
        dso(),
    )
    .unwrap();
    assert!(site.apply(&ok).is_ok());
    let low = eebus::failsafe(
        Direction::Consumption,
        3_000,
        fallback,
        Rounding::Exact,
        dso(),
    )
    .unwrap();
    assert!(matches!(site.apply(&low), Err(Error::GuaranteeBreached(_))));
}

#[test]
fn a_limit_is_written_with_the_duration_left() {
    let cap = Limit::consumption_cap(Window::new(at(17, 0), at(19, 0)).unwrap(), kw!(4.2), dso());
    let (direction, write) = eebus::write(&cap, at(17, 30)).unwrap();
    assert_eq!(direction, Direction::Consumption);
    assert!(write.is_active);
    assert_eq!(write.value.to_i64(), Some(4_200));
    assert_eq!(write.duration, Some(Duration::from_secs(90 * 60)));

    let feed_in =
        Limit::feed_in_cap(Window::new(at(12, 0), at(13, 0)).unwrap(), kw!(3), dso()).unwrap();
    let (direction, write) = eebus::write(&feed_in, at(12, 0)).unwrap();
    assert_eq!(
        (direction, write.value.to_i64()),
        (Direction::Production, Some(3_000))
    );
}

#[test]
fn what_eebus_cannot_carry_is_refused() {
    let evening = Window::new(at(17, 0), at(19, 0)).unwrap();
    let band = Limit::new(
        evening,
        flexibility::Bounds::new(Some(kw!(-1)), Some(kw!(1))).unwrap(),
        dso(),
    );
    let below_zero = Limit::consumption_cap(evening, kw!(-1), dso());
    let cap = Limit::consumption_cap(evening, kw!(4.2), dso());
    for (limit, when) in [
        (&band, at(17, 0)),
        (&below_zero, at(17, 0)),
        (&cap, at(19, 0)),
        (&cap, at(16, 0)),
    ] {
        assert!(
            matches!(
                eebus::write(limit, when),
                Err(Error::Unrepresentable {
                    protocol: "EEBUS",
                    ..
                })
            ),
            "{:?} at {when}",
            limit.bounds()
        );
    }
}

// --- 019: open-ended writes and rounding -----------------------------------------------------

#[test]
fn a_limit_written_open_ended_has_no_duration_and_reads_back_to_the_horizon() {
    let cap = Limit::consumption_cap(Window::new(at(16, 0), at(19, 0)).unwrap(), kw!(4.2), dso());
    let (direction, write) = eebus::write_open(&cap, at(16, 0)).unwrap();
    assert_eq!(direction, Direction::Consumption);
    assert_eq!(write, LimitWrite::active(4_200));
    assert_eq!(write.duration, None);
    let back = eebus::limit(
        direction,
        &write,
        at(16, 0),
        horizon(),
        Rounding::Exact,
        dso(),
    )
    .unwrap()
    .unwrap();
    assert_eq!(back.bounds(), cap.bounds());
    assert_eq!(back.window(), Window::new(at(16, 0), horizon()).unwrap());

    let feed_in =
        Limit::feed_in_cap(Window::new(at(12, 0), at(13, 0)).unwrap(), kw!(3), dso()).unwrap();
    assert_eq!(
        eebus::write_open(&feed_in, at(12, 30)).unwrap(),
        (Direction::Production, LimitWrite::active(3_000))
    );
}

#[test]
fn an_open_ended_write_refuses_what_a_timed_write_refuses() {
    let evening = Window::new(at(17, 0), at(19, 0)).unwrap();
    let band = Limit::new(
        evening,
        flexibility::Bounds::new(Some(kw!(-1)), Some(kw!(1))).unwrap(),
        dso(),
    );
    let below_zero = Limit::consumption_cap(evening, kw!(-1), dso());
    let cap = Limit::consumption_cap(evening, kw!(4.2), dso());
    for (limit, when) in [
        (&band, at(17, 0)),
        (&below_zero, at(17, 0)),
        (&cap, at(19, 0)),
        (&cap, at(16, 0)),
    ] {
        assert_eq!(
            eebus::write_open(limit, when).unwrap_err(),
            eebus::write(limit, when).unwrap_err()
        );
    }
}

fn read(direction: Direction, value: ScaledNumber, rounding: Rounding) -> Result<Limit, Error> {
    eebus::limit(
        direction,
        &LimitWrite::active(value),
        at(17, 0),
        horizon(),
        rounding,
        dso(),
    )
    .map(Option::unwrap)
}

#[test]
fn an_acknowledged_fraction_reads_as_the_rounding_names() {
    let ack = ScaledNumber::new(42_005, -1);
    let lpc = |r| read(Direction::Consumption, ack, r).map(|l| l.bounds().max());
    assert_eq!(lpc(Rounding::TowardZero).unwrap(), Some(w!(4200)));
    assert_eq!(lpc(Rounding::HalfAwayFromZero).unwrap(), Some(w!(4201)));
    assert!(
        lpc(Rounding::Exact)
            .unwrap_err()
            .to_string()
            .contains("4200.5")
    );
    // LPP: toward zero is the shallower feed-in, the stricter cap.
    let lpp = read(Direction::Production, ack, Rounding::TowardZero).unwrap();
    assert_eq!(lpp.bounds().min(), Some(w!(-4200)));
    // A failsafe follows the same rules.
    let fallback = Window::new(at(17, 0), at(19, 0)).unwrap();
    let failsafe = |r| eebus::failsafe(Direction::Consumption, ack, fallback, r, dso());
    assert_eq!(
        failsafe(Rounding::TowardZero).unwrap().bounds().max(),
        Some(w!(4200))
    );
    assert!(failsafe(Rounding::Exact).is_err());
}

#[test]
fn a_whole_value_reads_the_same_under_every_rounding() {
    for rounding in [
        Rounding::Exact,
        Rounding::TowardZero,
        Rounding::HalfAwayFromZero,
    ] {
        let cap = read(Direction::Consumption, ScaledNumber::new(42, 2), rounding).unwrap();
        assert_eq!(cap.bounds().max(), Some(w!(4200)));
    }
}

#[test]
fn extreme_scales_round_to_zero_or_are_refused() {
    let tiny = ScaledNumber::new(5, i16::MIN);
    assert_eq!(
        read(Direction::Consumption, tiny, Rounding::TowardZero)
            .unwrap()
            .bounds()
            .max(),
        Some(Power::ZERO)
    );
    assert!(read(Direction::Consumption, tiny, Rounding::Exact).is_err());
    for huge in [
        ScaledNumber::new(1, 19),
        ScaledNumber::new(i64::MAX, i16::MAX),
    ] {
        for rounding in [
            Rounding::Exact,
            Rounding::TowardZero,
            Rounding::HalfAwayFromZero,
        ] {
            let err = read(Direction::Consumption, huge, rounding).unwrap_err();
            assert!(err.to_string().contains("range"), "{err}");
        }
    }
    for rounding in [Rounding::TowardZero, Rounding::HalfAwayFromZero] {
        assert!(read(Direction::Consumption, ScaledNumber::new(-1, -1), rounding).is_err());
        assert_eq!(
            eebus::limit(
                Direction::Consumption,
                &LimitWrite::deactivated(),
                at(17, 0),
                horizon(),
                rounding,
                dso()
            )
            .unwrap(),
            None
        );
    }
}

proptest! {
    // SC-002: a limit EEBUS can carry, written at its start and read back, is the same limit.
    #[test]
    fn every_representable_limit_round_trips(watts in 0i64..=10_000_000, minutes in 1i64..=1_440, lpp: bool) {
        let from = at(0, 0);
        let window = Window::new(from, from + flexibility::jiff::SignedDuration::from_mins(minutes)).unwrap();
        let p = Power::from_watts(watts);
        let limit = if lpp {
            Limit::feed_in_cap(window, p, dso()).unwrap()
        } else {
            Limit::consumption_cap(window, p, dso())
        };
        let (direction, write) = eebus::write(&limit, from).unwrap();
        let back = eebus::limit(direction, &write, from, horizon(), Rounding::Exact, dso()).unwrap().unwrap();
        prop_assert_eq!(back, limit);
    }

    // SC-002: toward zero never loosens an acknowledged value and is less than a watt stricter;
    // exact reads it iff it is whole.
    #[test]
    fn toward_zero_never_loosens(number in 0i64..=i64::MAX / 1_000, scale in -6i16..=2, lpp: bool) {
        let direction = if lpp { Direction::Production } else { Direction::Consumption };
        let value = ScaledNumber::new(number, scale);
        let cap = read(direction, value, Rounding::TowardZero).unwrap();
        let bound = if lpp { cap.bounds().min() } else { cap.bounds().max() };
        let magnitude = i128::from(bound.unwrap().watts().abs());
        // In microwatts: magnitude ≤ value < magnitude + 1 W.
        let value_uw = i128::from(number) * 10_i128.pow(u32::try_from(6 + scale).unwrap());
        prop_assert!(magnitude * 1_000_000 <= value_uw && value_uw < (magnitude + 1) * 1_000_000);
        prop_assert_eq!(
            read(direction, value, Rounding::Exact).is_ok(),
            magnitude * 1_000_000 == value_uw
        );
    }
}