flexibility 0.1.1

Grid flexibility as exact, replayable arithmetic: limits, baselines, UFTP-exact settlement, and UFTP, EEBUS, S2, OpenADR, IEC 104 converters.
Documentation
//! Rebound: what comes back after an order. Deferred load returns once the activation ends;
//! the NC DR defines the *rebound effect* (Art 2(30)) and asks baselining to consider proven
//! rebound (Art 14(3)). A [`Rebound`] reports, for a window right after a settlement, the
//! deviation from the baseline **opposite** to the order, per ISP and in total, never negative.
//! Whether a contract nets, prices or ignores it is the contract's; this is the quantity.
//!
//! ```
//! # use flexibility::baseline::{self, Mbma};
//! # use flexibility::jiff::{civil::{date, time}, tz::TimeZone};
//! # use flexibility::*;
//! # let berlin = TimeZone::get("Europe/Berlin")?;
//! # let grid = Grid::day(date(2026, 12, 1), &berlin, IspDuration::FIFTEEN_MINUTES)?;
//! # let measured = Series::new(grid.clone(), grid.numbers().map(|isp| match isp {
//! #     69..=76 => kw!(4.5), 77..=80 => kw!(9), _ => kw!(7) }).collect())?;
//! let evening = grid.window(time(17, 0, 0, 0), time(19, 0, 0, 0))?;
//! let after = grid.window(time(19, 0, 0, 0), time(20, 0, 0, 0))?;
//! let mbma = Mbma { n: 4, gap: 1 };
//! let actual = measured.over(evening)?;
//! let ordered = Series::filled(actual.grid().clone(), Deviation::from_watts(-3_000));
//! let settlement = settle(&baseline::mbma(&measured, evening, mbma)?, &actual, &ordered, MeasurementPoint::ConnectionPoint)?;
//!
//! // The baseline over the order *and* the hour after it: the same meter-before ISPs.
//! let through = Window::new(evening.from(), after.until())?;
//! let extended = baseline::mbma(&measured, through, mbma)?;
//! // In the hour after the order, the site draws 2 kW above its baseline: 2 kWh came back.
//! let rebound = settlement.rebound(&extended, &measured.over(after)?, MeasurementPoint::ConnectionPoint)?;
//! assert_eq!(rebound.total(), kwh!(2));
//! assert_eq!(rebound.lines()[0].to_string(), "ISP 77 (19:00–19:15 +01:00): baseline 7 kW, actual 9 kW, rebound 2 kW");
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

use std::fmt;

use crate::canon::{self, Digest, Value};
use crate::{
    Baseline, Energy, Error, IspLabel, MeasurementPoint, Power, Series, Settlement, Window,
};

/// One ISP of a [`Rebound`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ReboundLine {
    /// The ISP.
    pub isp: IspLabel,
    /// The baseline.
    pub baseline: Power,
    /// The measured power.
    pub actual: Power,
    /// The deviation opposite to the order, never negative.
    pub rebound: Power,
}

impl fmt::Display for ReboundLine {
    /// `ISP 77 (19:00–19:15 +01:00): baseline 7 kW, actual 9 kW, rebound 2 kW`.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}: baseline {}, actual {}, rebound {}",
            self.isp, self.baseline, self.actual, self.rebound
        )
    }
}

/// The rebound after a settlement: per ISP of the window that follows it, and in total, with
/// the digests of what it was computed from, the settlement's among them.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Rebound {
    lines: Vec<ReboundLine>,
    total: Energy,
    settlement: Digest,
    baseline: Digest,
    actual: Digest,
    method: crate::MethodId,
    measured_at: MeasurementPoint,
    grid: Value,
}

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

