flexibility 0.1.1

Grid flexibility as exact, replayable arithmetic: limits, baselines, UFTP-exact settlement, and UFTP, EEBUS, S2, OpenADR, IEC 104 converters.
Documentation
//! OpenADR 3 capacity limits and usage reports, behind the `openadr` feature.
//!
//! - [`limits`]: an event's `IMPORT_CAPACITY_LIMIT` and `EXPORT_CAPACITY_LIMIT` intervals as
//!   [`Limit`]s, a consumption cap and a feed-in cap, each over its interval's own window.
//!   Apply them to an [`Envelope`](crate::Envelope): an interval that covers part of an ISP
//!   constrains the whole ISP, the strict reading.
//! - [`usage`]: a report resource's `USAGE` readings (energy per interval) as average power
//!   per ISP.
//!
//! The `openadr` crate's `IntervalExpander` places the intervals in time: inherited periods,
//! subdivided payloads, an event's `duration` looping and truncating. A value's unit comes
//! from the event's payload descriptor, or its programme's (User Guide ยง7.6), and is required:
//! *"meaning is indicated by units in associated eventPayloadDescriptor"* (the payload
//! definitions), so there is no default, and this crate does not guess. Limits are `KW`, usage
//! `KWH`; both are exact decimals, so a limit must be whole watts, and usage is rounded only as
//! named.
//!
//! ```
//! use flexibility::openadr::{self, wire};
//! use flexibility::{Envelope, Grid, IspDuration, Provenance, Window, kw};
//! use wire::model::{EventPayloadDescriptor, EventRequest, Interval, IntervalPeriod, ObjectId, StartTime, Unit, ValuesMap};
//! # use flexibility::jiff::{Timestamp, tz::TimeZone};
//! # let start: Timestamp = "2026-12-01T16:00:00Z".parse()?;
//! # let grid = Grid::new(start, IspDuration::FIFTEEN_MINUTES, 8, TimeZone::UTC)?;
//! let cap = |kw: i64| ValuesMap::single("IMPORT_CAPACITY_LIMIT".parse().unwrap(), kw);
//! let event = EventRequest::new(ObjectId::new("depot-caps")?)
//!     .with_interval_period(IntervalPeriod::new(StartTime::At("2026-12-01T16:00:00Z".parse()?), "PT1H".parse()?))
//!     .with_intervals(vec![Interval::new(0, vec![cap(250)]), Interval::new(1, vec![cap(400)])]);
//! // The unit is the descriptor's, and required: KW.
//! let mut event = event;
//! event.payload_descriptors = Some(vec![
//!     EventPayloadDescriptor::new("IMPORT_CAPACITY_LIMIT".parse()?).with_units(Unit::Kw),
//! ]);
//!
//! let dso = Provenance::new("vtn.example", "depot-caps", start);
//! let day = Window::new(grid.start(), grid.end())?;
//! let limits = openadr::limits(&event, None, day, start, &dso)?;
//! let envelope = limits.iter().try_fold(Envelope::unbounded(grid), |e, l| e.apply(l))?;
//! assert_eq!(envelope.bounds(1).unwrap().max(), Some(kw!(250)));
//! assert_eq!(envelope.bounds(5).unwrap().max(), Some(kw!(400)));
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

use jiff::{SignedDuration, Timestamp};

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

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

use wire::core::{ExpandedInterval, IntervalExpander};
use wire::model::{EventRequest, Program, ReportRequest, Unit, Value};

const PROTOCOL: &str = "OpenADR";
const IMPORT: &str = "IMPORT_CAPACITY_LIMIT";
const EXPORT: &str = "EXPORT_CAPACITY_LIMIT";
const USAGE: &str = "USAGE";

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

fn to_wire(t: Timestamp) -> wire::model::Timestamp {
    t.into()
}

fn from_wire(t: wire::model::Timestamp) -> Timestamp {
    t.into()
}

fn expanded(e: &impl ToString) -> Error {
    refuse("intervals", e, "cannot be placed in time")
}

/// The one value of a payload, as `(mantissa, scale)` and its text: a number, or refused.
fn decimal(field: &'static str, values: &[Value]) -> Result<((i128, u32), String), Error> {
    match values {
        [v] => v
            .as_decimal()
            .map(|d| ((d.mantissa(), d.scale()), d.to_string()))
            .ok_or_else(|| refuse(field, &format!("{v:?}"), "is not a number")),
        _ => Err(refuse(
            field,
            &format!("{} values", values.len()),
            "has not exactly one value",
        )),
    }
}

