flexibility 0.1.0

Grid flexibility as exact, replayable arithmetic: limits, baselines, UFTP-exact settlement, and UFTP, EEBUS, S2, OpenADR, IEC 104 converters.
Documentation
//! IEC 60870-5-104 active-power set points as limits and back, behind the `iec104` feature.
//!
//! A grid operator's control centre caps a plant or a site over IEC 104 with a set-point
//! command: type 48 (normalized), 49 (scaled) or 50 (short float). The command carries a number;
//! what it means is in the operator's **point list** (which information object, which unit,
//! what 100 % is). That is a [`Point`], the integrator's configuration, and every conversion
//! takes one.
//!
//! - **Normalized** values are fractions of a full-scale power in steps of 2⁻¹⁵: 30 % of 10 MW
//!   is not a whole watt, so the reading names a [`Rounding`]. [`Rounding::TowardZero`] never
//!   exceeds the exact value: for a cap, the stricter side.
//! - **Scaled** values are whole counts of a step (1 kW, 0.1 MW): exact.
//! - **Short floats** are read through their shortest decimal, the number the operator typed:
//!   `4.2` (kW) is 4 200 W exactly. Writing one, a cap that needs more digits than an `f32` keeps
//!   is refused rather than sent rounded.
//! - The command has no duration: a set point holds until the next one, so the window is the
//!   caller's. A **select** of select-before-operate sets nothing and is refused.
//!
//! ```
//! use flexibility::iec104::{self, wire, Direction, Point, Scale};
//! use flexibility::{Provenance, Rounding, Window, kw};
//! use wire::types::{Normalized, SetpointNormalized, SetpointScaled};
//! # use flexibility::jiff::Timestamp;
//! # let now: Timestamp = "2026-12-01T16:00:00Z".parse()?;
//! # let window = Window::new(now, "2026-12-01T18:00:00Z".parse()?)?;
//! let scc = Provenance::new("tso.example", "IOA 4711", now);
//! // A wind park, 10 MW installed: feed in at most 50 % of it.
//! let park = Point { direction: Direction::FeedIn, scale: Scale::Normalized { full_scale: kw!(10_000) } };
//! let cap = iec104::limit(SetpointNormalized::new(Normalized(16_384)), park, window, Rounding::Exact, scc.clone())?;
//! assert_eq!(cap.bounds().min(), Some(kw!(-5_000)));
//!
//! // A site cap in whole kilowatts: 250 counts of 1 kW.
//! let site = Point { direction: Direction::Consumption, scale: Scale::Scaled { step: kw!(1) } };
//! let cap = iec104::limit(SetpointScaled::new(250), site, window, Rounding::Exact, scc)?;
//! assert_eq!(cap.bounds().max(), Some(kw!(250)));
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

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

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

use wire::types::{
    Normalized, SetpointFloat, SetpointNormalized, SetpointQualifier, SetpointScaled,
};

const PROTOCOL: &str = "IEC 104";

/// 2¹⁵: a normalized value is `raw / 32768`.
const FULL: i128 = 32_768;

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

/// Which way a set point caps.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Direction {
    /// A consumption cap: power at most the value.
    Consumption,
    /// A feed-in cap: feed-in of at most the value (a generator's active-power limit).
    FeedIn,
}

/// What a set point's number is, from the operator's point list.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Scale {
    /// Type 48: a fraction (−1 … 1 − 2⁻¹⁵) of `full_scale`, often the installed or agreed power.
    Normalized {
        /// The power a value of 1 stands for.
        full_scale: Power,
    },
    /// Type 49: whole counts of `step` (1 kW, 100 kW).
    Scaled {
        /// The power of one count.
        step: Power,
    },
    /// Type 50: a short float in `unit`: `w!(1)`, `kw!(1)` or `mw!(1)`.
    Float {
        /// The power of 1.0; a power of ten watts.
        unit: Power,
    },
}

/// One information object's meaning: which way it caps and how its number reads.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Point {
    /// Which way it caps.
    pub direction: Direction,
    /// How its number reads.
    pub scale: Scale,
}

/// A set-point command of type 48, 49 or 50.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Setpoint {
    /// Type 48.
    Normalized(SetpointNormalized),
    /// Type 49.
    Scaled(SetpointScaled),
    /// Type 50.
    Float(SetpointFloat),
}

impl From<SetpointNormalized> for Setpoint {
    fn from(s: SetpointNormalized) -> Setpoint {
        Setpoint::Normalized(s)
    }
}
impl From<SetpointScaled> for Setpoint {
    fn from(s: SetpointScaled) -> Setpoint {
        Setpoint::Scaled(s)
    }
}
impl From<SetpointFloat> for Setpoint {
    fn from(s: SetpointFloat) -> Setpoint {
        Setpoint::Float(s)
    }
}

