flexibility 0.1.1

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
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
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
//! Limits, envelopes, guarantees and schedules, who set them, and why a bound is what it is.

use std::fmt;
use std::ops::RangeInclusive;

use jiff::Timestamp;

use crate::error::Breach;
use crate::{Deviation, Error, Grid, IspLabel, Power, Series, Window};

/// Who set a limit, guarantee, envelope or schedule, under which reference, and when.
///
/// The values are opaque: this crate authenticates nobody. Who may issue a limit is the
/// integrator's decision.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Provenance {
    issuer: String,
    reference: String,
    issued_at: Timestamp,
}

impl Provenance {
    /// `issuer` set it under `reference` (an order, rule or contract id) at `issued_at`.
    #[must_use]
    pub fn new(
        issuer: impl Into<String>,
        reference: impl Into<String>,
        issued_at: Timestamp,
    ) -> Provenance {
        Provenance {
            issuer: issuer.into(),
            reference: reference.into(),
            issued_at,
        }
    }

    /// The issuing party.
    #[must_use]
    pub fn issuer(&self) -> &str {
        &self.issuer
    }

    /// The order, rule or contract it was issued under.
    #[must_use]
    pub fn reference(&self) -> &str {
        &self.reference
    }

    /// When it was issued.
    #[must_use]
    pub fn issued_at(&self) -> Timestamp {
        self.issued_at
    }
}

impl fmt::Display for Provenance {
    /// `dso.example order-42`.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} {}", self.issuer, self.reference)
    }
}

/// The allowed power range: an optional minimum and maximum, the minimum never above the
/// maximum. With consumption positive, a consumption cap is a maximum and a feed-in cap a
/// (negative) minimum.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct Bounds {
    min: Option<Power>,
    max: Option<Power>,
}

impl Bounds {
    /// No constraint.
    pub const UNBOUNDED: Bounds = Bounds {
        min: None,
        max: None,
    };

    /// Power between `min` and `max`, both inclusive and both optional.
    ///
    /// # Errors
    /// [`Error::InvertedBounds`] if `min` is above `max`.
    pub fn new(min: Option<Power>, max: Option<Power>) -> Result<Bounds, Error> {
        if let (Some(min), Some(max)) = (min, max)
            && min > max
        {
            return Err(Error::InvertedBounds { min, max });
        }
        Ok(Bounds { min, max })
    }

    /// Power at most `max`.
    #[must_use]
    pub const fn at_most(max: Power) -> Bounds {
        Bounds {
            min: None,
            max: Some(max),
        }
    }

    /// Power at least `min`.
    #[must_use]
    pub const fn at_least(min: Power) -> Bounds {
        Bounds {
            min: Some(min),
            max: None,
        }
    }

    /// The minimum, if any.
    #[must_use]
    pub const fn min(self) -> Option<Power> {
        self.min
    }

    /// The maximum, if any.
    #[must_use]
    pub const fn max(self) -> Option<Power> {
        self.max
    }

    /// Whether `power` lies within the bounds.
    #[must_use]
    pub fn contains(self, power: Power) -> bool {
        self.min.is_none_or(|m| power >= m) && self.max.is_none_or(|m| power <= m)
    }
}

impl fmt::Display for Bounds {
    /// `max 4.2 kW`, `min -3 kW`, `-3 kW to 4.2 kW` or `unbounded`.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match (self.min, self.max) {
            (None, None) => f.write_str("unbounded"),
            (None, Some(max)) => write!(f, "max {max}"),
            (Some(min), None) => write!(f, "min {min}"),
            (Some(min), Some(max)) => write!(f, "{min} to {max}"),
        }
    }
}

/// Bounds over a window, with provenance.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Limit {
    window: Window,
    bounds: Bounds,
    provenance: Provenance,
}

impl Limit {
    /// `bounds` over `window`.
    #[must_use]
    pub fn new(window: Window, bounds: Bounds, provenance: Provenance) -> Limit {
        Limit {
            window,
            bounds,
            provenance,
        }
    }