/// `mantissa ยท 10^-scale ยท factor / divisor` as watts, rounded as named.
fn scaled(
    field: &'static str,
    (mantissa, scale): (i128, u32),
    factor: i128,
    divisor: i128,
    rounding: Rounding,
) -> Result<Power, Error> {
    let too_big = || refuse(field, &mantissa, "is outside the range of watts");
    let n = mantissa.checked_mul(factor).ok_or_else(too_big)?;
    let d = 10_i128
        .checked_pow(scale)
        .and_then(|p| p.checked_mul(divisor))
        .ok_or_else(too_big)?;
    let w = div_round(n, d, rounding)?;
    i64::try_from(w)
        .map(Power::from_watts)
        .map_err(|_| too_big())
}

/// The unit of `payload`: the event's own descriptor, whole, else its programme's default
/// [UG ยง7.6]; a programme with another id contributes nothing.
fn unit_of<'a>(
    event: &'a EventRequest,
    program: Option<&'a Program>,
    payload: &str,
) -> Option<&'a Unit> {
    event
        .payload_descriptor(payload)
        .or_else(|| {
            program
                .filter(|p| p.id == event.program_id)
                .and_then(|p| p.content.event_payload_descriptor(payload))
        })
        .and_then(|d| d.units.as_ref())
}

/// The capacity limits `event` sets within `window`, its units from its payload descriptors or,
/// where it has none for a type, from `program`'s (the programme it belongs to): one [`Limit`] per interval with an
/// `IMPORT_CAPACITY_LIMIT` (a consumption cap) or an `EXPORT_CAPACITY_LIMIT` (a feed-in cap).
/// `received` is the instant `StartTime::Now` (`0001-01-01`) means. An open-ended interval
/// lasts until `window` ends; an interval with `randomizeStart` is held until its end plus the
/// randomization, the latest any VEN may still apply it. Other payload types (prices,
/// subscriptions, reservations) are not limits and are left alone.
///
/// # Errors
/// [`Error::Unrepresentable`] for a limit without `KW` units in the event's payload
/// descriptor, a value that is not one non-negative whole number of watts, two limits of one
/// type in an interval, a negative `randomizeStart`, or intervals the expander cannot place; [`Error::EmptyWindow`] for a zero-length interval.
pub fn limits(
    event: &EventRequest,
    program: Option<&Program>,
    window: Window,
    received: Timestamp,
    provenance: &Provenance,
) -> Result<Vec<Limit>, Error> {
    let expander = IntervalExpander::at(to_wire(received));
    let intervals = expander
        .expand_window(event, to_wire(window.from()), to_wire(window.until()))
        .map_err(|e| expanded(&e))?;
    let mut out = Vec::new();
    for interval in &intervals {
        for payload in [IMPORT, EXPORT] {
            let Some(values) = only(&interval.payloads, payload)? else {
                continue;
            };
            if unit_of(event, program, payload) != Some(&Unit::Kw) {
                return Err(refuse(
                    "units",
                    &format!("{payload}: {:?}", unit_of(event, program, payload)),
                    "is not KW; OpenADR names no default unit",
                ));
            }
            let (value, text) = decimal(payload, &values.values)?;
            let power = scaled(payload, value, 1_000, 1, Rounding::Exact).map_err(|e| match e {
                Error::Inexact { .. } => {
                    refuse(payload, &text, "kW is not a whole number of watts")
                }
                other => other,
            })?;
            if power < Power::ZERO {
                return Err(refuse(
                    payload,
                    &power,
                    "is negative; a capacity limit is a magnitude",
                ));
            }
            let span = span(interval, window)?;
            out.push(if payload == IMPORT {
                Limit::consumption_cap(span, power, provenance.clone())
            } else {
                Limit::feed_in_cap(span, power, provenance.clone())?
            });
        }
    }
    Ok(out)
}

/// The one payload of type `name` in an interval, if any; two of the same type are refused
/// rather than one of them silently read.
fn only<'a>(
    payloads: &'a [wire::model::ValuesMap],
    name: &'static str,
) -> Result<Option<&'a wire::model::ValuesMap>, Error> {
    let mut found = payloads.iter().filter(|p| p.value_type.as_str() == name);
    let first = found.next();
    if found.next().is_some() {
        return Err(refuse(
            name,
            &"two payloads",
            "appears twice in one interval",
        ));
    }
    Ok(first)
}

