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
//! Baselines: what a site would have done without the activation, by a named method.
//!
//! Every method is a pure function with required parameters and no defaults. It returns a
//! [`Baseline`] over the event's ISPs that records its method id, parameters, a digest of every
//! input and its derivation (which ISPs or days it used, which adjustment it applied), so the
//! other party can recompute it and compare one [`Digest`].
//!
//! A method id never changes its meaning: `mbma@1` computes tomorrow exactly what it computed
//! when a settlement named it. Divisions happen once, after summing, rounding half away from
//! zero to the watt; that rounding is part of the id.
//!
//! | Id | Baseline is |
//! |---|---|
//! | `dprognosis@1` | the aggregator's D-Prognosis, as sent (UFTP's default) |
//! | `schedule@1` | a schedule declared before the event |
//! | `mbma@1` | meter before / meter after: the mean of the last *n* ISPs before the event, held flat |
//! | `xofy@1` | the mean of the X highest of Y comparable days, optionally adjusted to the day |
//!
//! [`cards`] gives each method's formula, parameters, rounding, fit and gaming notes.

use std::fmt;
use std::ops::RangeInclusive;
use std::str::FromStr;

use jiff::civil::Date;

use crate::canon::{self, Digest, Value};
use crate::power::div_round;
use crate::{Deviation, Error, Grid, Power, Provenance, Rounding, Schedule, Series, Window};

/// The most comparable days X-of-Y reads: a year and a day.
pub const MAX_DAYS: u32 = 366;

/// A baselining method and its version.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum MethodId {
    /// `dprognosis@1`: the aggregator's D-Prognosis.
    DPrognosis1,
    /// `schedule@1`: a declared schedule.
    Schedule1,
    /// `mbma@1`: meter before / meter after.
    Mbma1,
    /// `xofy@1`: X of Y comparable days.
    XofY1,
}

impl MethodId {
    /// Every method, sorted by its id text.
    pub const ALL: [MethodId; 4] = [
        MethodId::DPrognosis1,
        MethodId::Mbma1,
        MethodId::Schedule1,
        MethodId::XofY1,
    ];

    /// `mbma@1`, the form UFTP's `BaselineReference` and a register entry use.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            MethodId::DPrognosis1 => "dprognosis@1",
            MethodId::Schedule1 => "schedule@1",
            MethodId::Mbma1 => "mbma@1",
            MethodId::XofY1 => "xofy@1",
        }
    }

    /// What this method does, for people.
    #[must_use]
    pub fn card(self) -> &'static MethodCard {
        CARDS.iter().find(|c| c.id == self).unwrap_or(&CARDS[0])
    }

    fn refuse(self, reason: impl Into<String>) -> Error {
        Error::Method {
            method: self,
            reason: reason.into(),
        }
    }
}

impl fmt::Display for MethodId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl FromStr for MethodId {
    type Err = Error;

    fn from_str(text: &str) -> Result<MethodId, Error> {
        MethodId::ALL
            .into_iter()
            .find(|m| m.as_str() == text)
            .ok_or_else(|| Error::ParseMethod {
                text: text.chars().take(80).collect(),
            })
    }
}

/// What a method does, in words: the unit a contract, a register entry and a reviewer read.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MethodCard {
    /// The id.
    pub id: MethodId,
    /// One sentence.
    pub summary: &'static str,
    /// The computation.
    pub formula: &'static str,
    /// Each parameter and its meaning. None has a default.
    pub parameters: &'static [(&'static str, &'static str)],
    /// Where it divides and how it rounds.
    pub rounding: &'static str,
    /// What it suits, and what it does not.
    pub fits: &'static str,
    /// Known ways to inflate it, and what closes each.
    pub gaming: &'static [(&'static str, &'static str)],
}

const ROUNDING: &str = "one division per ISP after summing, half away from zero to the watt";