    /// Consumption of at most `max` over `window`. A negative `max` demands feed-in.
    #[must_use]
    pub fn consumption_cap(window: Window, max: Power, provenance: Provenance) -> Limit {
        Limit::new(window, Bounds::at_most(max), provenance)
    }

    /// Feed-in of at most `amount` over `window`: a minimum of `-amount`.
    ///
    /// # Errors
    /// [`Error::NegativeAmount`] if `amount` is negative.
    pub fn feed_in_cap(
        window: Window,
        amount: Power,
        provenance: Provenance,
    ) -> Result<Limit, Error> {
        let min = negated_amount(amount)?;
        Ok(Limit::new(window, Bounds::at_least(min), provenance))
    }

    /// Consumption of at least `min` over `window`: a must-run load (a heat pump kept running, a
    /// § 13k EnWG "use instead of curtail" order). A negative `min` allows feed-in down to it.
    #[must_use]
    pub fn consumption_floor(window: Window, min: Power, provenance: Provenance) -> Limit {
        Limit::new(window, Bounds::at_least(min), provenance)
    }

    /// Feed-in of at least `amount` over `window`: a maximum of `-amount` (a generator that must
    /// keep producing, a battery that must discharge).
    ///
    /// # Errors
    /// [`Error::NegativeAmount`] if `amount` is negative.
    pub fn feed_in_floor(
        window: Window,
        amount: Power,
        provenance: Provenance,
    ) -> Result<Limit, Error> {
        let max = negated_amount(amount)?;
        Ok(Limit::new(window, Bounds::at_most(max), provenance))
    }

    /// Power between `min` and `max` over `window`, both inclusive: a device's own range, or a
    /// corridor the operator keeps a site in.
    ///
    /// ```
    /// # use flexibility::{Limit, Provenance, Window, kw};
    /// # use flexibility::jiff::Timestamp;
    /// # let w = Window::new(Timestamp::UNIX_EPOCH, "1970-01-01T01:00:00Z".parse()?)?;
    /// let pv = Limit::band(w, kw!(-10), kw!(0), Provenance::new("site.example", "pv-10kWp", w.from()))?;
    /// assert_eq!(pv.bounds().to_string(), "-10 kW to 0 W");
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// # Errors
    /// [`Error::InvertedBounds`] if `min` is above `max`.
    pub fn band(
        window: Window,
        min: Power,
        max: Power,
        provenance: Provenance,
    ) -> Result<Limit, Error> {
        Ok(Limit::new(
            window,
            Bounds::new(Some(min), Some(max))?,
            provenance,
        ))
    }

    /// The window.
    #[must_use]
    pub fn window(&self) -> Window {
        self.window
    }

    /// The bounds.
    #[must_use]
    pub fn bounds(&self) -> Bounds {
        self.bounds
    }

    /// Who set it.
    #[must_use]
    pub fn provenance(&self) -> &Provenance {
        &self.provenance
    }

    /// The ISPs of `grid` this limit constrains: every ISP its window overlaps, even partly.
    /// `None` if it constrains none of them.
    #[must_use]
    pub fn isps(&self, grid: &Grid) -> Option<RangeInclusive<u32>> {
        grid.isps(self.window)
    }
}

fn negated_amount(amount: Power) -> Result<Power, Error> {
    if amount < Power::ZERO {
        return Err(Error::NegativeAmount { power: amount });
    }
    // A non-negative i64 always negates.
    amount.checked_neg()
}

/// Power an envelope must keep allowing over a window: what a limit may not take away.
///
/// Under § 14a EnWG a grid operator may reduce a controllable consumer only down to a minimum
/// power; registered as a guarantee, any cap below it is refused instead of applied. A
/// guarantee adds no bound of its own.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Guarantee {
    window: Window,
    kind: Kind,
    provenance: Provenance,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum Kind {
    /// Every maximum must be at least this (non-negative) power.
    Consumption(Power),
    /// Every minimum must be at most this (non-positive) power.
    FeedIn(Power),
}

