flexibility 0.1.0

Grid flexibility as exact, replayable arithmetic: limits, baselines, UFTP-exact settlement, and UFTP, EEBUS, S2, OpenADR, IEC 104 converters.
Documentation
//! S2 (EN 50491-12-2) power envelopes and power sequences, behind the `s2` feature.
//!
//! - **PEBC**: an [`Instruction`]'s power envelope is a list of [`Limit`]s ([`limits`]), and an
//!   [`Envelope`] is a power envelope to instruct ([`power_envelope`]). What both can carry
//!   round-trips.
//! - **PPBC**: a [`PowerSequence`], placed at a start, is a [`Schedule`] ([`schedule`]). A
//!   container's sequences are alternatives: convert each, check each.
//!
//! S2 power is watts, *"consumption is positive and production negative, always as seen at the
//! grid"* (`s2-kit`'s `PowerRange`): this crate's sign, so nothing is negated. Each function
//! reads the commodity quantity you name; `ELECTRIC.POWER.3_PHASE_SYMMETRIC` is the total over
//! three phases (S2 erratum E32). [`schedule`] also reads [`Read::ElectricTotal`]: the symmetric
//! total, or L1 to L3 summed exactly.
//!
//! S2 numbers are JSON numbers held as `f64`. `s2-kit` guarantees that a decimal of at most 15
//! significant digits comes back equal to what the peer wrote, so each value is read through
//! its shortest decimal: exact, and refused only for what the sender wrote. A limit must be
//! whole watts; a sequence's power may be rounded, if you name the rounding.
//!
//! ```
//! use flexibility::s2::{self, wire};
//! use flexibility::{Envelope, Grid, IspDuration, Provenance, kw};
//! use wire::types::{CommodityQuantity, Duration, Id, pebc};
//! # use flexibility::jiff::tz::TimeZone;
//! # let start: flexibility::jiff::Timestamp = "2026-12-01T11:00:00Z".parse()?;
//! # let grid = Grid::new(start, IspDuration::FIFTEEN_MINUTES, 4, TimeZone::UTC)?;
//! let curtail = pebc::Instruction {
//!     message_id: Id::new_const("m-1"),
//!     id: Id::new_const("i-1"),
//!     execution_time: start.into(),
//!     abnormal_condition: false,
//!     power_constraints_id: Id::new_const("pc-1"),
//!     power_envelopes: vec![pebc::PowerEnvelope {
//!         id: Id::new_const("pe-1"),
//!         commodity_quantity: CommodityQuantity::ElectricPower3PhaseSymmetric,
//!         // A 10 kWp array: feed in at most 4 kW for half an hour, then 10 kW.
//!         power_envelope_elements: vec![
//!             pebc::PowerEnvelopeElement::new(Duration::from_secs(1_800), -4_000.0, 0.0),
//!             pebc::PowerEnvelopeElement::new(Duration::from_secs(1_800), -10_000.0, 0.0),
//!         ],
//!     }],
//! };
//! let cem = Provenance::new("ems.example", "i-1", start);
//! let limits = s2::limits(&curtail, CommodityQuantity::ElectricPower3PhaseSymmetric, &cem)?;
//! let envelope = limits.iter().try_fold(Envelope::unbounded(grid), |e, l| e.apply(l))?;
//! assert_eq!(envelope.bounds(1).unwrap().min(), Some(kw!(-4)));
//! assert_eq!(envelope.bounds(3).unwrap().min(), Some(kw!(-10)));
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

use jiff::Timestamp;

use crate::power::div_round;
use crate::{
    Bounds, Envelope, Error, Grid, Limit, Power, Provenance, Rounding, Schedule, Series, Window,
};

/// The `s2-kit` crate this feature maps to.
pub use ::s2_kit as wire;

use wire::types::pebc::{Instruction, PowerEnvelope, PowerEnvelopeElement};
use wire::types::ppbc::PowerSequence;
use wire::types::{CommodityQuantity, Id, PowerForecastValue};

const PROTOCOL: &str = "S2";

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