impl Setpoint {
    fn qualifier(self) -> SetpointQualifier {
        match self {
            Setpoint::Normalized(s) => s.qualifier,
            Setpoint::Scaled(s) => s.qualifier,
            Setpoint::Float(s) => s.qualifier,
        }
    }
}

fn positive(field: &'static str, p: Power) -> Result<i128, Error> {
    if p <= Power::ZERO {
        return Err(refuse(field, &p, "must be positive in the point list"));
    }
    Ok(i128::from(p.watts()))
}

/// A float unit as a power of ten watts: `10^k`.
fn decimal_places(unit: Power) -> Result<u32, Error> {
    let w = positive("unit", unit)?;
    (0..=18)
        .find(|&k| 10_i128.pow(k) == w)
        .ok_or_else(|| refuse("unit", &unit, "is not a power of ten watts (W, kW, MW)"))
}

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

/// A short float as `(mantissa, scale)`: its shortest round-trip decimal, which is what the
/// operator typed when it has at most 7 significant digits. Rust prints no exponent.
#[allow(clippy::disallowed_types)]
fn float_decimal(value: f32) -> Result<(i128, u32), Error> {
    if !value.is_finite() {
        return Err(refuse("value", &value, "is not a finite number"));
    }
    let text = format!("{value}");
    let (whole, fraction) = text.split_once('.').unwrap_or((&text, ""));
    if whole.trim_start_matches('-').len() > 16 {
        return Err(refuse(
            "value",
            &format!("{value:e}"),
            "is outside the range of watts",
        ));
    }
    let mantissa: i128 = format!("{whole}{fraction}")
        .parse()
        .map_err(|_| refuse("value", &format!("{value:e}"), "is not a decimal number"))?;
    let scale = u32::try_from(fraction.len()).unwrap_or(u32::MAX);
    Ok((mantissa, scale))
}

/// The short float that reads back as `text`, a decimal; `None` if no `f32` does.
#[allow(clippy::disallowed_types)]
fn float_of(text: &str) -> Option<(f32, (i128, u32))> {
    let f: f32 = text.parse().ok()?;
    float_decimal(f).ok().map(|d| (f, d))
}

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

/// Refuses a negative value before any rounding: −0.4 W is negative, not a 0 W cap.
fn negative(raw: i128, shown: &dyn Fn() -> String) -> Result<(), Error> {
    if raw < 0 {
        return Err(refuse(
            "value",
            &shown(),
            "is negative; an active-power cap is a magnitude",
        ));
    }
    Ok(())
}

fn to_watts(
    n: i128,
    d: i128,
    rounding: Rounding,
    shown: &dyn Fn() -> String,
) -> Result<Power, Error> {
    let w = match rounding {
        Rounding::Exact if n % d != 0 => {
            return Err(refuse("value", &shown(), "is not a whole number of watts"));
        }
        _ => div_round(n, d, rounding)?,
    };
    i64::try_from(w)
        .map(Power::from_watts)
        .map_err(|_| refuse("value", &shown(), "is outside the range of watts"))
}

