flexibility 0.1.0

Grid flexibility as exact, replayable arithmetic: limits, baselines, UFTP-exact settlement, and UFTP, EEBUS, S2, OpenADR, IEC 104 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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
//! UFTP 3.1 in this crate's shapes, behind the `uftp` feature: a FlexRequest as a
//! [`DeviationEnvelope`], a FlexOffer option or a FlexOrder as a deviation series, the
//! FlexOrderSettlement item for an order, and the check a receiver can run on a settlement
//! alone.
//!
//! UFTP's power sign is this crate's: *"A positive value indicates that power flows towards the
//! prosumer (consumption)"* [UFTP 3.1 § 4.2.1], so MinPower, MaxPower, ISP Power,
//! BaselinePower, ActualPower and OrderedFlexPower map without change. The specification does
//! not sign DeliveredFlexPower and PowerDeficiency, so every function that writes or checks
//! them takes a [`FlexSign`] and none assumes one.
//!
//! ```
//! # use flexibility::uftp::{self, FlexSign};
//! # use flexibility::{baseline::Baseline, MeasurementPoint, Power, Rounding, Series, settle};
//! # fn order() -> uftp::wire::FlexOrder { unimplemented!() }
//! # fn baseline(_: &flexibility::Grid) -> Baseline { unimplemented!() }
//! # fn metered(_: &flexibility::Grid) -> Series<Power> { unimplemented!() }
//! # fn _doc() -> Result<(), flexibility::Error> {
//! // A DSO settles an order and builds the item the aggregator's UFTP check accepts:
//! let order = order();
//! let ordered = uftp::ordered(&order, Rounding::HalfAwayFromZero)?;
//! let ours = settle(&baseline(ordered.grid()), &metered(ordered.grid()), &ordered, MeasurementPoint::ConnectionPoint)?;
//! let item = uftp::settlement(&order, &ours, FlexSign::AsOrdered)?;
//!
//! // The aggregator checks a received item from its own fields:
//! for d in uftp::check(&item, FlexSign::AsOrdered)? {
//!     println!("{d}"); // ISP 71: PowerDeficiency sent 0 W, expected -1 MW
//! }
//! # Ok(()) }
//! ```

use std::collections::BTreeMap;
use std::fmt;

use crate::power::div_round;
use crate::settle::settle_isp;
use crate::{
    Band, Deviation, DeviationEnvelope, Disposition, Error, Grid, IspDuration, MAX_ISPS, MethodId,
    Provenance, Rounding, Series, Settlement,
};

/// The `uftp` crate this feature maps to.
pub use ::uftp as wire;

const PROTOCOL: &str = "UFTP";

/// How DeliveredFlexPower and PowerDeficiency are signed on the wire. There is no default: the
/// UFTP specification does not say, so the contract must.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum FlexSign {
    /// Both are magnitudes, never negative, as the table of UFTP 3.1 § 2.6.2 prints them.
    Magnitude,
    /// Both carry the sign of OrderedFlexPower, as the `uftp` crate documents them (its spec
    /// note SS-25): an order of −300 kW of which 280 kW was delivered is −280 000 W delivered
    /// and −20 000 W deficiency.
    AsOrdered,
}

impl FlexSign {
    /// The wire values of the rule's `delivered` (signed like `ordered`) and `deficiency` (a
    /// magnitude). The one place the reading is applied.
    fn write(self, delivered: i128, deficiency: i128, ordered: i128) -> (i128, i128) {
        match self {
            FlexSign::Magnitude => (delivered.abs(), deficiency),
            FlexSign::AsOrdered => (delivered, deficiency * ordered.signum()),
        }
    }
}

/// A received value the settlement rule does not give, or an ISP on one side only.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Discrepancy {
    /// The ISP, numbered per day as UFTP numbers it.
    pub isp: u32,
    /// What is wrong.
    pub kind: Kind,
}