// --- The one float crossing (converter rule 3) -----------------------------------------------

/// The exact decimal an S2 number denotes, as `(mantissa, scale)`: read from the `f64`'s
/// shortest round-trip text, which `s2-kit` guarantees is what the peer wrote (up to 15
/// significant digits). Rust prints an `f64` without an exponent.
#[allow(clippy::disallowed_types)]
fn decimal(field: &'static str, value: f64) -> Result<(i128, u32), Error> {
    if !value.is_finite() {
        return Err(refuse(field, &value, "is not a finite number"));
    }
    let text = format!("{value}");
    let (whole, fraction) = text.split_once('.').unwrap_or((&text, ""));
    // A whole part beyond 2^53 is beyond what S2 carries exactly, and beyond any real power.
    if whole.trim_start_matches('-').len() > 16 {
        return Err(refuse(
            field,
            &format!("{value:e}"),
            "is outside the range of watts",
        ));
    }
    // An f64's shortest decimal has at most 17 significant digits; leading zeros of a tiny
    // value are dropped, and its scale is kept.
    let digits = format!("{whole}{fraction}");
    let mantissa: i128 = digits
        .parse()
        .map_err(|_| refuse(field, &format!("{value:e}"), "is not a decimal number"))?;
    let scale = u32::try_from(fraction.len())
        .map_err(|_| refuse(field, &format!("{value:e}"), "is not a decimal number"))?;
    Ok((mantissa, scale))
}

/// Whole watts as an S2 number: exact for every `|w| ≤ 2^53`, refused beyond.
#[allow(clippy::disallowed_types, clippy::cast_precision_loss)]
fn number(field: &'static str, power: Power) -> Result<f64, Error> {
    let w = power.watts();
    if i128::from(w).unsigned_abs() > crate::MAX_EXACT.unsigned_abs() {
        return Err(refuse(
            field,
            &power,
            "is beyond ±2^53 W, where an S2 number is exact",
        ));
    }
    Ok(w as f64)
}

// ---------------------------------------------------------------------------------------------

/// An S2 number as power, rounded as named; [`Rounding::Exact`] refuses a fraction of a watt.
#[allow(clippy::disallowed_types)]
fn watts(field: &'static str, value: f64, rounding: Rounding) -> Result<Power, Error> {
    let (mantissa, scale) = decimal(field, value)?;
    rounded(field, mantissa, scale, rounding, &|| value.to_string())
}

/// `mantissa · 10^-scale` W, rounded as named.
fn rounded(
    field: &'static str,
    mantissa: i128,
    scale: u32,
    rounding: Rounding,
    shown: &dyn Fn() -> String,
) -> Result<Power, Error> {
    let Some(divisor) = 10_i128.checked_pow(scale) else {
        // Beyond 10^38 the value is below 10^-21 W: no whole watt, and it rounds to zero.
        return match rounding {
            Rounding::Exact if mantissa != 0 => {
                Err(refuse(field, &shown(), "is not a whole number of watts"))
            }
            _ => Ok(Power::ZERO),
        };
    };
    let w = match rounding {
        Rounding::Exact if mantissa % divisor != 0 => {
            return Err(refuse(field, &shown(), "is not a whole number of watts"));
        }
        _ => div_round(mantissa, divisor, rounding)?,
    };
    i64::try_from(w)
        .map(Power::from_watts)
        .map_err(|_| refuse(field, &shown(), "is outside the range of watts"))
}

/// Which power of an S2 element to read.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Read {
    /// One commodity quantity, as written.
    Quantity(CommodityQuantity),
    /// The electric power over all phases: `ELECTRIC.POWER.3_PHASE_SYMMETRIC` alone (the total,
    /// S2 erratum E32), or L1, L2 and L3 summed. A set that mixes both or repeats a quantity is
    /// refused: the standard does not say which wins.
    ElectricTotal,
}

impl From<CommodityQuantity> for Read {
    fn from(q: CommodityQuantity) -> Read {
        Read::Quantity(q)
    }
}

