flexibility 0.2.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
//! CSIP-AUS dynamic operating envelopes (IEEE 2030.5), behind the `csip` feature.
//!
//! A CSIP-AUS utility server sends a connection point's import and export limits
//! (`opModImpLimW`, `opModExpLimW`) as DER controls: each with an interval, a program primacy
//! and a creation time, superseding or superseded by others. [`envelope`] reads them onto a
//! [`Grid`] as an [`Envelope`], naming the control that set each bound.
//!
//! - **Which control is in force** is the `ieee2030-5` crate's call (`csip_aus::effective_limit`,
//!   CSIP-AUS v1.2 §7): the higher primacy wins, then the newer control, and a displaced control
//!   never comes back. Not the tightest: a later, looser envelope replaces an earlier one.
//! - **Within an ISP** the control in force may change; the envelope takes the strictest value
//!   any instant of the ISP sees, so a plan inside it keeps every control. When import and
//!   export controls each hold for part of an ISP and together leave no constant power (import
//!   at most 1 kW, then an export limit of −2 kW that demands 2 kW of import), the envelope is
//!   refused with [`Error::EmptyRange`]: no plan constant over the ISP keeps both.
//! - **Sign.** An import limit of p W is a consumption maximum of p; an export limit of p W is
//!   a minimum of −p (feed-in of at most p). A negative limit keeps its meaning: an export limit
//!   of −2 kW demands an import of at least 2 kW.
//! - **Exact.** A limit is `value × 10^multiplier` W; a fraction of a watt is refused.
//! - `opModGenLimW` and `opModLoadLimW` bound a DER's gross generation and load, not the
//!   connection point, and are not part of the envelope.
//!
//! ```
//! use flexibility::csip::{self, wire};
//! use flexibility::{Grid, IspDuration, Provenance, kw};
//! use wire::csip_aus::{ActivePower, Mode, SiteMode};
//! use wire::schedule::{Event, Offset, Window};
//! # use flexibility::jiff::{Timestamp, tz::TimeZone};
//! # let noon: Timestamp = "2026-12-01T02:00:00Z".parse()?;
//! # let grid = Grid::new(noon, IspDuration::FIFTEEN_MINUTES, 4, TimeZone::get("Australia/Sydney")?)?;
//! let site = SiteMode { connection_point: "NMI-4001", mode: Mode::Export };
//! let half_hour = Window::new(noon.as_second(), 1_800, Offset::default(), Offset::default()).unwrap();
//! // Export at most 1.5 kW for half an hour (150 × 10^1 W); 5 kW otherwise (the default).
//! let events = [Event { id: 0xA1, mode: site, value: ActivePower { value: 150, multiplier: 1 },
//!     primacy: 1, created: noon.as_second() - 600, received: noon.as_second() - 600,
//!     window: half_hour, termination: None }];
//! let defaults = [(Mode::Export, ActivePower { value: 5, multiplier: 3 })];
//!
//! let server = Provenance::new("utility.example", "csip", noon);
//! let envelope = csip::envelope(&events, "NMI-4001", &defaults, &grid, &server)?;
//! assert_eq!(envelope.bounds(1).unwrap().min(), Some(kw!(-1.5)));
//! assert_eq!(envelope.bounds(3).unwrap().min(), Some(kw!(-5)));
//! assert_eq!(envelope.min_source(1).unwrap().reference(), "DERControl 000000000000000000000000000000A1 opModExpLimW");
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

use std::collections::BTreeSet;

use crate::{Bounds, Envelope, Error, Grid, Limit, Power, Provenance};

/// The `ieee2030-5` crate this feature maps to.
pub use ::ieee2030_5 as wire;

use wire::csip_aus::{self, ActivePower, Mode, PowerError, SiteMode};
use wire::schedule::{self, Event, Selection};

const PROTOCOL: &str = "CSIP-AUS";