/// What a [`Discrepancy`] is.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Kind {
    /// A field differs: the message sent `sent`, the rule or our settlement gives `expected`.
    Field {
        /// The UFTP attribute.
        field: &'static str,
        /// The value in the message, in watts.
        sent: i64,
        /// The value expected, in watts.
        expected: i64,
    },
    /// The message addresses the ISP more than once.
    Duplicate,
    /// Our settlement has the ISP; the message does not.
    MissingInMessage,
    /// The message has the ISP; our settlement does not.
    MissingInOurs,
}

impl fmt::Display for Discrepancy {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let w = |watts: i64| crate::Power::from_watts(watts);
        match self.kind {
            Kind::Field {
                field,
                sent,
                expected,
            } => write!(
                f,
                "ISP {}: {field} sent {}, expected {}",
                self.isp,
                w(sent),
                w(expected)
            ),
            Kind::Duplicate => write!(f, "ISP {}: addressed more than once", self.isp),
            Kind::MissingInMessage => write!(f, "ISP {}: missing in the message", self.isp),
            Kind::MissingInOurs => write!(f, "ISP {}: not in our settlement", self.isp),
        }
    }
}

/// The `BaselineReference` naming `method`: its id, such as `mbma@1`.
#[must_use]
pub fn baseline_reference(method: MethodId) -> String {
    method.as_str().to_owned()
}

/// The method a `BaselineReference` names, or `None` for a reference this crate does not know.
/// The reference is a method id and nothing else.
/// UFTP defines no syntax for it, so a suffix such as `xofy@1(x=4,y=5)` is not read as
/// `xofy@1`: its parameters would be a convention nobody defined.
///
/// ```
/// # use flexibility::{MethodId, uftp::method_of};
/// assert_eq!(method_of("xofy@1"), Some(MethodId::XofY1));
/// assert_eq!(method_of("xofy@1(x=4,y=5)"), None);
/// assert_eq!(method_of("GOPACS-baseline"), None);
/// ```
#[must_use]
pub fn method_of(reference: &str) -> Option<MethodId> {
    reference.parse().ok()
}

/// The whole day a message's header names: its Period, TimeZone and ISP-Duration.
///
/// # Errors
/// [`Error::IspDuration`] or [`Error::Day`] if the header's day cannot be a grid.
pub fn grid(header: &wire::FlexHeader) -> Result<Grid, Error> {
    let isp = IspDuration::from_minutes(header.isp_duration.minutes())?;
    Grid::day(header.period, header.time_zone.zone(), isp)
}

/// The ISP numbers `spans` cover, each with its element, bounded before expanding and refusing
/// an ISP outside `day` or named twice.
fn expand<T: Copy>(
    day: &Grid,
    elements: &[T],
    span: impl Fn(&T) -> wire::IspSpan,
) -> Result<BTreeMap<u32, T>, Error> {
    let total: u64 = elements.iter().map(|e| u64::from(span(e).duration())).sum();
    if total > u64::from(MAX_ISPS) {
        return Err(Error::GridSize { count: total });
    }
    let mut map = BTreeMap::new();
    for e in elements {
        let s = span(e);
        if day.index(s.start()).is_none() || day.index(s.end()).is_none() {
            return Err(Error::IspRange {
                first: s.start(),
                last: s.end(),
                count: day.count(),
            });
        }
        for isp in s.start()..=s.end() {
            if map.insert(isp, *e).is_some() {
                return Err(Error::Unrepresentable {
                    protocol: PROTOCOL,
                    field: "ISP",
                    value: isp.to_string(),
                    reason: "named by more than one element",
                });
            }
        }
    }
    Ok(map)
}

