flexibility 0.3.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
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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
//! Settlement: ordered against delivered, per ISP, as UFTP 3.1 § 2.6 computes it.
//!
//! Per ISP, consumption positive, with baseline *b*, actual *a* and ordered deviation *o*:
//!
//! | Quantity | Rule |
//! |---|---|
//! | deviation | *d* = *a* − *b* |
//! | along the order | *r* = *d* · sign(*o*) |
//! | delivered | clamp(*r*, 0, \|*o*\|) · sign(*o*): never more than ordered (*"Passive contributions … are not rewarded"*) |
//! | deficiency | max(0, \|*o*\| − *r*): over-delivery is never penalised (*"negative deviations are set to 0"*); a site that moves the wrong way owes more than it was ordered |
//!
//! UFTP's own example, 2 MW ordered down from a 10 MW baseline:
//!
//! ```
//! use flexibility::jiff::{Timestamp, tz::TimeZone};
//! use flexibility::baseline;
//! use flexibility::*;
//! let grid = Grid::new(Timestamp::UNIX_EPOCH, IspDuration::FIFTEEN_MINUTES, 5, TimeZone::UTC)?;
//! let window = Window::new(grid.start(), grid.end())?;
//! let who = Provenance::new("agr.example", "d-prognosis", Timestamp::UNIX_EPOCH);
//! let base = baseline::dprognosis(&Schedule::new(Series::filled(grid.clone(), mw!(10)), who), window)?;
//! let actual = Series::new(grid.clone(), vec![mw!(7), mw!(8), mw!(9), mw!(10), mw!(11)])?;
//! let ordered = Series::filled(grid, Deviation::from_watts(-2_000_000));
//!
//! let s = settle(&base, &actual, &ordered, MeasurementPoint::ConnectionPoint)?;
//! let delivered: Vec<i64> = s.lines().iter().map(|l| l.delivered.watts() / 1_000_000).collect();
//! let deficiency: Vec<i64> = s.lines().iter().map(|l| l.deficiency.watts() / 1_000_000).collect();
//! assert_eq!(delivered, [-2, -2, -1, 0, 0]);
//! assert_eq!(deficiency, [0, 0, 1, 2, 3]);
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

use std::fmt;

use crate::baseline::{self, Baseline, MethodId};
use crate::canon::{self, Digest, Json, Value};
use jiff::Timestamp;
use jiff::tz::TimeZone;

use crate::{Deviation, Energy, Error, Grid, IspDuration, IspLabel, Power, Series};

/// One settled ISP.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Line {
    /// The ISP.
    pub isp: IspLabel,
    /// The baseline.
    pub baseline: Power,
    /// The measured power.
    pub actual: Power,
    /// The ordered deviation (Σ of the orders on this ISP).
    pub ordered: Deviation,
    /// `actual − baseline`.
    pub deviation: Deviation,
    /// The flexibility delivered, in the order's direction, never more than ordered.
    pub delivered: Deviation,
    /// The ordered flexibility not delivered; never negative.
    pub deficiency: Power,
}

impl fmt::Display for Line {
    /// `ISP 69 (17:00–17:15 +01:00): baseline 7 kW, actual 4.1 kW, ordered -3 kW, delivered -2.9 kW, deficiency 100 W`.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}: baseline {}, actual {}, ordered {}, delivered {}, deficiency {}",
            self.isp, self.baseline, self.actual, self.ordered, self.delivered, self.deficiency
        )
    }
}

/// Where the actual power was measured: the connection point's meter (the NC DR default,
/// Art 12) or a named dedicated measurement device (Art 13). Recorded in every settlement and
/// its receipt, so a sub-meter series cannot pass as the fiscal meter's.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum MeasurementPoint {
    /// The meter at the connection point.
    ConnectionPoint,
    /// A dedicated measurement device, by its id in the contract or asset register.
    Device(DeviceId),
}

impl MeasurementPoint {
    /// A dedicated measurement device named `id`.
    ///
    /// # Errors
    /// [`Error::DeviceId`] unless `id` is 1–64 characters without control characters.
    pub fn device(id: &str) -> Result<MeasurementPoint, Error> {
        DeviceId::new(id).map(MeasurementPoint::Device)
    }