/// The most controls read for one connection point: more is refused, not truncated.
pub const MAX_CONTROLS: usize = 10_000;

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

fn watts(mode: Mode, p: ActivePower) -> Result<Power, Error> {
    let text = format!("{} × 10^{} W", p.value, p.multiplier);
    match p.whole_watts() {
        Ok(w) => Ok(Power::from_watts(w)),
        Err(PowerError::Fractional) => Err(refuse(
            mode.local_name(),
            &text,
            "is not a whole number of watts",
        )),
        Err(_) => Err(refuse(
            mode.local_name(),
            &text,
            "is outside the range of watts",
        )),
    }
}

/// The connection point's import and export limits from CSIP-AUS DER controls, on `grid`: per
/// ISP, the strictest value of the control in force at any instant of the ISP, or the site's
/// default control for that mode when none is. Each bound names its control: `provenance`'s
/// issuer and issue time, and a reference `DERControl <mRID> opModImpLimW` (or
/// `DefaultDERControl opModExpLimW`).
///
/// Pass the controls of every program for the site, projected per mode with
/// `wire::csip_aus::events`; controls for other connection points or modes are skipped.
///
/// # Errors
/// [`Error::Unrepresentable`] for a limit that is not whole watts, more than [`MAX_CONTROLS`]
/// controls, or controls the CSIP rules cannot order (two of equal primacy and creation time,
/// a duplicate mRID).
pub fn envelope(
    events: &[Event<SiteMode<'_>, ActivePower>],
    connection_point: &str,
    defaults: &[(Mode, ActivePower)],
    grid: &Grid,
    provenance: &Provenance,
) -> Result<Envelope, Error> {
    if events.len() > MAX_CONTROLS {
        return Err(refuse(
            "DERControl",
            &events.len(),
            "is more controls than this crate reads",
        ));
    }
    let source =
        |reference: String| Provenance::new(provenance.issuer(), reference, provenance.issued_at());
    let mut envelope = Envelope::unbounded(grid.clone());
    for mode in [Mode::Import, Mode::Export] {
        let key = SiteMode {
            connection_point,
            mode,
        };
        let default = defaults.iter().find(|(m, _)| *m == mode).map(|(_, p)| p);
        // Every instant at which CSIP's selection may change: constant between them.
        let changes: BTreeSet<i64> = schedule::changes(events, &key).collect();
        for isp in grid.numbers() {
            let window = grid.interval(isp).ok_or(Error::NoData {
                what: "an ISP of the grid",
            })?;
            let (from, until) = (window.from().as_second(), window.until().as_second());
            let instants = std::iter::once(from).chain(changes.range(from + 1..until).copied());
            // The strictest value seen in the ISP, and who set it.
            let mut strictest: Option<(Power, String)> = None;
            for now in instants {
                let selected = csip_aus::effective_limit(
                    events,
                    key,
                    now,
                    default.map(|p| (key, p)),
                    MAX_CONTROLS,
                )
                .map_err(|e| {
                    refuse(
                        "DERControl",
                        &format!("{e:?}"),
                        "cannot be ordered by the CSIP rules",
                    )
                })?;
                let (value, reference) = match selected {
                    Selection::Event { id, value } => (value, format!("DERControl {id:032X}")),
                    Selection::Default(value) => (value, "DefaultDERControl".to_owned()),
                    Selection::Idle => continue,
                };
                let power = watts(mode, *value)?;
                if strictest.as_ref().is_none_or(|(p, _)| power < *p) {
                    strictest = Some((power, format!("{reference} {}", mode.local_name())));
                }
            }
            let Some((power, reference)) = strictest else {
                continue;
            };
            let bounds = match mode {
                Mode::Import => Bounds::at_most(power),
                _ => Bounds::at_least(power.checked_neg()?),
            };
            envelope = envelope.apply(&Limit::new(window, bounds, source(reference)))?;
        }
    }
    Ok(envelope)
}