flexibility 0.1.1

Grid flexibility as exact, replayable arithmetic: limits, baselines, UFTP-exact settlement, and UFTP, EEBUS, S2, OpenADR, IEC 104 converters.
Documentation
//! Bounds on a deviation from a baseline: what a UFTP FlexRequest asks for.
//!
//! A limit is absolute; a request is *"always relative to the agreed baseline"* [UFTP 3.1
//! § 2.4.4]. A [`DeviationEnvelope`] holds the request's [`Band`] per ISP. It checks an offer
//! or an order (a `Series<Deviation>`) against the request, and
//! [`resolve`](DeviationEnvelope::resolve) turns it into an absolute [`Envelope`] once a
//! baseline is agreed.

use std::fmt;

use crate::{Bounds, Deviation, Envelope, Error, Grid, IspLabel, Power, Provenance, Series};

/// Why a request bounds an ISP [UFTP 3.1 § 2.4.4].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Disposition {
    /// A deviation is needed here.
    Requested,
    /// There is room to deviate here.
    Available,
    /// The request does not say. UFTP's XSD makes the disposition optional with no default,
    /// so none is guessed.
    Unstated,
}

impl fmt::Display for Disposition {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Disposition::Requested => "requested",
            Disposition::Available => "available",
            Disposition::Unstated => "disposition unstated",
        })
    }
}

/// The allowed deviation in one ISP, both ends inclusive, and why it is bounded.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Band {
    /// The lowest allowed deviation: negative is consuming less or feeding in more.
    pub min: Deviation,
    /// The highest allowed deviation.
    pub max: Deviation,
    /// Requested, available or unstated.
    pub disposition: Disposition,
}

impl Band {
    /// A deviation between `min` and `max`.
    ///
    /// # Errors
    /// [`Error::InvertedBand`] if `min` is above `max`.
    pub fn new(min: Deviation, max: Deviation, disposition: Disposition) -> Result<Band, Error> {
        if min > max {
            return Err(Error::InvertedBand { min, max });
        }
        Ok(Band {
            min,
            max,
            disposition,
        })
    }

    /// Whether `deviation` lies within the band.
    #[must_use]
    pub fn contains(self, deviation: Deviation) -> bool {
        self.min <= deviation && deviation <= self.max
    }
}

impl fmt::Display for Band {
    /// `-30 kW to -10 kW (requested)`.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} to {} ({})", self.min, self.max, self.disposition)
    }
}

/// Bounds on the deviation from a baseline per ISP, set by one party: a flexibility request.
/// An ISP without a band is one the request says nothing about.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct DeviationEnvelope {
    bands: Series<Option<Band>>,
    provenance: Provenance,
}

/// One ISP in which an offer or order leaves a [`DeviationEnvelope`].
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Misfit {
    /// The ISP.
    pub label: IspLabel,
    /// The offered or ordered deviation.
    pub offered: Deviation,
    /// The band it leaves; `None` where the request names no band and the offer still deviates.
    pub band: Option<Band>,
    /// Who set the request.
    pub source: Provenance,
}

impl fmt::Display for Misfit {
    /// `ISP 2 (00:15–00:30 +01:00): offered -5 kW outside -30 kW to -10 kW (requested) set by
    /// dso.example request-7`.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.band {
            Some(band) => write!(
                f,
                "{}: offered {} outside {band} set by {}",
                self.label, self.offered, self.source
            ),
            None => write!(
                f,
                "{}: offered {} where {} requested nothing",
                self.label, self.offered, self.source
            ),
        }
    }
}

impl DeviationEnvelope {
    /// `bands` per ISP, set by `provenance`.
    #[must_use]
    pub fn new(bands: Series<Option<Band>>, provenance: Provenance) -> DeviationEnvelope {
        DeviationEnvelope { bands, provenance }
    }

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