/// The expected power `read` selects from an element's values. The phases are summed as exact
/// decimals, then rounded once (`s2-kit`'s `electric_total` adds `f64`s).
#[allow(clippy::disallowed_types)]
fn expected(values: &[PowerForecastValue], read: Read, rounding: Rounding) -> Result<Power, Error> {
    match read {
        Read::Quantity(q) => {
            let v = values
                .iter()
                .find(|v| v.commodity_quantity == q)
                .ok_or_else(|| {
                    refuse("power_values", &q.as_str(), "has no value in the element")
                })?;
            watts("value_expected", v.value_expected, rounding)
        }
        Read::ElectricTotal => {
            // s2-kit's rules for what makes one electric total; its sum is f64, so the parts
            // are added here, exactly.
            let pairs = values
                .iter()
                .map(|v| (v.commodity_quantity, v.value_expected));
            let parts: Vec<f64> = match wire::types::phases(pairs) {
                Some(wire::types::Phases::Symmetric(total)) => vec![total],
                Some(wire::types::Phases::PerPhase { l1, l2, l3 }) => {
                    [l1, l2, l3].into_iter().flatten().collect()
                }
                None => {
                    let quantities: Vec<&str> = values
                        .iter()
                        .map(|v| v.commodity_quantity.as_str())
                        .collect();
                    return Err(refuse(
                        "power_values",
                        &quantities.join(", "),
                        "is not one electric total: the symmetric total alone, or L1 to L3 once each",
                    ));
                }
            };
            let quantities = "the electric phases";
            // Σ mantissa · 10^-scale at the largest scale, exactly.
            let parts = parts
                .into_iter()
                .map(|v| decimal("value_expected", v))
                .collect::<Result<Vec<_>, Error>>()?;
            let scale = parts.iter().map(|&(_, s)| s).max().unwrap_or(0);
            let too_long = || {
                refuse(
                    "value_expected",
                    &quantities,
                    "has more digits than this crate reads",
                )
            };
            let sum = parts.iter().try_fold(0_i128, |acc, &(m, s)| {
                10_i128
                    .checked_pow(scale - s)
                    .and_then(|f| m.checked_mul(f))
                    .and_then(|x| acc.checked_add(x))
                    .ok_or_else(too_long)
            })?;
            rounded("value_expected", sum, scale, rounding, &|| {
                format!("{sum}e-{scale}")
            })
        }
    }
}

fn instant(field: &'static str, t: wire::Timestamp) -> Result<Timestamp, Error> {
    Timestamp::try_from(t).map_err(|_| refuse(field, &t, "is outside the representable time range"))
}

/// The limits an instruction's power envelope for `quantity` sets: one per element, from the
/// instruction's execution time, each element after the one before. Both bounds are the
/// element's, as written.
///
/// # Errors
/// [`Error::NoData`] if the instruction has no envelope for `quantity`;
/// [`Error::Unrepresentable`] for a bound that is not whole watts or a time out of range;
/// [`Error::InvertedBounds`] for a lower limit above the upper; [`Error::EmptyWindow`] for an
/// element of zero duration.
pub fn limits(
    instruction: &Instruction,
    quantity: CommodityQuantity,
    provenance: &Provenance,
) -> Result<Vec<Limit>, Error> {
    let envelope = instruction.envelope_for(quantity).ok_or(Error::NoData {
        what: "no S2 power envelope for the quantity",
    })?;
    let mut out = Vec::with_capacity(envelope.power_envelope_elements.len());
    for step in envelope.steps(instruction.execution_time) {
        let step = step.map_err(|_| {
            refuse(
                "duration",
                &instruction.execution_time,
                "ends outside the representable time range",
            )
        })?;
        let (from, until, element) = (
            instant("execution_time", step.start)?,
            instant("duration", step.end)?,
            step.element,
        );
        let bounds = Bounds::new(
            Some(watts("lower_limit", element.lower_limit, Rounding::Exact)?),
            Some(watts("upper_limit", element.upper_limit, Rounding::Exact)?),
        )?;
        out.push(Limit::new(
            Window::new(from, until)?,
            bounds,
            provenance.clone(),
        ));
    }
    Ok(out)
}