impl fmt::Display for Guarantee {
    /// `consumption of 8.001 kW stays allowed (bnetza.de BK6-22-300)`.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.kind {
            Kind::Consumption(p) => {
                write!(f, "consumption of {p} stays allowed ({})", self.provenance)
            }
            Kind::FeedIn(p) => write!(
                f,
                "feed-in of {} stays allowed ({})",
                Power::from_watts(-p.watts()),
                self.provenance
            ),
        }
    }
}

impl Guarantee {
    /// Consumption of `amount` stays allowed over `window`: no maximum below it.
    ///
    /// # Errors
    /// [`Error::NegativeAmount`] if `amount` is negative.
    pub fn consumption(
        window: Window,
        amount: Power,
        provenance: Provenance,
    ) -> Result<Guarantee, Error> {
        if amount < Power::ZERO {
            return Err(Error::NegativeAmount { power: amount });
        }
        Ok(Guarantee {
            window,
            kind: Kind::Consumption(amount),
            provenance,
        })
    }

    /// Feed-in of `amount` stays allowed over `window`: no minimum above `-amount`.
    ///
    /// # Errors
    /// [`Error::NegativeAmount`] if `amount` is negative.
    pub fn feed_in(
        window: Window,
        amount: Power,
        provenance: Provenance,
    ) -> Result<Guarantee, Error> {
        let min = negated_amount(amount)?;
        Ok(Guarantee {
            window,
            kind: Kind::FeedIn(min),
            provenance,
        })
    }

    /// The window.
    #[must_use]
    pub fn window(&self) -> Window {
        self.window
    }

    /// The signed power that must stay allowed: positive for consumption, negative for feed-in.
    #[must_use]
    pub fn power(&self) -> Power {
        match self.kind {
            Kind::Consumption(p) | Kind::FeedIn(p) => p,
        }
    }

    /// Who set it.
    #[must_use]
    pub fn provenance(&self) -> &Provenance {
        &self.provenance
    }

    /// The bound in `slot` that breaks this guarantee, with its source index.
    fn broken_by(&self, slot: Slot) -> Option<(Power, usize)> {
        match self.kind {
            Kind::Consumption(p) => slot.max.filter(|&(max, _)| max < p),
            Kind::FeedIn(p) => slot.min.filter(|&(min, _)| min > p),
        }
    }
}

/// One bound and the index of the provenance that set it.
type Sourced = Option<(Power, usize)>;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
struct Slot {
    min: Sourced,
    max: Sourced,
}

/// One applied limit, kept so that an explanation can list it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct Layer {
    first: u32,
    last: u32,
    bounds: Bounds,
    source: usize,
}

/// The allowed power per ISP of a grid, for each bound who set it, every limit applied, and the
/// guarantees in force.
///
/// Envelopes only ever get stricter: [`Envelope::combine`] takes the lower maximum and the
/// higher minimum in every ISP and fails if an ISP is left with no allowed power, or a
/// guarantee of either input would be broken.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Envelope {
    slots: Series<Slot>,
    provenances: Vec<Provenance>,
    layers: Vec<Layer>,
    guarantees: Vec<Guarantee>,
}

impl Envelope {
    /// No constraint in any ISP of `grid`.
    #[must_use]
    pub fn unbounded(grid: Grid) -> Envelope {
        Envelope {
            slots: Series::filled(grid, Slot::default()),
            provenances: Vec::new(),
            layers: Vec::new(),
            guarantees: Vec::new(),
        }
    }