/// The window an interval holds: its start until its end (or `window`'s end), plus any
/// start randomization.
fn span(interval: &ExpandedInterval, window: Window) -> Result<Window, Error> {
    let from = from_wire(interval.start);
    let mut until = match interval.end {
        Some(end) => from_wire(end),
        None => window.until(),
    };
    if let Some(r) = &interval.randomize_start {
        let nanos = r
            .as_nanos()
            .ok_or_else(|| refuse("randomizeStart", &r, "is not a fixed length"))?;
        if nanos < 0 {
            return Err(refuse(
                "randomizeStart",
                &r,
                "is negative; a start is only delayed",
            ));
        }
        until = i64::try_from(nanos)
            .ok()
            .and_then(|n| until.checked_add(SignedDuration::from_nanos(n)).ok())
            .ok_or_else(|| refuse("randomizeStart", &r, "ends outside the time range"))?;
    }
    Window::new(from, until)
}

/// The average power per ISP of `grid` from the `USAGE` readings of resource `resource` in
/// `report`: energy per interval (`KWH`) รท the ISP length, rounded as named. `event` places
/// readings that carry only the event's interval ids. Every interval must be exactly one ISP
/// of `grid`, and every ISP must have one reading: a missing quarter is refused, not invented.
/// `USAGE` is consumed energy, so the power is never negative.
///
/// # Errors
/// [`Error::Unrepresentable`] for a missing or repeated resource, `USAGE` without `KWH` units, a
/// reading that is not one non-negative number or appears twice in one interval, an interval that is not one ISP of `grid`, an ISP read twice or
/// not at all, or intervals the expander cannot place; [`Error::Inexact`] for a fraction of a
/// watt under [`Rounding::Exact`].
pub fn usage(
    report: &ReportRequest,
    resource: &str,
    event: Option<&EventRequest>,
    grid: &Grid,
    rounding: Rounding,
) -> Result<Series<Power>, Error> {
    let units = report
        .payload_descriptor(USAGE)
        .and_then(|d| d.units.as_ref());
    if units != Some(&Unit::Kwh) {
        return Err(refuse(
            "units",
            &format!("{USAGE}: {units:?}"),
            "is not KWH; OpenADR names no default unit",
        ));
    }
    let mut named = report
        .resources
        .iter()
        .filter(|r| r.resource_name.as_str() == resource);
    let r = named
        .next()
        .ok_or_else(|| refuse("resourceName", &resource, "is not in the report"))?;
    if named.next().is_some() {
        return Err(refuse(
            "resourceName",
            &resource,
            "appears twice in the report",
        ));
    }
    // A reading has a time of its own: a start of "now" lands outside every grid.
    let expander = IntervalExpander::at(wire::model::Timestamp::MIN);
    let readings = expander.expand_report(r, event).map_err(|e| expanded(&e))?;
    let seconds = i128::from(grid.isp().minutes()) * 60;
    let mut values: Vec<Option<Power>> = vec![None; grid.count() as usize];
    for reading in &readings {
        let Some(payload) = only(&reading.payloads, USAGE)? else {
            continue;
        };
        let from = from_wire(reading.start);
        let Some(until) = reading.end.map(from_wire) else {
            return Err(refuse(
                "intervalPeriod",
                &from,
                "has no end; a reading is one ISP",
            ));
        };
        let isp = grid
            .isps(Window::new(from, until)?)
            .filter(|r| r.start() == r.end())
            .map(|r| *r.start())
            .filter(|&isp| {
                grid.interval(isp)
                    .is_some_and(|w| w.from() == from && w.until() == until)
            })
            .ok_or_else(|| {
                refuse(
                    "intervalPeriod",
                    &from,
                    "is not exactly one ISP of the grid",
                )
            })?;
        let (value, text) = decimal(USAGE, &payload.values)?;
        if value.0 < 0 {
            return Err(refuse(
                USAGE,
                &text,
                "is negative; USAGE is consumed energy",
            ));
        }
        let power = scaled(USAGE, value, 3_600_000, seconds, rounding)?;
        let slot = &mut values[(isp - grid.first()) as usize];
        if slot.replace(power).is_some() {
            return Err(refuse("intervalPeriod", &from, "is read twice"));
        }
    }
    let values = grid
        .numbers()
        .zip(values)
        .map(|(isp, v)| {
            v.ok_or_else(|| {
                let label = grid
                    .label(isp)
                    .map_or_else(|| isp.to_string(), |l| l.to_string());
                refuse("intervals", &label, "has no USAGE reading")
            })
        })
        .collect::<Result<Vec<_>, Error>>()?;
    Series::new(grid.clone(), values)
}