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
//! Pools of devices: what a pool can offer, and whether a given split of a pool plan works.
//!
//! **Check, never solve.** [`aggregate`] sums the devices' envelopes; for devices with power
//! bounds only that sum is exact, and for storage it is an outer approximation: a pool plan
//! inside it may have no split the devices can follow. [`Aggregate`] says which. Choosing a
//! split is the caller's; [`check_split`] verifies one.
//!
//! For storage, [`EnergyEnvelope::steady_headroom`] gives each device's range for one constant
//! deviation over a window, power and stored energy both. Any pool deviation up to their sum,
//! split in proportion to them, keeps every device inside its envelope.
//!
//! ```
//! use flexibility::jiff::{Timestamp, tz::TimeZone};
//! use flexibility::pool::{self, Aggregate};
//! use flexibility::*;
//! let grid = Grid::new(Timestamp::UNIX_EPOCH, IspDuration::FIFTEEN_MINUTES, 4, TimeZone::UTC)?;
//! let all = Window::new(grid.start(), grid.end())?;
//! let who = Provenance::new("agr.example", "pool-1", grid.start());
//! let charger = Envelope::unbounded(grid.clone()).apply(&Limit::band(all, kw!(0), kw!(11), who.clone())?)?;
//! let car = EnergyEnvelope::new(charger.clone(), kwh!(0)).level_at(grid.end(), Level::at_least(kwh!(5)), who.clone())?;
//! let heater = EnergyEnvelope::new(charger, kwh!(0));
//!
//! match pool::aggregate(&[car, heater], who)? {
//!     Aggregate::Outer(env) => assert_eq!(env.power().bounds(1).and_then(|b| b.max()), Some(kw!(22))),
//!     Aggregate::Exact(_) => unreachable!("the car has a level bound"),
//! }
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

use std::fmt;

use crate::storage::{LevelSlot, overflow};
use crate::{
    Bounds, EnergyEnvelope, Envelope, Error, IspLabel, Power, Provenance, Report, Schedule,
};

/// The envelope of a pool, and whether it is exact.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Aggregate {
    /// Every pool plan inside it has a split the devices can follow, for the envelopes as given:
    /// no device has a level bound, and per-ISP sums of boxes are exact. One such split moves
    /// every device by the same fraction of its power headroom.
    ///
    /// Stored energy is checked only as level bounds. A battery given without them aggregates
    /// as `Exact`, and a split can still run it empty; give its limits with
    /// [`EnergyEnvelope::level_always`] and the aggregate is [`Aggregate::Outer`].
    Exact(EnergyEnvelope),
    /// An outer approximation: every plan the devices can follow together is inside it, but a
    /// plan inside it may have no valid split. Check a split with [`check_split`] before
    /// offering it.
    Outer(EnergyEnvelope),
}

impl Aggregate {
    /// The pool's envelope, exact or not.
    #[must_use]
    pub fn envelope(&self) -> &EnergyEnvelope {
        match self {
            Aggregate::Exact(e) | Aggregate::Outer(e) => e,
        }
    }

    /// Whether the envelope is exact.
    #[must_use]
    pub fn is_exact(&self) -> bool {
        matches!(self, Aggregate::Exact(_))
    }
}

fn sum_power(values: impl Iterator<Item = Option<Power>>) -> Result<Option<Power>, Error> {
    let mut total = Power::ZERO;
    for v in values {
        let Some(v) = v else { return Ok(None) };
        total = total.checked_add(v)?;
    }
    Ok(Some(total))
}

fn sum_energy(
    values: impl Iterator<Item = Option<crate::Energy>>,
) -> Result<Option<crate::Energy>, Error> {
    let mut total = crate::Energy::ZERO;
    for v in values {
        let Some(v) = v else { return Ok(None) };
        total = total.checked_add(v)?;
    }
    Ok(Some(total))
}