static CARDS: [MethodCard; 4] = [
    MethodCard {
        id: MethodId::DPrognosis1,
        summary: "The aggregator's D-Prognosis for the day is the baseline, as sent.",
        formula: "baseline(isp) = prognosis(isp) for every ISP of the event",
        parameters: &[(
            "prognosis",
            "the D-Prognosis schedule, with who sent it and when",
        )],
        rounding: "none: the prognosis is taken as sent",
        fits: "UFTP's default method; any asset whose aggregator sends a D-Prognosis",
        gaming: &[(
            "the seller writes a high prognosis",
            "nothing in the method; the DSO compares prognoses with metered days (accuracy::score)",
        )],
    },
    MethodCard {
        id: MethodId::Mbma1,
        summary: "Meter before / meter after: the mean of the last n ISPs before the event, held flat.",
        formula: "baseline(isp) = round(Σ measured(i) / n) for the n ISPs i ending gap ISPs before the event's first ISP",
        parameters: &[
            (
                "n",
                "how many ISPs before the event are averaged; at least 1",
            ),
            (
                "gap",
                "ISPs skipped between the averaged ISPs and the event, so a notification cannot move the window",
            ),
        ],
        rounding: ROUNDING,
        fits: "short activations, heat pumps, curtailment; fails on ramps (the accuracy score shows it)",
        gaming: &[(
            "raise consumption just before the event",
            "gap: the averaged ISPs end before the notification",
        )],
    },
    MethodCard {
        id: MethodId::Schedule1,
        summary: "A schedule the asset declared before the event is the baseline.",
        formula: "baseline(isp) = declared(isp) for every ISP of the event",
        parameters: &[(
            "declared",
            "the committed schedule (an S2 plan, a Fahrplan), with who declared it and when",
        )],
        rounding: "none: the schedule is taken as declared",
        fits: "batteries and scheduled assets; a declarative baseline",
        gaming: &[(
            "declare a schedule after the notification",
            "the contract's cut-off: the schedule's provenance carries its issue instant",
        )],
    },
    MethodCard {
        id: MethodId::XofY1,
        summary: "The mean of the X highest of Y comparable days, optionally adjusted to the day.",
        formula: "rank the Y days by total consumption over the event ISPs (ties: later date first); baseline(isp) = round(Σ over the X highest days of day(isp) / X); then the adjustment",
        parameters: &[
            ("x", "how many of the highest days are averaged; 1 ≤ x ≤ y"),
            (
                "y",
                "how many comparable days are given, already filtered by the caller (day type, no event, no holiday); at most 366",
            ),
            (
                "adjustment",
                "none; additive {window, gap, cap}: shift by round(Σ(actual − baseline) / window) over the window ISPs ending gap ISPs before the event, within ±cap; ratio {window, gap, cap_percent}: scale by Σ actual / Σ baseline over that window, within 1 ± cap_percent %",
            ),
        ],
        rounding: ROUNDING,
        fits: "household and commercial loads; PJM, CAISO, NYISO and Elia run variants",
        gaming: &[
            (
                "pick high days",
                "the caller filters the Y days by rule before the event; ranking is fixed",
            ),
            (
                "inflate the adjustment window",
                "the window ends gap ISPs before the event, and the cap bounds the shift",
            ),
        ],
    },
];

/// Every method card, in id order.
#[must_use]
pub fn cards() -> &'static [MethodCard] {
    &CARDS
}

/// Parameters of `mbma@1`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Mbma {
    /// ISPs averaged; at least 1.
    pub n: u32,
    /// ISPs skipped between the averaged ISPs and the event.
    pub gap: u32,
}

/// Parameters of `xofy@1`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct XofY {
    /// Highest days averaged.
    pub x: u32,
    /// Comparable days given.
    pub y: u32,
    /// The same-day adjustment.
    pub adjustment: Adjustment,
}

