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
//! 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,
}

/// How an ISP of an offer or order misfits a [`DeviationEnvelope`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum MisfitKind {
    /// Offered, outside the ISP's band.
    Outside {
        /// The offered or ordered deviation.
        offered: Deviation,
        /// The band it leaves.
        band: Band,
    },
    /// Offered where the request names no band.
    Unrequested {
        /// The offered or ordered deviation.
        offered: Deviation,
    },
    /// Not offered, where the band excludes 0 W. UFTP allows it: an offer is rejected only
    /// when it names none of the Requested ISPs [UFTP 3.1 § 3.8.3, *Request mismatch*].
    NotOffered {
        /// The band left unmet.
        band: Band,
    },
}

/// One ISP in which an offer or order misfits a [`DeviationEnvelope`].
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Misfit {
    /// The ISP.
    pub label: IspLabel,
    /// How it misfits.
    pub kind: MisfitKind,
    /// 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`; `… offered 1 kW where … requested nothing`; `… not offered,
    /// outside -30 kW to -10 kW (requested) set by …`.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let (label, source) = (&self.label, &self.source);
        match self.kind {
            MisfitKind::Outside { offered, band } => {
                write!(
                    f,
                    "{label}: offered {offered} outside {band} set by {source}"
                )
            }
            MisfitKind::Unrequested { offered } => {
                write!(
                    f,
                    "{label}: offered {offered} where {source} requested nothing"
                )
            }
            MisfitKind::NotOffered { band } => {
                write!(f, "{label}: not offered, outside {band} set by {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` misfits, in ISP order; empty if it fits. `offer` is on the
    /// request's grid or a slice of it, as UFTP offers and orders are, with a deviation per ISP
    /// or `None` where it names none ([`uftp::profile`](crate::uftp) reads them so). An ISP it
    /// does not name, inside or outside its slice, deviates by nothing: a misfit only where the
    /// band excludes 0 W ([`MisfitKind::NotOffered`]).
    ///
    /// ```
    /// use flexibility::jiff::{Timestamp, tz::TimeZone};
    /// use flexibility::*;
    /// let grid = Grid::new(Timestamp::UNIX_EPOCH, IspDuration::FIFTEEN_MINUTES, 3, TimeZone::UTC)?;
    /// let need = Band::new(Deviation::from_watts(-30_000), Deviation::from_watts(-10_000), Disposition::Requested)?;
    /// let request = DeviationEnvelope::new(
    ///     Series::filled(grid.clone(), Some(need)),
    ///     Provenance::new("dso.example", "request-7", Timestamp::UNIX_EPOCH),
    /// );
    /// let kw = |k: i64| Some(Deviation::from_watts(k * 1_000));
    /// let offer = Series::new(grid, vec![kw(-5), None, kw(-20)])?;
    /// 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"
    /// );
    /// assert!(matches!(misfits[1].kind, MisfitKind::NotOffered { .. }));
    /// # 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<T>(&self, offer: &Series<T>) -> Result<Vec<Misfit>, Error>
    where
        T: Copy + Into<Option<Deviation>>,
    {
        within(self.grid(), offer.grid())?;
        let zero = Deviation::from_watts(0);
        Ok(self
            .bands
            .iter()
            .filter_map(|(isp, &band)| {
                let offered = offer.get(isp).copied().and_then(Into::into);
                let kind = match (offered, band) {
                    (Some(o), Some(b)) if !b.contains(o) => MisfitKind::Outside {
                        offered: o,
                        band: b,
                    },
                    (Some(o), None) if o != zero => MisfitKind::Unrequested { offered: o },
                    (None, Some(b)) if !b.contains(zero) => MisfitKind::NotOffered { band: b },
                    _ => return None,
                };
                Some(Misfit {
                    label: self.grid().label_total(isp),
                    kind,
                    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(),
        })
    }
}