/// The power envelope for `quantity` that carries `envelope`: one element per run of ISPs with
/// equal bounds, from the envelope's start. Put it in an [`Instruction`] with
/// `execution_time` = the envelope grid's start.
///
/// # Errors
/// [`Error::Unrepresentable`] for an ISP without both bounds (an S2 element bounds both sides)
/// or a bound beyond ±2^53 W.
pub fn power_envelope(
    envelope: &Envelope,
    id: Id,
    quantity: CommodityQuantity,
) -> Result<PowerEnvelope, Error> {
    let grid = envelope.grid();
    let isp_ms = u64::from(grid.isp().minutes()) * 60_000;
    let mut runs: Vec<(Power, Power, u64)> = Vec::new();
    for isp in grid.numbers() {
        let b = envelope.bounds(isp).unwrap_or(Bounds::UNBOUNDED);
        let (Some(min), Some(max)) = (b.min(), b.max()) else {
            let label = grid
                .label(isp)
                .map_or_else(|| isp.to_string(), |l| l.to_string());
            return Err(refuse(
                "power_envelope_elements",
                &label,
                "has an open side; an S2 power envelope bounds both",
            ));
        };
        match runs.last_mut() {
            Some((lo, hi, ms)) if *lo == min && *hi == max => *ms += isp_ms,
            _ => runs.push((min, max, isp_ms)),
        }
    }
    let power_envelope_elements = runs
        .into_iter()
        .map(|(lo, hi, ms)| {
            Ok(PowerEnvelopeElement::new(
                wire::Duration::from_millis(ms),
                number("lower_limit", lo)?,
                number("upper_limit", hi)?,
            ))
        })
        .collect::<Result<_, Error>>()?;
    Ok(PowerEnvelope {
        id,
        commodity_quantity: quantity,
        power_envelope_elements,
    })
}

/// A power sequence started at `start`, as a schedule on the ISPs of `grid` it covers: each
/// element's expected power as `read` selects it (a quantity, or [`Read::ElectricTotal`]),
/// rounded as named. Every element must start and end on an ISP boundary of `grid`; an element
/// may span several ISPs.
///
/// # Errors
/// [`Error::Unrepresentable`] for an element that ends between ISP boundaries or outside
/// `grid`, or that has no value to read, a fraction of a watt under
/// [`Rounding::Exact`], or a time out of range; [`Error::NoData`] for an empty sequence.
pub fn schedule(
    sequence: &PowerSequence,
    read: impl Into<Read>,
    start: Timestamp,
    grid: &Grid,
    rounding: Rounding,
    provenance: Provenance,
) -> Result<Schedule, Error> {
    let read = read.into();
    let mut first = None;
    let mut values = Vec::new();
    for step in sequence.steps(start.into()) {
        let step = step.map_err(|_| {
            refuse(
                "duration",
                &start,
                "ends outside the representable time range",
            )
        })?;
        let (from, until, element) = (
            instant("start", step.start)?,
            instant("duration", step.end)?,
            step.element,
        );
        let window = Window::new(from, until)?;
        let isps = grid
            .isps(window)
            .filter(|r| {
                grid.interval(*r.start()).map(Window::from) == Some(from)
                    && grid.interval(*r.end()).map(Window::until) == Some(until)
            })
            .ok_or_else(|| {
                refuse(
                    "duration",
                    &window,
                    "does not start and end on ISP boundaries of the grid",
                )
            })?;
        let power = expected(&element.power_values, read, rounding)?;
        first.get_or_insert(*isps.start());
        values.extend(isps.map(|_| power));
    }
    let first = first.ok_or(Error::NoData {
        what: "an S2 power sequence without elements",
    })?;
    let last = first + u32::try_from(values.len()).unwrap_or(u32::MAX) - 1;
    Ok(Schedule::new(
        Series::new(grid.slice(first..=last)?, values)?,
        provenance,
    ))
}