/// The same-day adjustment of `xofy@1`. `None` is a choice, not a default.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Adjustment {
    /// No adjustment.
    None,
    /// Shift by the mean difference over `window` ISPs ending `gap` ISPs before the event,
    /// within ±`cap` if given.
    Additive {
        /// ISPs in the adjustment window; at least 1.
        window: u32,
        /// ISPs between the window and the event.
        gap: u32,
        /// The largest shift, if capped.
        cap: Option<Power>,
    },
    /// Scale by Σ actual / Σ baseline over `window` ISPs ending `gap` ISPs before the event,
    /// within 1 ± `cap_percent` %.
    Ratio {
        /// ISPs in the adjustment window; at least 1.
        window: u32,
        /// ISPs between the window and the event.
        gap: u32,
        /// The largest change of the factor, in percent.
        cap_percent: u32,
    },
}

/// What a baseline was computed from.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Derivation {
    /// Taken from a declared schedule.
    Declared {
        /// Who declared it.
        provenance: Provenance,
    },
    /// The ISPs of the measured series that were averaged.
    Mbma {
        /// The ISPs.
        isps: RangeInclusive<u32>,
    },
    /// The days averaged, and the adjustment applied.
    XofY {
        /// The X days, highest first.
        days: Vec<Date>,
        /// The adjustment, if any.
        adjustment: Option<Applied>,
    },
}

/// An adjustment as applied.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Applied {
    /// Every ISP shifted by this deviation (after the cap).
    Additive(Deviation),
    /// Every ISP scaled by `numerator / denominator` (after the cap).
    Ratio {
        /// The numerator.
        numerator: i128,
        /// The denominator, positive.
        denominator: i128,
    },
}

/// A baseline over the event's ISPs, with what it was computed from.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Baseline {
    method: MethodId,
    parameters: Value,
    series: Series<Power>,
    inputs: Vec<(&'static str, Digest)>,
    derivation: Derivation,
}

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

    /// The baseline per ISP of the event.
    #[must_use]
    pub fn series(&self) -> &Series<Power> {
        &self.series
    }

    /// What it was computed from.
    #[must_use]
    pub fn derivation(&self) -> &Derivation {
        &self.derivation
    }

    /// The digest of each input, by name.
    #[must_use]
    pub fn inputs(&self) -> &[(&'static str, Digest)] {
        &self.inputs
    }

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

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

    pub(crate) fn value(&self) -> Value {
        Value::obj([
            ("derivation", derivation(&self.derivation)),
            ("inputs", inputs(&self.inputs)),
            ("method", Value::str(self.method)),
            ("parameters", self.parameters.clone()),
            ("profile", canon::profile("baseline")),
            ("series", canon::powers(&self.series)),
        ])
    }
}

/// The digest of an `xofy@1` history: `flexibility.history@1`, the days in date order.
fn history_digest(days: &[(Date, &Series<Power>)]) -> Result<Digest, Error> {
    Ok(Value::obj([
        (
            "days",
            Value::Arr(days.iter().map(|(_, s)| canon::powers(s)).collect()),
        ),
        ("profile", canon::profile("history")),
    ])
    .exact()?
    .digest())
}

/// The history days in date order, each checked against `day`: the same local times, dated
/// before it, each date once.
fn history_days<'a>(
    method: MethodId,
    day: &Grid,
    history: &'a [Series<Power>],
) -> Result<Vec<(Date, &'a Series<Power>)>, Error> {
    let target = day.date();
    let mut days: Vec<(Date, &Series<Power>)> = Vec::with_capacity(history.len());
    for h in history {
        // The date in the target's zone; the series must cover the target's local wall-clock
        // times, ISP by ISP (so a slice of a DST day lines up by the hour, not the ISP number).
        let d = day.zone().to_datetime(h.grid().start()).date();
        if !same_local_times(day, h.grid()) {
            return Err(method.refuse(format!(
                "the history series starting {} does not cover the target's local times {} ({} ISPs of {}): on a day that skips or repeats an hour, give the event's hours only",
                h.grid().start(),
                day,
                h.grid().count(),
                h.grid().isp()
            )));
        }
        if d >= target {
            return Err(method.refuse(format!("{d} is not before the target day {target}")));
        }
        days.push((d, h));
    }
    days.sort_by_key(|(d, _)| *d);
    if let Some(w) = days.windows(2).find(|w| w[0].0 == w[1].0) {
        return Err(method.refuse(format!("{} is given twice", w[0].0)));
    }
    Ok(days)
}