    /// An envelope with `bounds` per ISP of `grid`, all set by `provenance`; runs of equal
    /// bounds become one layer each, so `explain` reads as the source wrote it.
    pub(crate) fn from_bounds(
        grid: Grid,
        bounds: &[Bounds],
        provenance: Provenance,
    ) -> Result<Envelope, Error> {
        let slots = Series::new(
            grid,
            bounds
                .iter()
                .map(|b| Slot {
                    min: b.min.map(|p| (p, 0)),
                    max: b.max.map(|p| (p, 0)),
                })
                .collect(),
        )?;
        let mut layers: Vec<Layer> = Vec::new();
        for (isp, &b) in slots.grid().numbers().zip(bounds) {
            if b == Bounds::UNBOUNDED {
                continue;
            }
            match layers.last_mut() {
                Some(l) if l.bounds == b && l.last + 1 == isp => l.last = isp,
                _ => layers.push(Layer {
                    first: isp,
                    last: isp,
                    bounds: b,
                    source: 0,
                }),
            }
        }
        Ok(Envelope {
            slots,
            provenances: vec![provenance],
            layers,
            guarantees: Vec::new(),
        })
    }

    /// This envelope with `limit` applied to every ISP its window overlaps, even partly. A
    /// limit that overlaps no ISP of the grid leaves the envelope unchanged;
    /// [`Limit::isps`] tells the caller so.
    ///
    /// # Errors
    /// [`Error::EmptyRange`] if an ISP is left with no allowed power;
    /// [`Error::GuaranteeBreached`] if the limit cuts below a guarantee.
    pub fn apply(&self, limit: &Limit) -> Result<Envelope, Error> {
        let Some(range) = limit.isps(self.grid()) else {
            return Ok(self.clone());
        };
        let set = Slot {
            min: limit.bounds.min.map(|p| (p, 0)),
            max: limit.bounds.max.map(|p| (p, 0)),
        };
        let values = self
            .grid()
            .numbers()
            .map(|isp| {
                if range.contains(&isp) {
                    set
                } else {
                    Slot::default()
                }
            })
            .collect();
        let other = Envelope {
            slots: Series::new(self.grid().clone(), values)?,
            provenances: vec![limit.provenance.clone()],
            layers: vec![Layer {
                first: *range.start(),
                last: *range.end(),
                bounds: limit.bounds,
                source: 0,
            }],
            guarantees: Vec::new(),
        };
        self.combine(&other)
    }

    /// The stricter of both envelopes in every ISP, with the guarantees of both. On equal
    /// bounds the provenance of `self` is kept; every input provenance is kept once.
    ///
    /// # Errors
    /// [`Error::GridMismatch`] for different grids; [`Error::EmptyRange`] naming the first
    /// ISP whose combined minimum is above its combined maximum;
    /// [`Error::GuaranteeBreached`] if a guarantee of either input is broken.
    pub fn combine(&self, other: &Envelope) -> Result<Envelope, Error> {
        self.slots.same_grid(other.grid())?;
        let mut provenances = self.provenances.clone();
        let remap: Vec<usize> = other
            .provenances
            .iter()
            .map(|p| {
                provenances.iter().position(|q| q == p).unwrap_or_else(|| {
                    provenances.push(p.clone());
                    provenances.len() - 1
                })
            })
            .collect();
        let mut values = Vec::with_capacity(self.slots.values().len());
        for (isp, (a, b)) in self
            .grid()
            .numbers()
            .zip(self.slots.values().iter().zip(other.slots.values()))
        {
            let b_min = b.min.and_then(|(p, i)| Some((p, *remap.get(i)?)));
            let b_max = b.max.and_then(|(p, i)| Some((p, *remap.get(i)?)));
            let min = stricter(a.min, b_min, |left, right| right > left);
            let max = stricter(a.max, b_max, |left, right| right < left);
            if let (Some((min, _)), Some((max, _))) = (min, max)
                && min > max
            {
                return Err(Error::EmptyRange {
                    isp: self.label(isp),
                    min,
                    max,
                });
            }
            values.push(Slot { min, max });
        }
        let mut layers = self.layers.clone();
        layers.extend(other.layers.iter().filter_map(|l| {
            Some(Layer {
                source: *remap.get(l.source)?,
                ..*l
            })
        }));
        let mut guarantees = self.guarantees.clone();
        for g in &other.guarantees {
            if !guarantees.contains(g) {
                guarantees.push(g.clone());
            }
        }
        let combined = Envelope {
            slots: Series::new(self.grid().clone(), values)?,
            provenances,
            layers,
            guarantees,
        };
        for g in &combined.guarantees {
            combined.check_guarantee(g)?;
        }
        Ok(combined)
    }