    pub(crate) fn canonical_value(&self) -> Value {
        match self {
            MeasurementPoint::ConnectionPoint => Value::str("connection-point"),
            MeasurementPoint::Device(id) => Value::obj([("device", Value::str(id.as_str()))]),
        }
    }
}

impl fmt::Display for MeasurementPoint {
    /// `connection point` or `device hp-1`.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            MeasurementPoint::ConnectionPoint => f.write_str("connection point"),
            MeasurementPoint::Device(id) => write!(f, "device {}", id.as_str()),
        }
    }
}

/// The id of a dedicated measurement device: 1–64 characters, no control characters.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct DeviceId(String);

impl DeviceId {
    /// `id`, checked.
    ///
    /// # Errors
    /// [`Error::DeviceId`] unless `id` is 1–64 characters without control characters.
    pub fn new(id: &str) -> Result<DeviceId, Error> {
        let reason = match id.chars().count() {
            0 => Some("is empty"),
            n if n > 64 => Some("is longer than 64 characters"),
            _ if id.chars().any(char::is_control) => Some("contains a control character"),
            _ => None,
        };
        match reason {
            Some(reason) => Err(Error::DeviceId {
                id: canon::quote(id),
                reason,
            }),
            None => Ok(DeviceId(id.to_owned())),
        }
    }

    /// The id as given.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

/// A settlement: every line, the totals, and what it was computed from.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Settlement {
    method: MethodId,
    measured_at: MeasurementPoint,
    baseline: Digest,
    inputs: Vec<(&'static str, Digest)>,
    lines: Vec<Line>,
    delivered: Energy,
    deficiency: Energy,
    grid: Grid,
    canonical_grid: Value,
}

/// The first thing two settlements disagree on.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Difference {
    /// Different methods.
    Method {
        /// Ours.
        ours: MethodId,
        /// Theirs.
        theirs: MethodId,
    },
    /// Measured at different points.
    MeasurementPoint {
        /// Ours.
        ours: MeasurementPoint,
        /// Theirs.
        theirs: MeasurementPoint,
    },
    /// Different ISPs: the lines cannot be paired.
    Grid,
    /// An input with a different digest.
    Input {
        /// The input's name: `baseline`, `actual` or `ordered`.
        name: &'static str,
        /// Our digest.
        ours: Digest,
        /// Theirs.
        theirs: Digest,
    },
    /// A line with a different value.
    Line {
        /// The ISP.
        isp: IspLabel,
        /// The field: `baseline`, `actual`, `ordered`, `delivered` or `deficiency`.
        field: &'static str,
        /// Our watts.
        ours: i64,
        /// Their watts.
        theirs: i64,
    },
}

impl fmt::Display for Difference {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Difference::Method { ours, theirs } => {
                write!(f, "method: ours {ours}, theirs {theirs}")
            }
            Difference::MeasurementPoint { ours, theirs } => {
                write!(f, "measured at: ours {ours}, theirs {theirs}")
            }
            Difference::Grid => f.write_str("the settlements cover different ISPs"),
            Difference::Input { name, ours, theirs } => {
                write!(f, "input `{name}` differs: ours {ours}, theirs {theirs}")
            }
            Difference::Line {
                isp,
                field,
                ours,
                theirs,
            } => write!(
                f,
                "{isp}: {field} ours {}, theirs {}",
                Power::from_watts(*ours),
                Power::from_watts(*theirs)
            ),
        }
    }
}