/// A FlexRequest as bounds on the deviation per ISP of its day, with each ISP's disposition. An
/// ISP the request does not name has no band; an ISP without `Disposition` is
/// [`Disposition::Unstated`]. The provenance is the sender's domain, the message id and its
/// timestamp.
///
/// # Errors
/// [`Error::IspRange`] for an ISP outside the day, [`Error::Unrepresentable`] for an ISP named
/// twice, [`Error::GridSize`] if the elements expand past [`MAX_ISPS`], [`Error::InvertedBand`]
/// for MinPower above MaxPower.
pub fn request(request: &wire::FlexRequest) -> Result<DeviationEnvelope, Error> {
    let header = &request.header;
    let day = grid(header)?;
    let named = expand(&day, &request.isps, |i| i.span)?;
    let bands = day
        .numbers()
        .map(|isp| {
            named
                .get(&isp)
                .map(|i| {
                    let disposition = match i.disposition {
                        Some(wire::AvailableRequested::Requested) => Disposition::Requested,
                        Some(wire::AvailableRequested::Available) => Disposition::Available,
                        None => Disposition::Unstated,
                    };
                    Band::new(
                        Deviation::from_watts(i.min_power),
                        Deviation::from_watts(i.max_power),
                        disposition,
                    )
                })
                .transpose()
        })
        .collect::<Result<Vec<_>, Error>>()?;
    Ok(DeviationEnvelope::new(
        Series::new(day, bands)?,
        provenance(&header.meta),
    ))
}

fn provenance(meta: &wire::Metadata) -> Provenance {
    Provenance::new(
        meta.sender_domain.as_str(),
        meta.message_id.to_string(),
        meta.timestamp,
    )
}

/// The ISP elements of a FlexOffer option or a FlexOrder as a deviation per ISP, from the
/// first to the last ISP they name; 0 W in an ISP between them that none names (nothing is
/// offered there).
///
/// # Errors
/// As [`request`]; [`Error::NoData`] for no elements.
pub fn profile(
    header: &wire::FlexHeader,
    isps: &[wire::PowerIsp],
) -> Result<Series<Deviation>, Error> {
    let day = grid(header)?;
    let named = expand(&day, isps, |i| i.span)?;
    let (Some((&first, _)), Some((&last, _))) = (named.first_key_value(), named.last_key_value())
    else {
        return Err(Error::NoData {
            what: "the message names no ISP",
        });
    };
    let values = (first..=last)
        .map(|isp| Deviation::from_watts(named.get(&isp).map_or(0, |i| i.power)))
        .collect();
    Series::new(day.slice(first..=last)?, values)
}

/// The ordered deviation per ISP: the order's ISP power × its ActivationFactor, in integers,
/// rounded once as `rounding` says. The ISP list is the offer's, copied unchanged
/// [UFTP 3.1 § 4.2.24], and OrderedFlexPower is *"as per the referenced FlexOrder"*
/// [§ 4.2.28]; the `uftp` crate checks settlements the same way.
///
/// # Errors
/// As [`profile`]; [`Error::Inexact`] for a fractional watt under [`Rounding::Exact`].
pub fn ordered(order: &wire::FlexOrder, rounding: Rounding) -> Result<Series<Deviation>, Error> {
    let factor = order.activation_factor.value();
    let scale = factor.scale();
    let hundredths = match scale {
        0..=2 => factor.mantissa() * 10_i128.pow(2 - scale),
        _ => {
            return Err(Error::Unrepresentable {
                protocol: PROTOCOL,
                field: "ActivationFactor",
                value: factor.to_string(),
                reason: "has more than two decimals",
            });
        }
    };
    profile(&order.header, &order.isps)?.try_map(|d| {
        let w = div_round(i128::from(d.watts()) * hundredths, 100, rounding)?;
        // |factor| ≤ 1, so the product fits where the power did.
        Ok(Deviation::from_watts(i64::try_from(w).unwrap_or(d.watts())))
    })
}