    /// This envelope with `guarantee` in force: every later [`apply`](Envelope::apply) and
    /// [`combine`](Envelope::combine) refuses a bound that cuts below it.
    ///
    /// ```
    /// use flexibility::jiff::{civil::{date, time}, tz::TimeZone, Timestamp};
    /// use flexibility::*;
    /// let berlin = TimeZone::get("Europe/Berlin")?;
    /// let grid = Grid::day(date(2026, 12, 1), &berlin, IspDuration::FIFTEEN_MINUTES)?;
    /// let day = Window::new(grid.start(), grid.end())?;
    /// let rule = Provenance::new("bnetza", "§ 14a minimum", Timestamp::UNIX_EPOCH);
    /// let dso = Provenance::new("dso.example", "order-42", Timestamp::UNIX_EPOCH);
    ///
    /// let envelope = Envelope::unbounded(grid.clone()).guarantee(&Guarantee::consumption(day, kw!(4.2), rule)?)?;
    /// let evening = grid.window(time(17, 0, 0, 0), time(19, 0, 0, 0))?;
    /// assert!(envelope.apply(&Limit::consumption_cap(evening, kw!(3), dso.clone())).is_err());
    /// assert!(envelope.apply(&Limit::consumption_cap(evening, kw!(4.2), dso)).is_ok());
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// # Errors
    /// [`Error::GuaranteeBreached`] if a bound already in the envelope breaks it.
    pub fn guarantee(&self, guarantee: &Guarantee) -> Result<Envelope, Error> {
        self.check_guarantee(guarantee)?;
        let mut next = self.clone();
        if !next.guarantees.contains(guarantee) {
            next.guarantees.push(guarantee.clone());
        }
        Ok(next)
    }

    /// The guarantees in force.
    #[must_use]
    pub fn guarantees(&self) -> &[Guarantee] {
        &self.guarantees
    }

    fn check_guarantee(&self, g: &Guarantee) -> Result<(), Error> {
        let Some(range) = self.grid().isps(g.window) else {
            return Ok(());
        };
        for isp in range {
            let Some(&slot) = self.slots.get(isp) else {
                continue;
            };
            if let Some((bound, source)) = g.broken_by(slot)
                && let Some(limit) = self.provenances.get(source)
            {
                return Err(Error::GuaranteeBreached(Box::new(Breach {
                    isp: self.label(isp),
                    bound,
                    guaranteed: g.power(),
                    limit: limit.clone(),
                    guarantee: g.provenance.clone(),
                })));
            }
        }
        Ok(())
    }

    /// The grid.
    #[must_use]
    pub fn grid(&self) -> &Grid {
        self.slots.grid()
    }

    /// The bounds of ISP `isp`, or `None` outside the grid.
    #[must_use]
    pub fn bounds(&self, isp: u32) -> Option<Bounds> {
        self.slots.get(isp).map(|s| Bounds {
            min: s.min.map(|(p, _)| p),
            max: s.max.map(|(p, _)| p),
        })
    }

    /// Who set the maximum of ISP `isp`; `None` if it has none.
    #[must_use]
    pub fn max_source(&self, isp: u32) -> Option<&Provenance> {
        let (_, i) = self.slots.get(isp)?.max?;
        self.provenances.get(i)
    }