/// Settles `actual` against `baseline` for `ordered`, ISP by ISP. All three are on the event's
/// ISPs; [`Series::over`] cuts a day's measurement to them.
///
/// # Errors
/// [`Error::GridMismatch`] if the series are on different grids; [`Error::Overflow`] at the
/// edges of the range.
pub fn settle(
    baseline: &Baseline,
    actual: &Series<Power>,
    ordered: &Series<Deviation>,
    measured_at: MeasurementPoint,
) -> Result<Settlement, Error> {
    let grid = baseline.series().grid();
    actual.same_grid(grid)?;
    ordered.same_grid(grid)?;
    let rows = baseline
        .series()
        .values()
        .iter()
        .zip(actual.values())
        .zip(ordered.values())
        .map(|((&b, &a), &o)| (b, a, o));
    build(
        baseline.method(),
        measured_at,
        baseline.digest(),
        vec![
            ("actual", canon::power_input(actual)?),
            ("ordered", canon::deviation_input(ordered)?),
        ],
        grid,
        rows,
    )
}

/// A settlement from its method, baseline digest, input digests, grid and the (baseline,
/// actual, ordered) of each ISP: every derived value computed here, by [`settle`] and when a
/// received text is read back.
fn build(
    method: MethodId,
    measured_at: MeasurementPoint,
    baseline: Digest,
    inputs: Vec<(&'static str, Digest)>,
    grid: &Grid,
    rows: impl Iterator<Item = (Power, Power, Deviation)>,
) -> Result<Settlement, Error> {
    let seconds = i128::from(grid.isp().minutes()) * 60;
    let mut lines = Vec::with_capacity(grid.count() as usize);
    let (mut delivered_ws, mut deficiency_ws) = (0i128, 0i128);
    for (isp, (b, a, o)) in grid.numbers().zip(rows) {
        let deviation = a.deviation_from(b)?;
        let (delivered, deficiency) =
            settle_isp(i128::from(deviation.watts()), i128::from(o.watts()));
        delivered_ws += delivered * seconds;
        deficiency_ws += deficiency * seconds;
        lines.push(Line {
            isp: grid.label_total(isp),
            baseline: b,
            actual: a,
            ordered: o,
            deviation,
            delivered: Deviation::from_watts(to_i64(delivered)?),
            deficiency: Power::from_watts(to_i64(deficiency)?),
        });
    }
    let settlement = Settlement {
        method,
        measured_at,
        baseline,
        inputs,
        lines,
        delivered: Energy::from_sum(delivered_ws)?,
        deficiency: Energy::from_sum(deficiency_ws)?,
        grid: grid.clone(),
        canonical_grid: canon::grid(grid),
    };
    settlement.value().exact()?;
    Ok(settlement)
}

/// (delivered, deficiency) in watts for one ISP, in i128 so nothing can overflow. The one home
/// of the rule: [`settle`] and the UFTP check both call it.
pub(crate) fn settle_isp(deviation: i128, ordered: i128) -> (i128, i128) {
    let o = ordered;
    let u = o.signum();
    let r = deviation * u;
    let amount = o.abs();
    let delivered = r.clamp(0, amount) * u;
    let deficiency = (amount - r).max(0);
    (delivered, deficiency)
}

fn to_i64(w: i128) -> Result<i64, Error> {
    i64::try_from(w).map_err(|_| Error::Overflow {
        quantity: "power",
        operation: "settle",
        left: w,
        right: None,
    })
}

fn watts(v: &Json, path: &str) -> Result<i64, Error> {
    i64::try_from(v.int(path)?).map_err(|_| canon::refuse(path, "outside the range of watts"))
}

fn digest_at(inputs: &Json, name: &str) -> Result<Digest, Error> {
    let path = canon::join("inputs", name);
    inputs
        .get("inputs", name)?
        .str(&path)?
        .parse()
        .map_err(|_| canon::refuse(&path, "not a digest"))
}

/// The profile of a settlement's canonical text.
const SETTLEMENT_PROFILE: &str = "flexibility.settlement@1";

fn read_header(root: &Json) -> Result<MethodId, Error> {
    let profile = root.get("", "profile")?.str("profile")?;
    if profile != SETTLEMENT_PROFILE {
        return Err(canon::refuse(
            "profile",
            format!("{} is not {SETTLEMENT_PROFILE}", canon::quote(profile)),
        ));
    }
    let id = root.get("", "method")?.str("method")?;
    id.parse().map_err(|_| {
        canon::refuse(
            "method",
            format!("{} is not a known method id", canon::quote(id)),
        )
    })
}

fn read_point(v: &Json) -> Result<MeasurementPoint, Error> {
    match v {
        Json::Str(s) if s == "connection-point" => Ok(MeasurementPoint::ConnectionPoint),
        Json::Obj(_) => {
            let id = v.get("measured_at", "device")?.str("measured_at.device")?;
            MeasurementPoint::device(id)
                .map_err(|e| canon::refuse("measured_at.device", e.to_string()))
        }
        _ => Err(canon::refuse(
            "measured_at",
            "neither \"connection-point\" nor {\"device\":…}",
        )),
    }
}

fn read_grid(g: &Json, zone: TimeZone) -> Result<Grid, Error> {
    let number = |name: &str| {
        let path = canon::join("grid", name);
        u32::try_from(g.get("grid", name)?.int(&path)?)
            .map_err(|_| canon::refuse(&path, "out of range"))
    };
    let (count, first) = (number("count")?, number("first")?);
    let isp_text = g.get("grid", "isp")?.str("grid.isp")?;
    let isp = IspDuration::from_canonical(isp_text).ok_or_else(|| {
        canon::refuse(
            "grid.isp",
            format!("{} is not an ISP length", canon::quote(isp_text)),
        )
    })?;
    let start_text = g.get("grid", "start")?.str("grid.start")?;
    let start: Timestamp = start_text.parse().map_err(|_| {
        canon::refuse(
            "grid.start",
            format!("{} is not an instant", canon::quote(start_text)),
        )
    })?;
    Grid::numbered(start, isp, count, first, zone).map_err(|e| canon::refuse("grid", e.to_string()))
}

fn read_rows(lines: &[Json], grid: &Grid) -> Result<Vec<(Power, Power, Deviation)>, Error> {
    if lines.len() != grid.count() as usize {
        return Err(canon::refuse(
            "lines",
            format!("{} lines for a grid of {} ISPs", lines.len(), grid.count()),
        ));
    }
    lines
        .iter()
        .enumerate()
        .zip(grid.numbers())
        .map(|((k, line), isp)| {
            let path = format!("lines[{k}]");
            let field = |name: &str| watts(line.get(&path, name)?, &canon::join(&path, name));
            if field("isp")? != i64::from(isp) {
                return Err(canon::refuse(
                    &canon::join(&path, "isp"),
                    format!("expected ISP {isp}"),
                ));
            }
            Ok((
                Power::from_watts(field("baseline")?),
                Power::from_watts(field("actual")?),
                Deviation::from_watts(field("ordered")?),
            ))
        })
        .collect()
}

/// The first derived value in the received text that the rule does not give.
fn explain_mismatch(lines: &[Json], totals: &Json, read: &Settlement) -> Result<(), Error> {
    for ((k, line), ours) in lines.iter().enumerate().zip(&read.lines) {
        let path = format!("lines[{k}]");
        for (name, expected) in [
            ("deviation", ours.deviation.watts()),
            ("delivered", ours.delivered.watts()),
            ("deficiency", ours.deficiency.watts()),
        ] {
            let sent = watts(line.get(&path, name)?, &canon::join(&path, name))?;
            if sent != expected {
                return Err(canon::refuse(
                    &canon::join(&path, name),
                    format!("sent {sent}, the rule gives {expected}"),
                ));
            }
        }
    }
    for (name, expected) in [
        ("delivered_ws", read.delivered.watt_seconds()),
        ("deficiency_ws", read.deficiency.watt_seconds()),
    ] {
        let path = canon::join("totals", name);
        let sent = totals.get("totals", name)?.int(&path)?;
        if sent != i128::from(expected) {
            return Err(canon::refuse(
                &path,
                format!("sent {sent}, the lines give {expected}"),
            ));
        }
    }
    Ok(())
}

impl Settlement {
    /// Reads a settlement back from its `canon@1` text, as [`canonical`](Settlement::canonical)
    /// writes it and the other party sends it, with `zone` for its labels (the zone is not in
    /// the text). Then [`diff`](Settlement::diff) names the first thing it and ours disagree on.
    ///
    /// Untrusted input is fine: the text must be **exactly** canonical (byte for byte the text
    /// this crate writes for the settlement it describes, so its digest is the digest of the
    /// bytes received), and every line and total must follow the settlement rule from the
    /// line's baseline, actual and ordered values. Anything else is refused, naming where.
    ///
    /// ```
    /// # use flexibility::baseline;
    /// # use flexibility::jiff::{Timestamp, tz::TimeZone};
    /// # use flexibility::*;
    /// # let grid = Grid::new(Timestamp::UNIX_EPOCH, IspDuration::FIFTEEN_MINUTES, 2, TimeZone::UTC)?;
    /// # let who = Provenance::new("agr.example", "d-prognosis", grid.start());
    /// # let base = baseline::dprognosis(&Schedule::new(Series::filled(grid.clone(), kw!(10)), who), Window::new(grid.start(), grid.end())?)?;
    /// # let ours = settle(&base, &Series::filled(grid.clone(), kw!(7)), &Series::filled(grid, Deviation::from_watts(-2_000)), MeasurementPoint::ConnectionPoint)?;
    /// let text = ours.canonical(); // as the other party sends it
    /// let theirs = Settlement::from_canonical(&text, TimeZone::UTC)?;
    /// assert_eq!(theirs.digest(), Digest::of(text.as_bytes()));
    /// assert_eq!(ours.diff(&theirs), None);
    ///
    /// let edited = text.replace("\"deficiency\":0", "\"deficiency\":1");
    /// let err = Settlement::from_canonical(&edited, TimeZone::UTC).unwrap_err();
    /// assert_eq!(err.to_string(), "receipt at `lines[0].deficiency`: sent 1, the rule gives 0");
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// # Errors
    /// [`Error::Receipt`] naming the path and the reason: not canonical, another version or
    /// kind, an unknown method, a malformed grid, digest or ISP number, a line or total that
    /// breaks the rule, or a text over [`MAX_RECEIPT_BYTES`](crate::MAX_RECEIPT_BYTES).
    pub fn from_canonical(text: &str, zone: TimeZone) -> Result<Settlement, Error> {
        let root = canon::read(text)?;
        let method = read_header(&root)?;
        let grid = read_grid(root.get("", "grid")?, zone)?;
        let inputs = root.get("", "inputs")?;
        let lines = root.get("", "lines")?.arr("lines")?;
        let read = build(
            method,
            read_point(root.get("", "measured_at")?)?,
            digest_at(inputs, "baseline")?,
            vec![
                ("actual", digest_at(inputs, "actual")?),
                ("ordered", digest_at(inputs, "ordered")?),
            ],
            &grid,
            read_rows(lines, &grid)?.into_iter(),
        )
        .map_err(|e| canon::refuse("lines", e.to_string()))?;
        explain_mismatch(lines, root.get("", "totals")?, &read)?;
        if read.canonical() != text {
            return Err(canon::refuse(
                "",
                "not in canonical form: the bytes differ from the canonical text of the \
                 settlement they describe (whitespace, key order, an escape or an extra field)",
            ));
        }
        Ok(read)
    }

    /// Where the actual power was measured.
    #[must_use]
    pub fn measured_at(&self) -> &MeasurementPoint {
        &self.measured_at
    }

    /// The grid the settlement is on: the event's ISPs, numbered as their day numbers them.
    #[must_use]
    pub fn grid(&self) -> &Grid {
        &self.grid
    }

    /// The baseline method.
    #[must_use]
    pub fn method(&self) -> MethodId {
        self.method
    }

    /// Every ISP, in order.
    #[must_use]
    pub fn lines(&self) -> &[Line] {
        &self.lines
    }

    /// Total delivered energy, signed in the orders' directions.
    #[must_use]
    pub fn delivered(&self) -> Energy {
        self.delivered
    }

    /// Total energy ordered but not delivered.
    #[must_use]
    pub fn deficiency(&self) -> Energy {
        self.deficiency
    }

    /// The digest of the baseline settled against.
    #[must_use]
    pub fn baseline(&self) -> Digest {
        self.baseline
    }

    /// The digest of each other input: `actual` and `ordered`.
    #[must_use]
    pub fn inputs(&self) -> &[(&'static str, Digest)] {
        &self.inputs
    }

    /// The `canon@1` text: what both parties hash.
    #[must_use]
    pub fn canonical(&self) -> String {
        self.value().text()
    }

    /// The SHA-256 of [`canonical`](Settlement::canonical).
    #[must_use]
    pub fn digest(&self) -> Digest {
        self.value().digest()
    }

    /// The first thing `theirs` disagrees on: the method, then the ISPs, then the first
    /// differing line (so a changed meter value names its ISP), then an input digest (an
    /// input that differs only outside the event, such as an MBMA day). `None` if they are the same settlement.
    #[must_use]
    pub fn diff(&self, theirs: &Settlement) -> Option<Difference> {
        if self.method != theirs.method {
            return Some(Difference::Method {
                ours: self.method,
                theirs: theirs.method,
            });
        }
        if self.measured_at != theirs.measured_at {
            return Some(Difference::MeasurementPoint {
                ours: self.measured_at.clone(),
                theirs: theirs.measured_at.clone(),
            });
        }
        if self.canonical_grid != theirs.canonical_grid || self.lines.len() != theirs.lines.len() {
            return Some(Difference::Grid);
        }
        for (a, b) in self.lines.iter().zip(&theirs.lines) {
            let fields = [
                ("baseline", a.baseline.watts(), b.baseline.watts()),
                ("actual", a.actual.watts(), b.actual.watts()),
                ("ordered", a.ordered.watts(), b.ordered.watts()),
                ("delivered", a.delivered.watts(), b.delivered.watts()),
                ("deficiency", a.deficiency.watts(), b.deficiency.watts()),
            ];
            if let Some((field, ours, theirs)) = fields.into_iter().find(|(_, x, y)| x != y) {
                return Some(Difference::Line {
                    isp: a.isp,
                    field,
                    ours,
                    theirs,
                });
            }
        }
        let ours = std::iter::once(("baseline", self.baseline)).chain(self.inputs.iter().copied());
        let other =
            std::iter::once(("baseline", theirs.baseline)).chain(theirs.inputs.iter().copied());
        for ((name, a), (_, b)) in ours.zip(other) {
            if a != b {
                return Some(Difference::Input {
                    name,
                    ours: a,
                    theirs: b,
                });
            }
        }
        None
    }

    fn value(&self) -> Value {
        let mut inputs = self.inputs.clone();
        inputs.push(("baseline", self.baseline));
        let lines = self
            .lines
            .iter()
            .map(|l| {
                Value::obj([
                    ("actual", Value::int(l.actual.watts())),
                    ("baseline", Value::int(l.baseline.watts())),
                    ("deficiency", Value::int(l.deficiency.watts())),
                    ("delivered", Value::int(l.delivered.watts())),
                    ("deviation", Value::int(l.deviation.watts())),
                    ("isp", Value::int(l.isp.isp())),
                    ("ordered", Value::int(l.ordered.watts())),
                ])
            })
            .collect();
        Value::obj([
            ("grid", self.canonical_grid.clone()),
            ("inputs", baseline::inputs(&inputs)),
            ("lines", Value::Arr(lines)),
            ("measured_at", self.measured_at.canonical_value()),
            ("method", Value::str(self.method)),
            ("profile", Value::str(SETTLEMENT_PROFILE)),
            (
                "totals",
                Value::obj([
                    ("deficiency_ws", Value::int(self.deficiency.watt_seconds())),
                    ("delivered_ws", Value::int(self.delivered.watt_seconds())),
                ]),
            ),
        ])
    }
}

impl fmt::Display for Settlement {
    /// One line per ISP, then the totals and the digest.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for line in &self.lines {
            writeln!(f, "{line}")?;
        }
        write!(
            f,
            "{}: delivered {}, deficiency {}, digest {}",
            self.method,
            self.delivered,
            self.deficiency,
            self.digest()
        )
    }
}