/// The envelope of a pool of `devices` on one grid, set by `provenance`: per ISP the sum of the
/// devices' power bounds, the sum of their initial levels, and per boundary the sum of their
/// level bounds. A side that any device leaves unbounded is unbounded for the pool. Guarantees
/// are not carried over: a sum of guarantees guarantees no device anything.
///
/// # Errors
/// [`Error::NoData`] for no devices; [`Error::GridMismatch`] for devices on different grids;
/// [`Error::Overflow`] at the edges of the range.
pub fn aggregate(devices: &[EnergyEnvelope], provenance: Provenance) -> Result<Aggregate, Error> {
    let first = devices.first().ok_or(Error::NoData {
        what: "a pool needs at least one device",
    })?;
    let grid = first.grid();
    for d in devices {
        if d.grid() != grid {
            return Err(Error::GridMismatch {
                left: grid.clone(),
                right: d.grid().clone(),
            });
        }
    }
    let bounds = grid
        .numbers()
        .map(|isp| {
            let side = |pick: fn(Bounds) -> Option<Power>| {
                sum_power(devices.iter().map(|d| d.power().bounds(isp).and_then(pick)))
            };
            Bounds::new(side(Bounds::min)?, side(Bounds::max)?)
        })
        .collect::<Result<Vec<_>, Error>>()?;
    let initial =
        sum_energy(devices.iter().map(|d| Some(d.initial())))?.unwrap_or(crate::Energy::ZERO);
    let levels = (0..grid.count() as usize)
        .map(|i| {
            let side = |pick: fn(&LevelSlot) -> Option<crate::Energy>| {
                sum_energy(devices.iter().map(|d| d.slots().get(i).and_then(pick)))
                    .map(|e| e.map(|e| (e, 0)))
            };
            Ok(LevelSlot {
                min: side(|s| s.min.map(|(e, _)| e))?,
                max: side(|s| s.max.map(|(e, _)| e))?,
            })
        })
        .collect::<Result<Vec<_>, Error>>()?;
    let power = Envelope::from_bounds(grid.clone(), &bounds, provenance.clone())?;
    let exact = devices.iter().all(|d| !d.has_levels());
    let pool = EnergyEnvelope::from_parts(power, initial, levels, vec![provenance]);
    Ok(if exact {
        Aggregate::Exact(pool)
    } else {
        Aggregate::Outer(pool)
    })
}

/// One ISP in which the device plans do not add up to the pool plan.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct SumMismatch {
    /// The ISP.
    pub label: IspLabel,
    /// The pool plan's power.
    pub pool: Power,
    /// The sum of the device plans.
    pub devices: Power,
}

impl fmt::Display for SumMismatch {
    /// `ISP 3 (00:30–00:45 +00:00): pool plans 10 kW, devices sum to 9.999 kW`.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}: pool plans {}, devices sum to {}",
            self.label, self.pool, self.devices
        )
    }
}

/// Everything wrong with a split: ISPs that do not add up, and devices whose plans misfit.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
pub struct SplitReport {
    /// Every ISP whose device plans do not sum to the pool plan, in ISP order.
    pub sums: Vec<SumMismatch>,
    /// The report of every device whose plan misfits, by its index in the split.
    pub devices: Vec<(usize, Report)>,
}

impl SplitReport {
    /// Whether the split works: every ISP adds up and every device plan fits.
    #[must_use]
    pub fn fits(&self) -> bool {
        self.sums.is_empty() && self.devices.is_empty()
    }
}

/// Checks a given split of `pool` across `devices` (each an envelope and its plan): the device
/// plans must sum to the pool plan in every ISP, and each must fit its own envelope.
///
/// # Errors
/// [`Error::GridMismatch`] for a plan or envelope on another grid; [`Error::Overflow`] at the
/// edges of the range.
pub fn check_split(
    pool: &Schedule,
    devices: &[(&EnergyEnvelope, &Schedule)],
) -> Result<SplitReport, Error> {
    let grid = pool.series().grid();
    let mut report = SplitReport::default();
    for (i, (envelope, plan)) in devices.iter().enumerate() {
        if plan.series().grid() != grid {
            return Err(Error::GridMismatch {
                left: grid.clone(),
                right: plan.series().grid().clone(),
            });
        }
        let r = envelope.check(plan)?;
        if !r.fits() {
            report.devices.push((i, r));
        }
    }
    for (k, (isp, &planned)) in pool.series().iter().enumerate() {
        let sum: i128 = devices
            .iter()
            .filter_map(|(_, p)| p.series().values().get(k))
            .map(|p| i128::from(p.watts()))
            .sum();
        if sum != i128::from(planned.watts()) {
            report.sums.push(SumMismatch {
                label: grid.label_total(isp),
                pool: planned,
                devices: Power::from_watts(i64::try_from(sum).map_err(|_| overflow(sum))?),
            });
        }
    }
    Ok(report)
}