    /// Who set the minimum of ISP `isp`; `None` if it has none.
    #[must_use]
    pub fn min_source(&self, isp: u32) -> Option<&Provenance> {
        let (_, i) = self.slots.get(isp)?.min?;
        self.provenances.get(i)
    }

    /// Every provenance that went into this envelope, each once.
    #[must_use]
    pub fn provenances(&self) -> &[Provenance] {
        &self.provenances
    }

    /// Why ISP `isp` allows what it allows: the bounds, who set each, and every other limit
    /// applied there (shadowed: in force, but looser). `None` outside the grid.
    #[must_use]
    pub fn explain(&self, isp: u32) -> Option<Explanation> {
        let slot = *self.slots.get(isp)?;
        let label = self.grid().label(isp)?;
        // The sides of a layer that are not the effective bound here: in force, but looser.
        let shadowed_part = |l: &Layer| Bounds {
            max: l
                .bounds
                .max
                .filter(|&p| !matches!(slot.max, Some((q, s)) if s == l.source && q == p)),
            min: l
                .bounds
                .min
                .filter(|&p| !matches!(slot.min, Some((q, s)) if s == l.source && q == p)),
        };
        let shadowed = self
            .layers
            .iter()
            .filter(|l| (l.first..=l.last).contains(&isp))
            .map(|l| (shadowed_part(l), l.source))
            .filter(|(b, _)| *b != Bounds::UNBOUNDED)
            .filter_map(|(b, i)| Some((b, self.provenances.get(i)?.clone())))
            .collect();
        Some(Explanation {
            label,
            bounds: self.bounds(isp)?,
            max_source: self.max_source(isp).cloned(),
            min_source: self.min_source(isp).cloned(),
            shadowed,
            guaranteed: self
                .guarantees
                .iter()
                .filter(|g| self.grid().isps(g.window).is_some_and(|r| r.contains(&isp)))
                .cloned()
                .collect(),
        })
    }

    /// How far `schedule` may still move in every ISP without leaving the envelope: up to the
    /// maximum and down to the minimum, as deviations from the plan. Where the plan already
    /// breaks a bound, that side is negative (up) or positive (down) by the excess.
    ///
    /// # Errors
    /// [`Error::GridMismatch`] if the schedule is on another grid; [`Error::Overflow`] at the
    /// edges of the range.
    pub fn headroom(&self, schedule: &Schedule) -> Result<Series<Headroom>, Error> {
        let series = schedule.series.zip_with(&self.slots, |planned, slot| {
            let up = slot
                .max
                .map(|(max, _)| max.deviation_from(*planned))
                .transpose()?;
            let down = slot
                .min
                .map(|(min, _)| min.deviation_from(*planned))
                .transpose()?;
            Ok::<_, Error>(Headroom { up, down })
        })?;
        series.try_map(Clone::clone)
    }

    fn label(&self, isp: u32) -> IspLabel {
        self.grid().label_total(isp)
    }
}

/// The stricter of two optional bounds; `right_wins(left, right)` says when `right` is
/// strictly stricter, so ties keep `left`.
fn stricter(left: Sourced, right: Sourced, right_wins: impl Fn(Power, Power) -> bool) -> Sourced {
    match (left, right) {
        (Some(l), Some(r)) => Some(if right_wins(l.0, r.0) { r } else { l }),
        (l, None) => l,
        (None, r) => r,
    }
}

/// Why one ISP allows what it allows.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Explanation {
    /// The ISP.
    pub label: IspLabel,
    /// The effective bounds.
    pub bounds: Bounds,
    /// Who set the maximum.
    pub max_source: Option<Provenance>,
    /// Who set the minimum.
    pub min_source: Option<Provenance>,
    /// Every other limit applied to this ISP, in the order applied.
    pub shadowed: Vec<(Bounds, Provenance)>,
    /// The guarantees in force in this ISP: no limit may cut below them.
    pub guaranteed: Vec<Guarantee>,
}