/// The settlement's lines as UFTP ISP elements, one per ISP, numbered per day.
///
/// # Errors
/// [`Error::IspRange`] if an ISP number is not a valid UFTP ISP (never for a grid this crate
/// built).
pub fn isps(settlement: &Settlement, sign: FlexSign) -> Result<Vec<wire::SettlementIsp>, Error> {
    settlement
        .lines()
        .iter()
        .map(|l| {
            let n = l.isp.isp();
            let span = wire::IspSpan::single(n).map_err(|_| Error::IspRange {
                first: n,
                last: n,
                count: MAX_ISPS,
            })?;
            let ordered = i128::from(l.ordered.watts());
            let (delivered, deficiency) = sign.write(
                i128::from(l.delivered.watts()),
                i128::from(l.deficiency.watts()),
                ordered,
            );
            Ok(wire::SettlementIsp {
                span,
                baseline_power: l.baseline.watts(),
                ordered_flex_power: l.ordered.watts(),
                actual_power: l.actual.watts(),
                delivered_flex_power: narrow(delivered),
                power_deficiency: narrow(deficiency),
            })
        })
        .collect()
}

fn mismatch(field: &'static str, ours: impl fmt::Display, theirs: impl fmt::Display) -> Error {
    Error::Mismatch {
        field,
        ours: ours.to_string(),
        theirs: theirs.to_string(),
    }
}

/// The FlexOrderSettlement item for `order`, from our settlement of it: the order's references
/// and its price × ActivationFactor ([`wire::FlexOrder::settlement`], spec note SS-26) and one
/// ISP element per settled ISP the order covers. `BaselineReference` names our method when the order names none and no D-Prognosis.
/// UFTP has no field for the [measurement point](crate::MeasurementPoint); it stays in our
/// receipt ([`Settlement::canonical`]).
///
/// # Errors
/// [`Error::Mismatch`] if the settlement is on another day, zone or ISP length, is not numbered
/// as the order's day, or the order names another baseline method (in `BaselineReference`, or a
/// D-Prognosis for a method other than `dprognosis@1`).
pub fn settlement(
    order: &wire::FlexOrder,
    ours: &Settlement,
    sign: FlexSign,
) -> Result<wire::FlexOrderSettlement, Error> {
    let header = &order.header;
    let on = ours.grid();
    if on.date() != header.period {
        return Err(mismatch("Period", on.date(), header.period));
    }
    let zone = on.zone().iana_name().unwrap_or("unnamed");
    if zone != header.time_zone.as_str() {
        return Err(mismatch("TimeZone", zone, header.time_zone.as_str()));
    }
    if on.isp().minutes() != header.isp_duration.minutes() {
        return Err(mismatch(
            "ISP-Duration",
            on.isp().minutes(),
            header.isp_duration.minutes(),
        ));
    }
    let day = grid(header)?;
    if day.slice(on.numbers()).ok().as_ref() != Some(on) {
        return Err(mismatch("ISP numbers", on, day));
    }
    let method = ours.method();
    let reference = match (&order.baseline_reference, &order.d_prognosis_message_id) {
        (Some(r), _) if method_of(r) == Some(method) => None,
        (Some(r), _) => return Err(mismatch("BaselineReference", method, r)),
        (None, Some(_)) if method == MethodId::DPrognosis1 => None,
        (None, Some(id)) => return Err(mismatch("D-PrognosisMessageID", method, id)),
        (None, None) => Some(baseline_reference(method)),
    };
    let covered = |isp: u32| {
        order
            .isps
            .iter()
            .any(|i| i.span.start() <= isp && isp <= i.span.end())
    };
    let elements = isps(ours, sign)?
        .into_iter()
        .filter(|e| covered(e.span.start()))
        .collect();
    let mut item = order.settlement(elements);
    if reference.is_some() {
        item.baseline_reference = reference;
    }
    Ok(item)
}

/// Every ISP of `received`, expanded from its elements, with duplicates reported.
fn expand_settlement(
    received: &wire::FlexOrderSettlement,
) -> Result<(BTreeMap<u32, wire::SettlementIsp>, Vec<Discrepancy>), Error> {
    let total: u64 = received
        .isps
        .iter()
        .map(|e| u64::from(e.span.duration()))
        .sum();
    if total > u64::from(MAX_ISPS) {
        return Err(Error::GridSize { count: total });
    }
    let mut map = BTreeMap::new();
    let mut found = Vec::new();
    for e in &received.isps {
        for isp in e.span.start()..=e.span.end() {
            if map.insert(isp, *e).is_some() {
                found.push(Discrepancy {
                    isp,
                    kind: Kind::Duplicate,
                });
            }
        }
    }
    Ok((map, found))
}

