flexibility 0.1.2

Grid flexibility as exact, replayable arithmetic: limits, baselines, UFTP-exact settlement, and UFTP, EEBUS, S2, OpenADR, CSIP-AUS, IEC 104, CLS.EEDI converters.
Documentation
//! How well a baseline method predicts what a site actually did, scored exactly.
//!
//! Score a method on **non-event** days: compute the baseline as if an event had happened and
//! compare it with the measurement. The network code asks for methods that are *"precise,
//! accurate and unbiased"*; this module measures that and decides nothing. Accepting a method is
//! the grid operator's decision.
//!
//! With error *e* = baseline − actual per ISP over *n* ISPs:
//!
//! | Metric | Definition |
//! |---|---|
//! | bias | round(Σ*e* / *n*), half away from zero |
//! | RMSE | ⌊√(⌊Σ*e*² / *n*⌋)⌋, an integer square root |
//! | RRMSE | round(RMSE · 10 000 · *n* / Σ actual) in basis points, when Σ actual > 0 |
//!
//! ```
//! use flexibility::jiff::{Timestamp, tz::TimeZone};
//! use flexibility::{accuracy, kw, Grid, IspDuration, Series};
//! let grid = Grid::new(Timestamp::UNIX_EPOCH, IspDuration::FIFTEEN_MINUTES, 3, TimeZone::UTC)?;
//! let baseline = Series::filled(grid.clone(), kw!(10));
//! let actual = Series::new(grid, vec![kw!(9), kw!(10), kw!(11)])?;
//! let score = accuracy::score([(&baseline, &actual)])?;
//! assert_eq!(score.bias.watts(), 0);
//! assert_eq!(score.rmse.watts(), 816); // ⌊√(2/3) kW⌋
//! assert_eq!(score.rrmse_basis_points, Some(816));
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

use crate::power::div_round;
use crate::{Deviation, Error, Power, Rounding, Series};

/// The accuracy of a set of baselines against their actuals.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Accuracy {
    /// The ISPs scored.
    pub count: u64,
    /// The mean error, baseline − actual: positive means the method over-estimates.
    pub bias: Deviation,
    /// The root mean square error, floored to the watt.
    pub rmse: Power,
    /// RMSE relative to the mean actual, in basis points; `None` if the mean actual is not
    /// positive.
    pub rrmse_basis_points: Option<u64>,
}

/// Scores `(baseline, actual)` pairs, each pair on one grid.
///
/// # Errors
/// [`Error::NoData`] without any ISP; [`Error::GridMismatch`] for a pair on two grids;
/// [`Error::Overflow`] if a sum leaves the range (far beyond any real data).
pub fn score<'a>(
    pairs: impl IntoIterator<Item = (&'a Series<Power>, &'a Series<Power>)>,
) -> Result<Accuracy, Error> {
    let (mut n, mut sum_e, mut sum_e2, mut sum_a) = (0u64, 0i128, 0u128, 0i128);
    for (baseline, actual) in pairs {
        baseline.same_grid(actual.grid())?;
        for (b, a) in baseline.values().iter().zip(actual.values()) {
            let e = i128::from(b.watts()) - i128::from(a.watts());
            n += 1;
            sum_e += e;
            sum_e2 = sum_e2
                .checked_add(e.unsigned_abs().pow(2))
                .ok_or_else(|| overflow(sum_e2))?;
            sum_a += i128::from(a.watts());
        }
    }
    if n == 0 {
        return Err(Error::NoData {
            what: "no ISPs to score",
        });
    }
    let bias = div_round(sum_e, i128::from(n), Rounding::HalfAwayFromZero)?;
    let rmse = (sum_e2 / u128::from(n)).isqrt();
    let rmse_w = i64::try_from(rmse).map_err(|_| overflow(rmse))?;
    let relative = if sum_a > 0 {
        let num = i128::try_from(rmse).map_err(|_| overflow(rmse))? * 10_000 * i128::from(n);
        let bp = div_round(num, sum_a, Rounding::HalfAwayFromZero)?;
        u64::try_from(bp).ok()
    } else {
        None
    };
    Ok(Accuracy {
        count: n,
        bias: Deviation::from_watts(
            i64::try_from(bias).map_err(|_| overflow(bias.unsigned_abs()))?,
        ),
        rmse: Power::from_watts(rmse_w),
        rrmse_basis_points: relative,
    })
}

fn overflow(value: u128) -> Error {
    Error::Overflow {
        quantity: "accuracy",
        operation: "sum",
        left: i128::try_from(value).unwrap_or(i128::MAX),
        right: None,
    }
}