/// Whether `history` has the ISP length and count of `day` and each of its ISPs starts at the
/// same local wall-clock time, in `day`'s zone, as the matching ISP of `day`.
fn same_local_times(day: &Grid, history: &Grid) -> bool {
    let zone = day.zone();
    history.isp() == day.isp()
        && history.count() == day.count()
        && day.numbers().zip(history.numbers()).all(|(a, b)| {
            match (day.interval(a), history.interval(b)) {
                (Some(x), Some(y)) => {
                    zone.to_datetime(x.from()).time() == zone.to_datetime(y.from()).time()
                }
                _ => false,
            }
        })
}

/// The baseline, refused if its document holds an integer beyond ±2^53.
fn checked(b: Baseline) -> Result<Baseline, Error> {
    b.value().exact()?;
    Ok(b)
}

pub(crate) fn inputs(list: &[(&'static str, Digest)]) -> Value {
    Value::Obj(list.iter().map(|(k, d)| (*k, Value::str(d))).collect())
}

fn derivation(d: &Derivation) -> Value {
    match d {
        Derivation::Declared { provenance } => {
            Value::obj([("declared", canon::provenance(provenance))])
        }
        Derivation::Mbma { isps } => Value::obj([(
            "isps",
            Value::Arr(vec![Value::int(*isps.start()), Value::int(*isps.end())]),
        )]),
        Derivation::XofY { days, adjustment } => {
            let mut v = vec![("days", Value::Arr(days.iter().map(Value::str).collect()))];
            match adjustment {
                Some(Applied::Additive(d)) => v.push(("additive", Value::int(d.watts()))),
                Some(Applied::Ratio {
                    numerator,
                    denominator,
                }) => v.push((
                    "ratio",
                    Value::Arr(vec![Value::Int(*numerator), Value::Int(*denominator)]),
                )),
                None => {}
            }
            Value::Obj(v.into_iter().collect())
        }
    }
}

/// The event's ISPs on `grid`, as a sub-grid.
fn event_isps(method: MethodId, grid: &Grid, event: Window) -> Result<RangeInclusive<u32>, Error> {
    grid.isps(event)
        .ok_or_else(|| method.refuse(format!("the event {event} overlaps no ISP of {grid}")))
}

fn declared(method: MethodId, schedule: &Schedule, event: Window) -> Result<Baseline, Error> {
    let isps = event_isps(method, schedule.series().grid(), event)?;
    let series = schedule.series().slice(isps)?;
    let declared = Value::obj([
        ("profile", canon::profile("schedule")),
        ("provenance", canon::provenance(schedule.provenance())),
        ("series", canon::powers(schedule.series())),
    ])
    .exact()?;
    checked(Baseline {
        method,
        parameters: Value::obj([("event", canon::window(event))]),
        series,
        inputs: vec![("declared", declared.digest())],
        derivation: Derivation::Declared {
            provenance: schedule.provenance().clone(),
        },
    })
}

/// `dprognosis@1`: the D-Prognosis, as sent, over the event's ISPs.
///
/// # Errors
/// [`Error::Method`] if the event overlaps no ISP of the prognosis.
pub fn dprognosis(prognosis: &Schedule, event: Window) -> Result<Baseline, Error> {
    declared(MethodId::DPrognosis1, prognosis, event)
}

/// `schedule@1`: a declared schedule, over the event's ISPs.
///
/// # Errors
/// [`Error::Method`] if the event overlaps no ISP of the schedule.
pub fn schedule(declared_schedule: &Schedule, event: Window) -> Result<Baseline, Error> {
    declared(MethodId::Schedule1, declared_schedule, event)
}

/// The `n` ISPs ending `gap` ISPs before `first`.
fn window_before(
    method: MethodId,
    grid: &Grid,
    first: u32,
    n: u32,
    gap: u32,
) -> Result<RangeInclusive<u32>, Error> {
    if n == 0 {
        return Err(method.refuse("the window must have at least one ISP"));
    }
    let start = u64::from(first)
        .checked_sub(u64::from(gap) + u64::from(n))
        .filter(|&s| s >= u64::from(grid.first()))
        .ok_or_else(|| {
            method.refuse(format!(
                "needs {n} ISPs ending {gap} ISPs before ISP {first}, but the series starts too late"
            ))
        })?;
    // grid.first() <= start < first <= u32::MAX.
    let start = u32::try_from(start).map_err(|_| method.refuse("ISP out of range"))?;
    Ok(start..=start + (n - 1))
}

fn mean(method: MethodId, sum: i128, count: u32) -> Result<Power, Error> {
    let w = div_round(sum, i128::from(count), Rounding::HalfAwayFromZero)?;
    i64::try_from(w)
        .map(Power::from_watts)
        .map_err(|_| method.refuse("the mean is outside the representable range"))
}

/// Σ watts over `isps`, refusing an ISP the series does not have rather than skipping it.
fn sum(
    method: MethodId,
    series: &Series<Power>,
    isps: &RangeInclusive<u32>,
) -> Result<i128, Error> {
    isps.clone().try_fold(0i128, |acc, i| {
        series
            .get(i)
            .map(|p| acc + i128::from(p.watts()))
            .ok_or_else(|| method.refuse(format!("ISP {i} is not in {}", series.grid())))
    })
}

/// `mbma@1`: the mean of the `n` measured ISPs ending `gap` ISPs before the event, held flat
/// over the event's ISPs.
///
/// ```
/// use flexibility::jiff::{civil::{date, time}, tz::TimeZone};
/// use flexibility::baseline::{self, Mbma};
/// use flexibility::*;
/// let berlin = TimeZone::get("Europe/Berlin")?;
/// let grid = Grid::day(date(2026, 12, 1), &berlin, IspDuration::FIFTEEN_MINUTES)?;
/// let measured = Series::filled(grid.clone(), kw!(7));
/// let evening = grid.window(time(17, 0, 0, 0), time(19, 0, 0, 0))?;
/// let b = baseline::mbma(&measured, evening, Mbma { n: 4, gap: 1 })?;
/// assert_eq!(b.series().values(), &[kw!(7); 8]);
/// assert_eq!(b.derivation(), &baseline::Derivation::Mbma { isps: 64..=67 });
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// # Errors
/// [`Error::Method`] if `n` is 0, the window starts before the series, or the event overlaps
/// no ISP.
pub fn mbma(measured: &Series<Power>, event: Window, params: Mbma) -> Result<Baseline, Error> {
    let method = MethodId::Mbma1;
    let isps = event_isps(method, measured.grid(), event)?;
    let window = window_before(method, measured.grid(), *isps.start(), params.n, params.gap)?;
    let level = mean(method, sum(method, measured, &window)?, params.n)?;
    let grid = measured.grid().slice(isps)?;
    checked(Baseline {
        method,
        parameters: Value::obj([
            ("event", canon::window(event)),
            ("gap", Value::int(params.gap)),
            ("n", Value::int(params.n)),
        ]),
        series: Series::filled(grid, level),
        inputs: vec![("measured", canon::power_input(measured)?)],
        derivation: Derivation::Mbma { isps: window },
    })
}

/// `xofy@1`: the per-ISP mean of the `x` days among `history` with the highest consumption over
/// the event's ISPs, over the event's ISPs of `day`, adjusted with `same_day` if asked.
///
/// `history` is exactly the `y` comparable days, already filtered by the caller; each must
/// cover the same local wall-clock times as `day`, ISP by ISP, dated before it, each date once.
/// The order they are given in does not matter. Days line up by local time, not ISP number: on
/// a day that skips or repeats an hour (92 or 100 quarter hours), pass `day` and the history
/// as the event's hours only (`Grid::slice`), and they compare 17:00 with 17:00.
///
/// # Errors
/// [`Error::Method`] naming the reason: `y` above [`MAX_DAYS`], `x` not in `1..=y`, a count of
/// days other than `y`, a day of another length, a date not before `day`, a repeated date, an
/// adjustment without `same_day`, a ratio window with no positive baseline.
pub fn xofy(
    day: &Grid,
    event: Window,
    history: &[Series<Power>],
    same_day: Option<&Series<Power>>,
    params: XofY,
) -> Result<Baseline, Error> {
    let method = MethodId::XofY1;
    let XofY { x, y, adjustment } = params;
    if y > MAX_DAYS {
        return Err(method.refuse(format!("y = {y} is above {MAX_DAYS} days")));
    }
    if x == 0 || x > y {
        return Err(method.refuse(format!("x = {x} must be within 1..={y}")));
    }
    if history.len() != y as usize {
        return Err(method.refuse(format!(
            "needs y = {y} comparable days, got {}",
            history.len()
        )));
    }
    let days = history_days(method, day, history)?;
    let history_digest = history_digest(&days)?;

    let event_range = event_isps(method, day, event)?;
    // Each day on the target's numbering: ISP n of a history day is the target's ISP n.
    let aligned: Vec<(Date, Series<Power>)> = days
        .iter()
        .map(|(d, s)| {
            let g = s.grid();
            let grid = Grid::numbered(
                g.start(),
                g.isp(),
                g.count(),
                day.first(),
                day.zone().clone(),
            )?;
            Ok((*d, Series::new(grid, s.values().to_vec())?))
        })
        .collect::<Result<_, Error>>()?;
    // Rank by consumption over the event ISPs, highest first; ties: the later date first.
    let mut ranked: Vec<(i128, Date, &Series<Power>)> = aligned
        .iter()
        .map(|(d, s)| Ok((sum(method, s, &event_range)?, *d, s)))
        .collect::<Result<_, Error>>()?;
    ranked.sort_by(|a, b| b.0.cmp(&a.0).then(b.1.cmp(&a.1)));
    ranked.truncate(x as usize);
    let chosen: Vec<&Series<Power>> = ranked.iter().map(|(_, _, s)| *s).collect();
    let unadjusted = |isp: u32| -> Result<Power, Error> {
        let total = chosen
            .iter()
            .try_fold(0i128, |acc, s| Ok(acc + sum(method, s, &(isp..=isp))?))?;
        mean(method, total, x)
    };

    let mut parameters = vec![
        ("event", canon::window(event)),
        ("x", Value::int(x)),
        ("y", Value::int(y)),
    ];
    let mut inputs = vec![("history", history_digest)];
    let (applied, adjustment_value) = if adjustment == Adjustment::None {
        (None, Value::str("none"))
    } else {
        let actual = same_day_series(method, day, same_day)?;
        inputs.push(("same_day", canon::power_input(actual)?));
        adjust(
            method,
            day,
            *event_range.start(),
            actual,
            &unadjusted,
            adjustment,
        )?
    };
    parameters.push(("adjustment", adjustment_value));

    let values = event_range
        .clone()
        .map(|isp| {
            let b = unadjusted(isp)?;
            applied.map_or(Ok(b), |a| a.apply(b))
        })
        .collect::<Result<Vec<_>, _>>()?;
    let grid = day.slice(event_range)?;
    checked(Baseline {
        method,
        parameters: Value::Obj(parameters.into_iter().collect()),
        series: Series::new(grid, values)?,
        inputs,
        derivation: Derivation::XofY {
            days: ranked.iter().map(|(_, d, _)| *d).collect(),
            adjustment: applied,
        },
    })
}

fn same_day_series<'a>(
    method: MethodId,
    day: &Grid,
    same_day: Option<&'a Series<Power>>,
) -> Result<&'a Series<Power>, Error> {
    let s = same_day
        .ok_or_else(|| method.refuse("an adjustment needs the day's own measurement (same_day)"))?;
    s.same_grid(day)?;
    Ok(s)
}

