flexibility 0.1.1

Grid flexibility as exact, replayable arithmetic: limits, baselines, UFTP-exact settlement, and UFTP, EEBUS, S2, OpenADR, IEC 104 converters.
Documentation
//! One value per ISP of a grid.

use std::ops::RangeInclusive;

use crate::{Energy, Error, Grid, Power, Window};

/// Exactly one value per ISP of its grid.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Series<T> {
    grid: Grid,
    values: Vec<T>,
}

impl<T> Series<T> {
    /// A series of `values`, the first for ISP 1.
    ///
    /// # Errors
    /// [`Error::SeriesLength`] unless there is exactly one value per ISP.
    pub fn new(grid: Grid, values: Vec<T>) -> Result<Series<T>, Error> {
        if values.len() != grid.count() as usize {
            return Err(Error::SeriesLength {
                expected: grid.count(),
                actual: values.len(),
            });
        }
        Ok(Series { grid, values })
    }

    /// The same `value` in every ISP.
    #[must_use]
    pub fn filled(grid: Grid, value: T) -> Series<T>
    where
        T: Clone,
    {
        let values = vec![value; grid.count() as usize];
        Series { grid, values }
    }

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

    /// The values, the first for ISP 1.
    #[must_use]
    pub fn values(&self) -> &[T] {
        &self.values
    }

    /// The value of ISP `isp`, or `None` if it is not on the grid.
    #[must_use]
    pub fn get(&self, isp: u32) -> Option<&T> {
        let index = usize::try_from(self.grid.index(isp)?).ok()?;
        self.values.get(index)
    }

    /// `(ISP number, value)` pairs in order.
    pub fn iter(&self) -> impl Iterator<Item = (u32, &T)> {
        self.grid.numbers().zip(self.values.iter())
    }

    /// `f` applied to every value, on the same grid.
    #[must_use]
    pub fn map<U>(&self, f: impl FnMut(&T) -> U) -> Series<U> {
        Series {
            grid: self.grid.clone(),
            values: self.values.iter().map(f).collect(),
        }
    }

    /// `f` applied to every value, stopping at the first error.
    ///
    /// # Errors
    /// The first error `f` returns.
    pub fn try_map<U, E>(&self, f: impl FnMut(&T) -> Result<U, E>) -> Result<Series<U>, E> {
        Ok(Series {
            grid: self.grid.clone(),
            values: self.values.iter().map(f).collect::<Result<_, _>>()?,
        })
    }

    /// `f` applied ISP by ISP to `self` and `other`.
    ///
    /// # Errors
    /// [`Error::GridMismatch`] if `other` is on another grid.
    pub fn zip_with<U, V>(
        &self,
        other: &Series<U>,
        mut f: impl FnMut(&T, &U) -> V,
    ) -> Result<Series<V>, Error> {
        self.same_grid(other.grid())?;
        Ok(Series {
            grid: self.grid.clone(),
            values: self
                .values
                .iter()
                .zip(&other.values)
                .map(|(a, b)| f(a, b))
                .collect(),
        })
    }

    /// The values of ISPs `isps`, on the sliced grid ([`Grid::slice`]).
    ///
    /// # Errors
    /// [`Error::IspRange`] outside the grid.
    pub fn slice(&self, isps: RangeInclusive<u32>) -> Result<Series<T>, Error>
    where
        T: Clone,
    {
        let grid = self.grid.slice(isps.clone())?;
        // `slice` checked that both ends are on the grid.
        let from = self.grid.index(*isps.start()).unwrap_or(0) as usize;
        let values = self.values[from..from + grid.count() as usize].to_vec();
        Ok(Series { grid, values })
    }

    /// The values of the ISPs `window` overlaps, even partly: a day's measurement cut to an
    /// event.
    ///
    /// # Errors
    /// [`Error::NoData`] if the window overlaps no ISP.
    pub fn over(&self, window: Window) -> Result<Series<T>, Error>
    where
        T: Clone,
    {
        let isps = self.grid.isps(window).ok_or(Error::NoData {
            what: "the window overlaps no ISP of the series",
        })?;
        self.slice(isps)
    }

    /// Fails unless `other` is on the same grid.
    pub(crate) fn same_grid(&self, other: &Grid) -> Result<(), Error> {
        if &self.grid == other {
            Ok(())
        } else {
            Err(Error::GridMismatch {
                left: self.grid.clone(),
                right: other.clone(),
            })
        }
    }
}

impl Series<Power> {
    /// The energy of the whole series, exact: Σ power × ISP duration.
    ///
    /// # Errors
    /// [`Error::Overflow`] if the sum leaves the range of [`Energy`].
    pub fn energy(&self) -> Result<Energy, Error> {
        let seconds = i128::from(self.grid.isp().minutes()) * 60;
        // At most MAX_ISPS values of at most 2^63 W × 86 400 s: far inside i128.
        let sum: i128 = self
            .values
            .iter()
            .map(|p| i128::from(p.watts()) * seconds)
            .sum();
        Energy::from_sum(sum)
    }
}