    /// The band of ISP `isp`; `None` outside the grid or where the request sets none.
    #[must_use]
    pub fn band(&self, isp: u32) -> Option<Band> {
        self.bands.get(isp).copied().flatten()
    }

    /// The bands per ISP.
    #[must_use]
    pub fn bands(&self) -> &Series<Option<Band>> {
        &self.bands
    }

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

    /// Every ISP in which `offer` leaves its band, and every ISP without a band in which
    /// `offer` is not zero, in ISP order. Empty if the offer fits. `offer` may cover only some
    /// of the request's ISPs (a [`Grid::slice`] of its grid, as UFTP offers and orders do); in
    /// the ISPs it does not cover it deviates by nothing, which a Requested band may not allow.
    ///
    /// ```
    /// use flexibility::jiff::{Timestamp, tz::TimeZone};
    /// use flexibility::*;
    /// let grid = Grid::new(Timestamp::UNIX_EPOCH, IspDuration::FIFTEEN_MINUTES, 2, TimeZone::UTC)?;
    /// let need = Band::new(Deviation::from_watts(-30_000), Deviation::from_watts(-10_000), Disposition::Requested)?;
    /// let request = DeviationEnvelope::new(
    ///     Series::new(grid.clone(), vec![Some(need), None])?,
    ///     Provenance::new("dso.example", "request-7", Timestamp::UNIX_EPOCH),
    /// );
    /// let offer = Series::new(grid, vec![Deviation::from_watts(-5_000), Deviation::from_watts(0)])?;
    /// let misfits = request.check(&offer)?;
    /// assert_eq!(
    ///     misfits[0].to_string(),
    ///     "ISP 1 (00:00–00:15 +00:00): offered -5 kW outside -30 kW to -10 kW (requested) set by dso.example request-7"
    /// );
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// # Errors
    /// [`Error::GridMismatch`] if `offer` is not on the request's grid or a slice of it.
    pub fn check(&self, offer: &Series<Deviation>) -> Result<Vec<Misfit>, Error> {
        within(self.grid(), offer.grid())?;
        let none = Deviation::from_watts(0);
        Ok(self
            .bands
            .iter()
            .filter_map(|(isp, &band)| {
                let offered = offer.get(isp).copied().unwrap_or(none);
                let fits = band.map_or(offered == none, |b| b.contains(offered));
                (!fits).then(|| Misfit {
                    label: self.grid().label_total(isp),
                    offered,
                    band,
                    source: self.provenance.clone(),
                })
            })
            .collect())
    }

    /// The absolute envelope this request means once `baseline` is agreed, on the baseline's
    /// grid (the request's or a slice of it): in every ISP with a band, baseline + `min` to
    /// baseline + `max`, set by the request's provenance. ISPs without a band stay unbounded.
    ///
    /// # Errors
    /// [`Error::GridMismatch`] if `baseline` is not on the request's grid or a slice of it;
    /// [`Error::Overflow`] at the edges of the range.
    pub fn resolve(&self, baseline: &Series<Power>) -> Result<Envelope, Error> {
        within(self.grid(), baseline.grid())?;
        let bounds = baseline
            .iter()
            .map(|(isp, &b)| match self.band(isp) {
                None => Ok(Bounds::UNBOUNDED),
                Some(band) => Bounds::new(
                    Some(b.checked_add_deviation(band.min)?),
                    Some(b.checked_add_deviation(band.max)?),
                ),
            })
            .collect::<Result<Vec<_>, Error>>()?;
        Envelope::from_bounds(baseline.grid().clone(), &bounds, self.provenance.clone())
    }
}

/// `inner` is `outer` or a slice of it.
fn within(outer: &Grid, inner: &Grid) -> Result<(), Error> {
    if outer.slice(inner.numbers()).ok().as_ref() == Some(inner) {
        Ok(())
    } else {
        Err(Error::GridMismatch {
            left: outer.clone(),
            right: inner.clone(),
        })
    }
}