/// The adjustment over the window before the event's first ISP, as applied, and its parameters.
fn adjust(
    method: MethodId,
    day: &Grid,
    first: u32,
    actual: &Series<Power>,
    unadjusted: &dyn Fn(u32) -> Result<Power, Error>,
    adjustment: Adjustment,
) -> Result<(Option<Applied>, Value), Error> {
    let measured = |isp| sum(method, actual, &(isp..=isp));
    match adjustment {
        Adjustment::None => Ok((None, Value::str("none"))),
        Adjustment::Additive { window, gap, cap } => {
            let w = window_before(method, day, first, window, gap)?;
            let mut diff: i128 = 0;
            for isp in w {
                diff += measured(isp)? - i128::from(unadjusted(isp)?.watts());
            }
            let mut delta = div_round(diff, i128::from(window), Rounding::HalfAwayFromZero)?;
            if let Some(cap) = cap {
                if cap < Power::ZERO {
                    return Err(
                        method.refuse(format!("the additive cap {cap} must not be negative"))
                    );
                }
                let c = i128::from(cap.watts());
                delta = delta.clamp(-c, c);
            }
            let delta = i64::try_from(delta)
                .map(Deviation::from_watts)
                .map_err(|_| method.refuse("the adjustment is outside the representable range"))?;
            let value = Value::obj([
                (
                    "cap",
                    cap.map_or(Value::str("none"), |c| Value::int(c.watts())),
                ),
                ("gap", Value::int(gap)),
                ("kind", Value::str("additive")),
                ("window", Value::int(window)),
            ]);
            Ok((Some(Applied::Additive(delta)), value))
        }
        Adjustment::Ratio {
            window,
            gap,
            cap_percent,
        } => {
            let w = window_before(method, day, first, window, gap)?;
            let (mut num, mut den) = (0i128, 0i128);
            for isp in w.clone() {
                num += measured(isp)?;
                den += i128::from(unadjusted(isp)?.watts());
            }
            if den <= 0 {
                return Err(method.refuse(format!(
                    "the ratio window ISPs {}..={} have no positive baseline consumption",
                    w.start(),
                    w.end()
                )));
            }
            // Clamp num/den to [1 - c/100, 1 + c/100] by cross multiplication.
            let c = i128::from(cap_percent);
            let (low, high) = ((100 - c).max(0), 100 + c);
            if num * 100 < low * den {
                (num, den) = (low, 100);
            } else if num * 100 > high * den {
                (num, den) = (high, 100);
            }
            let value = Value::obj([
                ("cap_percent", Value::int(cap_percent)),
                ("gap", Value::int(gap)),
                ("kind", Value::str("ratio")),
                ("window", Value::int(window)),
            ]);
            Ok((
                Some(Applied::Ratio {
                    numerator: num,
                    denominator: den,
                }),
                value,
            ))
        }
    }
}

impl Applied {
    /// `baseline` with this adjustment applied.
    ///
    /// # Errors
    /// [`Error::Overflow`] or [`Error::Method`] outside the representable range.
    pub fn apply(self, baseline: Power) -> Result<Power, Error> {
        match self {
            Applied::Additive(delta) => baseline.checked_add_deviation(delta),
            Applied::Ratio {
                numerator,
                denominator,
            } => {
                let product =
                    i128::from(baseline.watts())
                        .checked_mul(numerator)
                        .ok_or(Error::Overflow {
                            quantity: "power",
                            operation: "ratio adjustment",
                            left: i128::from(baseline.watts()),
                            right: Some(numerator),
                        })?;
                let w = div_round(product, denominator, Rounding::HalfAwayFromZero)?;
                i64::try_from(w).map(Power::from_watts).map_err(|_| {
                    MethodId::XofY1
                        .refuse("the adjusted baseline is outside the representable range")
                })
            }
        }
    }
}