impl Settlement {
    /// The rebound in the window right after this settlement (the ISPs of `actual`): per ISP,
    /// the deviation of `actual` from `baseline` opposite to the order, never negative.
    ///
    /// `baseline` is the settlement's method computed over the order **and** the window
    /// together, so that a method like `mbma@1` reads the same ISPs before the order rather than
    /// the order itself; its values over the order must be the settlement's baselines. A
    /// baseline over the window alone is refused.
    ///
    /// # Errors
    /// [`Error::Mismatch`] if the window does not start where the settlement ends, has another
    /// ISP length, the baseline does not cover the order and the window, differs from the
    /// settlement's over the order, or has another method, or the measurement point differs; [`Error::Method`] if
    /// the ordered power has no single direction; [`Error::Overflow`] at the edges.
    pub fn rebound(
        &self,
        baseline: &Baseline,
        actual: &Series<Power>,
        measured_at: MeasurementPoint,
    ) -> Result<Rebound, Error> {
        if &measured_at != self.measured_at() {
            return Err(mismatch("measured_at", self.measured_at(), measured_at));
        }
        if baseline.method() != self.method() {
            return Err(mismatch("method", self.method(), baseline.method()));
        }
        let window = actual.grid();
        if window.isp() != self.grid().isp() {
            return Err(mismatch("ISP-Duration", self.grid().isp(), window.isp()));
        }
        if window.start() != self.grid().end() {
            return Err(mismatch(
                "rebound window start",
                self.grid().end(),
                window.start(),
            ));
        }
        let base = baseline.series();
        let covered = Window::new(window.start(), window.end())
            .ok()
            .and_then(|w| base.over(w).ok())
            .filter(|b| b.grid().start() == window.start() && b.grid().count() == window.count())
            .ok_or_else(|| mismatch("baseline window", window, base.grid()))?;
        // The baseline must cover the order too: a method like mbma@1 over the window alone reads
        // the order's own reduced ISPs as "before" and overstates what came back.
        for l in self.lines() {
            let during = l.isp.window();
            match base.over(during) {
                Ok(b) if b.grid().start() == during.from() => {
                    if b.values().first() != Some(&l.baseline) {
                        return Err(mismatch("baseline during the order", l.isp, l.baseline));
                    }
                }
                _ => {
                    return Err(mismatch(
                        "baseline during the order",
                        format!("{} covered", l.isp),
                        "not covered: compute it over the order and the window together",
                    ));
                }
            }
        }
        let sign = self.order_sign()?;
        let seconds = i128::from(window.isp().minutes()) * 60;
        let mut total = 0i128;
        let mut lines = Vec::with_capacity(window.count() as usize);
        for ((isp, &a), &b) in actual.iter().zip(covered.values()) {
            let back = ((i128::from(a.watts()) - i128::from(b.watts())) * -sign).max(0);
            let watts = i64::try_from(back).map_err(|_| Error::Overflow {
                quantity: "power",
                operation: "rebound",
                left: back,
                right: None,
            })?;
            total += back * seconds;
            lines.push(ReboundLine {
                isp: window.label_total(isp),
                baseline: b,
                actual: a,
                rebound: Power::from_watts(watts),
            });
        }
        let rebound = Rebound {
            lines,
            total: Energy::from_sum(total)?,
            settlement: self.digest(),
            baseline: baseline.digest(),
            actual: canon::power_input(actual)?,
            method: self.method(),
            measured_at,
            grid: canon::grid(window),
        };
        rebound.value().exact()?;
        Ok(rebound)
    }

    /// The sign of the order: +1 for more consumption, −1 for less; refused if the ordered
    /// power is zero throughout or changes direction.
    fn order_sign(&self) -> Result<i128, Error> {
        let mut signs = self
            .lines()
            .iter()
            .map(|l| i128::from(l.ordered.watts()).signum())
            .filter(|&s| s != 0);
        let first = signs.next();
        match first {
            Some(s) if signs.all(|t| t == s) => Ok(s),
            _ => Err(Error::Method {
                method: self.method(),
                reason: "rebound needs an order in one direction: the ordered power is zero \
                         or changes sign"
                    .into(),
            }),
        }
    }
}

impl Rebound {
    /// One line per ISP of the window.
    #[must_use]
    pub fn lines(&self) -> &[ReboundLine] {
        &self.lines
    }

    /// The rebound energy over the window.
    #[must_use]
    pub fn total(&self) -> Energy {
        self.total
    }

    /// The digest of the settlement this rebound follows.
    #[must_use]
    pub fn settlement(&self) -> Digest {
        self.settlement
    }

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

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

    fn value(&self) -> Value {
        let lines = self
            .lines
            .iter()
            .map(|l| {
                Value::obj([
                    ("actual", Value::int(l.actual.watts())),
                    ("baseline", Value::int(l.baseline.watts())),
                    ("isp", Value::int(l.isp.isp())),
                    ("rebound", Value::int(l.rebound.watts())),
                ])
            })
            .collect();
        Value::obj([
            ("grid", self.grid.clone()),
            (
                "inputs",
                Value::obj([
                    ("actual", Value::str(self.actual)),
                    ("baseline", Value::str(self.baseline)),
                    ("settlement", Value::str(self.settlement)),
                ]),
            ),
            ("lines", Value::Arr(lines)),
            ("measured_at", self.measured_at.canonical_value()),
            ("method", Value::str(self.method)),
            ("profile", canon::profile("rebound")),
            (
                "totals",
                Value::obj([("rebound_ws", Value::int(self.total.watt_seconds()))]),
            ),
        ])
    }
}

impl fmt::Display for Rebound {
    /// One line per ISP, then the total, the settlement it follows and the digest.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for line in &self.lines {
            writeln!(f, "{line}")?;
        }
        write!(
            f,
            "rebound {} after settlement {}, digest {}",
            self.total,
            self.settlement,
            self.digest()
        )
    }
}