impl fmt::Display for Explanation {
    /// ```text
    /// ISP 69 (17:00–17:15 +01:00): max 4.2 kW (dso.example order-42)
    ///   shadowed: max 11 kW (grid.example connection-7)
    /// ```
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}: ", self.label)?;
        match (
            self.bounds.min,
            &self.min_source,
            self.bounds.max,
            &self.max_source,
        ) {
            (None, _, None, _) => f.write_str("unbounded")?,
            (min, min_src, max, max_src) => {
                let mut first = true;
                if let (Some(min), Some(src)) = (min, min_src) {
                    write!(f, "min {min} ({src})")?;
                    first = false;
                }
                if let (Some(max), Some(src)) = (max, max_src) {
                    if !first {
                        f.write_str(", ")?;
                    }
                    write!(f, "max {max} ({src})")?;
                }
            }
        }
        for (bounds, src) in &self.shadowed {
            write!(f, "\n  shadowed: {bounds} ({src})")?;
        }
        for g in &self.guaranteed {
            write!(f, "\n  guaranteed: {g}")?;
        }
        Ok(())
    }
}

/// How far a schedule may move in one ISP: `None` where the envelope has no bound.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Headroom {
    /// To the maximum: positive is room to consume more.
    pub up: Option<Deviation>,
    /// To the minimum: negative is room to consume less or feed in more.
    pub down: Option<Deviation>,
}

/// Planned power per ISP, with provenance.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Schedule {
    series: Series<Power>,
    provenance: Provenance,
}

/// Which bound a planned power breaks.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Broken {
    /// Above this maximum.
    AboveMax(Power),
    /// Below this minimum.
    BelowMin(Power),
}

/// One ISP in which a schedule leaves its envelope.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Violation {
    /// The ISP.
    pub label: IspLabel,
    /// The planned power.
    pub planned: Power,
    /// The bound it breaks.
    pub broken: Broken,
    /// Who set that bound.
    pub source: Provenance,
}

impl fmt::Display for Violation {
    /// `ISP 69 (17:00–17:15 +01:00): planned 7.4 kW above max 4.2 kW set by dso.example order-42`.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let (side, bound) = match self.broken {
            Broken::AboveMax(p) => ("above max", p),
            Broken::BelowMin(p) => ("below min", p),
        };
        write!(
            f,
            "{}: planned {} {side} {bound} set by {}",
            self.label, self.planned, self.source
        )
    }
}

impl Schedule {
    /// `series` planned by `provenance`.
    #[must_use]
    pub fn new(series: Series<Power>, provenance: Provenance) -> Schedule {
        Schedule { series, provenance }
    }

    /// The planned power per ISP.
    #[must_use]
    pub fn series(&self) -> &Series<Power> {
        &self.series
    }

    /// Who planned it.
    #[must_use]
    pub fn provenance(&self) -> &Provenance {
        &self.provenance
    }

    /// Every ISP in which the schedule leaves `envelope`, in ISP order; empty if it fits.
    ///
    /// # Errors
    /// [`Error::GridMismatch`] if the envelope is on another grid.
    pub fn check(&self, envelope: &Envelope) -> Result<Vec<Violation>, Error> {
        self.series.same_grid(envelope.grid())?;
        let mut violations = Vec::new();
        for ((isp, &planned), slot) in self.series.iter().zip(envelope.slots.values()) {
            let broken = match (slot.min, slot.max) {
                (_, Some((max, i))) if planned > max => Some((Broken::AboveMax(max), i)),
                (Some((min, i)), _) if planned < min => Some((Broken::BelowMin(min), i)),
                _ => None,
            };
            if let Some((broken, i)) = broken
                && let Some(source) = envelope.provenances.get(i)
            {
                violations.push(Violation {
                    label: envelope.label(isp),
                    planned,
                    broken,
                    source: source.clone(),
                });
            }
        }
        Ok(violations)
    }
}