/// The cap a set point sets at `point`, over `window` (until the next set point): a
/// consumption cap or a feed-in cap of the value read as the point list says, rounded as named.
///
/// # Errors
/// [`Error::Unrepresentable`] for a select (not an execute), a type the point is not
/// configured for, a negative value, a scale that is not positive, a float that is not finite
/// or not whole watts under [`Rounding::Exact`].
pub fn limit(
    setpoint: impl Into<Setpoint>,
    point: Point,
    window: Window,
    rounding: Rounding,
    provenance: Provenance,
) -> Result<Limit, Error> {
    let setpoint = setpoint.into();
    if setpoint.qualifier().is_select() {
        return Err(refuse(
            "qualifier",
            &"select",
            "is the select of select-before-operate; only the execute sets a value",
        ));
    }
    let power = match (setpoint, point.scale) {
        (Setpoint::Normalized(s), Scale::Normalized { full_scale }) => {
            let raw = i128::from(s.value.0);
            negative(raw, &|| s.value.to_string())?;
            to_watts(
                raw * positive("full_scale", full_scale)?,
                FULL,
                rounding,
                &|| format!("{} of {full_scale}", s.value),
            )?
        }
        (Setpoint::Scaled(s), Scale::Scaled { step }) => {
            let raw = i128::from(s.value);
            negative(raw, &|| s.value.to_string())?;
            to_watts(raw * positive("step", step)?, 1, rounding, &|| {
                format!("{} × {step}", s.value)
            })?
        }
        (Setpoint::Float(s), Scale::Float { unit }) => {
            let k = decimal_places(unit)?;
            let (mantissa, scale) = float_decimal(s.value)?;
            let shown = || format!("{mantissa}e-{scale} × {unit}");
            negative(mantissa, &shown)?;
            // mantissa · 10^-scale · 10^k W
            if scale <= k {
                let factor = 10_i128
                    .checked_pow(k - scale)
                    .ok_or_else(|| refuse("value", &shown(), "is outside the range of watts"))?;
                to_watts(
                    mantissa.checked_mul(factor).ok_or_else(|| {
                        refuse("value", &shown(), "is outside the range of watts")
                    })?,
                    1,
                    rounding,
                    &shown,
                )?
            } else {
                match 10_i128.checked_pow(scale - k) {
                    Some(divisor) => to_watts(mantissa, divisor, rounding, &shown)?,
                    // Below 10^-21 W: no whole watt; zero when a rounding is named.
                    None if rounding == Rounding::Exact && mantissa != 0 => {
                        return Err(refuse("value", &shown(), "is not a whole number of watts"));
                    }
                    None => Power::ZERO,
                }
            }
        }
        (s, scale) => {
            return Err(refuse(
                "type",
                &format!("{s:?}"),
                match scale {
                    Scale::Normalized { .. } => {
                        "arrived where the point list expects type 48 (normalized)"
                    }
                    Scale::Scaled { .. } => "arrived where the point list expects type 49 (scaled)",
                    Scale::Float { .. } => {
                        "arrived where the point list expects type 50 (short float)"
                    }
                },
            ));
        }
    };
    if power < Power::ZERO {
        return Err(refuse(
            "value",
            &power,
            "is negative; an active-power cap is a magnitude",
        ));
    }
    match point.direction {
        Direction::Consumption => Ok(Limit::consumption_cap(window, power, provenance)),
        Direction::FeedIn => Limit::feed_in_cap(window, power, provenance),
    }
}

/// The execute set point that carries a cap of `cap` (a magnitude) at `point`, rounded as
/// named. [`Rounding::TowardZero`] sends a value that never exceeds the cap; a normalized
/// 100 % (not representable, the largest value is 1 − 2⁻¹⁵) becomes the largest value under it.
///
/// # Errors
/// [`Error::Unrepresentable`] for a negative cap, a value beyond the type's range, a scale that
/// is not positive, or a cap a short float cannot hold exactly; [`Error::Inexact`] for a
/// remainder under [`Rounding::Exact`].
pub fn setpoint(cap: Power, point: Point, rounding: Rounding) -> Result<Setpoint, Error> {
    if cap < Power::ZERO {
        return Err(refuse(
            "value",
            &cap,
            "is negative; an active-power cap is a magnitude",
        ));
    }
    let w = i128::from(cap.watts());
    let fit = |raw: i128| {
        i16::try_from(raw).map_err(|_| refuse("value", &cap, "is beyond the set point's range"))
    };
    match point.scale {
        Scale::Normalized { full_scale } => {
            let full = positive("full_scale", full_scale)?;
            let mut raw = div_round(w * FULL, full, rounding)?;
            if raw == FULL && rounding == Rounding::TowardZero {
                raw = FULL - 1;
            }
            Ok(Setpoint::Normalized(SetpointNormalized::new(Normalized(
                fit(raw)?,
            ))))
        }
        Scale::Scaled { step } => {
            let raw = div_round(w, positive("step", step)?, rounding)?;
            Ok(Setpoint::Scaled(SetpointScaled::new(fit(raw)?)))
        }
        Scale::Float { unit } => {
            let k = decimal_places(unit)?;
            let places = k as usize;
            let digits = format!("{:0>width$}", w, width = places + 1);
            let (whole, fraction) = digits.split_at(digits.len() - places);
            let text = if k == 0 {
                whole.to_owned()
            } else {
                format!("{whole}.{fraction}")
            };
            let (value, (mantissa, scale)) =
                float_of(&text).ok_or_else(|| refuse("value", &cap, "is not a short float"))?;
            // The float must read back as the cap, exactly.
            let back = (scale <= k).then(|| mantissa * 10_i128.pow(k - scale));
            if back != Some(w) {
                return Err(refuse(
                    "value",
                    &cap,
                    "needs more digits than a short float holds",
                ));
            }
            Ok(Setpoint::Float(SetpointFloat::new(value)))
        }
    }
}