fn field(isp: u32, field: &'static str, sent: i64, expected: i64) -> Option<Discrepancy> {
    (sent != expected).then_some(Discrepancy {
        isp,
        kind: Kind::Field {
            field,
            sent,
            expected,
        },
    })
}

/// The rule's delivered and deficiency for one ISP element, as the wire carries them.
fn expected(e: &wire::SettlementIsp, sign: FlexSign) -> (i128, i128) {
    let deviation = i128::from(e.actual_power) - i128::from(e.baseline_power);
    let ordered = i128::from(e.ordered_flex_power);
    let (delivered, deficiency) = settle_isp(deviation, ordered);
    sign.write(delivered, deficiency, ordered)
}

fn narrow(w: i128) -> i64 {
    // The inputs are i64, so the rule's outputs are within ±2^64; saturate the one edge.
    i64::try_from(w).unwrap_or(if w < 0 { i64::MIN } else { i64::MAX })
}

/// Checks `received` on its own: for every ISP, `DeliveredFlexPower` and `PowerDeficiency` must
/// be what the settlement rule gives from the message's `BaselinePower`, `OrderedFlexPower` and
/// `ActualPower`. Returns every discrepancy, in ISP order; empty if the message is right.
///
/// # Errors
/// [`Error::GridSize`] if the elements expand to more than [`MAX_ISPS`] ISPs.
pub fn check(
    received: &wire::FlexOrderSettlement,
    sign: FlexSign,
) -> Result<Vec<Discrepancy>, Error> {
    let (isps, mut found) = expand_settlement(received)?;
    for (&isp, e) in &isps {
        let (delivered, deficiency) = expected(e, sign);
        found.extend(field(
            isp,
            "DeliveredFlexPower",
            e.delivered_flex_power,
            narrow(delivered),
        ));
        found.extend(field(
            isp,
            "PowerDeficiency",
            e.power_deficiency,
            narrow(deficiency),
        ));
    }
    found.sort_by_key(|d| d.isp);
    Ok(found)
}

/// Compares `received` with `ours`, ISP by ISP: every field that differs, and ISPs on one side
/// only. Returns every discrepancy, in ISP order; empty if they agree.
///
/// # Errors
/// [`Error::GridSize`] if the elements expand to more than [`MAX_ISPS`] ISPs.
pub fn compare(
    received: &wire::FlexOrderSettlement,
    ours: &Settlement,
    sign: FlexSign,
) -> Result<Vec<Discrepancy>, Error> {
    let (theirs, mut found) = expand_settlement(received)?;
    let mine: BTreeMap<u32, wire::SettlementIsp> = isps(ours, sign)?
        .into_iter()
        .map(|e| (e.span.start(), e))
        .collect();
    for (&isp, m) in &mine {
        let Some(t) = theirs.get(&isp) else {
            found.push(Discrepancy {
                isp,
                kind: Kind::MissingInMessage,
            });
            continue;
        };
        found.extend(
            [
                field(isp, "BaselinePower", t.baseline_power, m.baseline_power),
                field(
                    isp,
                    "OrderedFlexPower",
                    t.ordered_flex_power,
                    m.ordered_flex_power,
                ),
                field(isp, "ActualPower", t.actual_power, m.actual_power),
                field(
                    isp,
                    "DeliveredFlexPower",
                    t.delivered_flex_power,
                    m.delivered_flex_power,
                ),
                field(
                    isp,
                    "PowerDeficiency",
                    t.power_deficiency,
                    m.power_deficiency,
                ),
            ]
            .into_iter()
            .flatten(),
        );
    }
    found.extend(
        theirs
            .keys()
            .filter(|isp| !mine.contains_key(isp))
            .map(|&isp| Discrepancy {
                isp,
                kind: Kind::MissingInOurs,
            }),
    );
    found.sort_by_key(|d| d.isp);
    Ok(found)
}