flexibility 0.1.1

Grid flexibility as exact, replayable arithmetic: limits, baselines, UFTP-exact settlement, and UFTP, EEBUS, S2, OpenADR, IEC 104 converters.
Documentation
//! `metering`'s numbers in this crate's shapes, behind the `metering` feature: the § 14a
//! minimum as a [`Guarantee`], and quarter-hour Lastgang energy as average power per ISP, for
//! [`settle`](crate::settle).
//!
//! ```
//! use flexibility::metering::{self, wire};
//! use wire::dec;
//! use wire::grid::para14a::{Anlage, Para14aConfig, SteuVeFallgruppe, mindestleistung_direktansteuerung, steuerbare_verbrauchseinrichtungen};
//! # use flexibility::{Provenance, Window, w};
//! # use flexibility::jiff::Timestamp;
//! # let day = Window::new("2026-11-30T23:00:00Z".parse()?, "2026-12-01T23:00:00Z".parse()?)?;
//! let pump = steuerbare_verbrauchseinrichtungen(&[Anlage::new(SteuVeFallgruppe::Waermepumpe, dec!(20.001))]).unwrap();
//! let minimum = mindestleistung_direktansteuerung(&pump[0], &Para14aConfig::VERMUTUNG);
//! let rule = Provenance::new("bnetza.de", "BK6-22-300", Timestamp::UNIX_EPOCH);
//! // 0,4 × 20,001 kW = 8 000,4 W: the minimum is kept to the watt above, never below.
//! assert_eq!(metering::guarantee(minimum, day, rule)?.power(), w!(8001));
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

use crate::power::div_round;
use crate::{Error, Grid, Guarantee, Power, Provenance, Rounding, Series, Window};

/// The `metering` crate this feature maps to.
pub use ::metering as wire;

use wire::Direction;
use wire::grid::para14a::Mindestleistung;

const PROTOCOL: &str = "metering";

fn refuse(field: &'static str, value: &impl ToString, reason: &'static str) -> Error {
    Error::Unrepresentable {
        protocol: PROTOCOL,
        field,
        value: value.to_string(),
        reason,
    }
}

/// The § 14a minimum as a guarantee over `window`: its whole watts as `metering` gives them,
/// rounded **up**, since it is a power that must at least stay allowed (BK6-22-300 Anlage 1
/// Ziff. 4.5).
///
/// # Errors
/// [`Error::Unrepresentable`] if the minimum has no whole-watt value in range.
pub fn guarantee(
    minimum: Mindestleistung,
    window: Window,
    provenance: Provenance,
) -> Result<Guarantee, Error> {
    let watts = minimum.watts().ok_or_else(|| {
        refuse(
            "Mindestleistung",
            &minimum,
            "exceeds the range of whole watts",
        )
    })?;
    Guarantee::consumption(window, Power::consumption(watts)?, provenance)
}

/// Overflow while netting energy.
fn overflow(left: i128) -> Error {
    Error::Overflow {
        quantity: "energy",
        operation: "net",
        left,
        right: None,
    }
}

/// The average power per ISP of `grid` from the quarter-hour Lastgang energy of `channels`:
/// import (`1-0:1.29.0`) positive, export (`1-0:2.29.0`) negative, summed exactly and rounded
/// once per ISP as `rounding` says. Pass the import and the export of one connection point to
/// get its net power.
///
/// Every quarter of the grid must be present and billable in every channel, as `metering`
/// defines it (measured, estimated, substituted, calculated, corrected or preliminary). Filter
/// first if the contract settles only on measured values.
///
/// # Errors
/// [`Error::Mismatch`] if `grid` is not quarter hours; [`Error::Unrepresentable`] for a channel
/// that is not an active-energy Lastgang in kWh with a direction, or a quarter that is missing
/// or not billable (naming the instant); [`Error::Inexact`] under [`Rounding::Exact`] for a
/// fraction of a watt; [`Error::Overflow`] at the edges.
pub fn power(
    channels: &[&wire::Series],
    grid: &Grid,
    rounding: Rounding,
) -> Result<Series<Power>, Error> {
    if grid.isp().minutes() != 15 {
        return Err(Error::Mismatch {
            field: "ISP-Duration",
            ours: format!("{} min", grid.isp().minutes()),
            theirs: "15 min (Lastgang quarters)".into(),
        });
    }
    if channels.is_empty() {
        return Err(Error::NoData {
            what: "no metering channel",
        });
    }
    let n = grid.count() as usize;
    // Per ISP: Σ ±kWh as num / 10^scale, at the largest scale seen so far.
    let mut sums: Vec<(i128, u32)> = vec![(0, 0); n];
    for series in channels {
        let channel = series.channel();
        let sign = match series.lastgang_direction() {
            Some(Direction::Import) => 1,
            Some(Direction::Export) => -1,
            _ => {
                return Err(refuse(
                    "channel",
                    &channel.map_or_else(|| "none".to_owned(), |c| c.to_string()),
                    "is not an active-energy Lastgang in kWh (1-0:1.29.0 import, 1-0:2.29.0 export)",
                ));
            }
        };
        let quarters = series
            .billable_quarters((grid.start(), grid.end()))
            .map_err(|e| refuse("interval", &e, "cannot be settled"))?;
        for (sum, iv) in sums.iter_mut().zip(quarters) {
            let v = iv.value();
            let (num, scale) = (sign * v.mantissa(), v.scale());
            let top = sum.1.max(scale);
            let lift = |x: i128, from: u32| {
                10_i128
                    .checked_pow(top - from)
                    .and_then(|f| x.checked_mul(f))
                    .ok_or_else(|| overflow(x))
            };
            let total = lift(sum.0, sum.1)?
                .checked_add(lift(num, scale)?)
                .ok_or_else(|| overflow(sum.0))?;
            *sum = (total, top);
        }
    }
    // kWh over 15 minutes → W: × 3 600 000 Ws/kWh ÷ 900 s = × 4 000.
    let values = sums
        .into_iter()
        .map(|(num, scale)| {
            let n = num.checked_mul(4_000).ok_or_else(|| overflow(num))?;
            let d = 10_i128.checked_pow(scale).ok_or_else(|| overflow(num))?;
            let w = div_round(n, d, rounding)?;
            i64::try_from(w)
                .map(Power::from_watts)
                .map_err(|_| overflow(w))
        })
        .collect::<Result<Vec<_>, Error>>()?;
    Series::new(grid.clone(), values)
}