flexpool-core 0.4.0

flexpool domain core: exact energy and money units, the Europe/Berlin quarter-hour calendar, portfolio identities and the single quantisation boundary. No I/O, no clock.
Documentation
//! Exact physical and monetary quantities.
//!
//! Only physically meaningful operations exist: power × duration is energy, energy × price is
//! money, capacity price × power × duration is money. Adding power to energy does not compile.
//! Same-unit arithmetic is checked: overflow yields `None`, never a wrapped value.
//!
//! ```compile_fail
//! use flexpool_core::{Kw, Kwh};
//! use rust_decimal::Decimal;
//! let _ = Kw::new(Decimal::ONE).checked_add(Kwh::new(Decimal::ONE));
//! ```

use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use time::Duration;

const THOUSAND: Decimal = Decimal::from_parts(1000, 0, 0, false, 0);
const SECONDS_PER_HOUR: Decimal = Decimal::from_parts(3600, 0, 0, false, 0);

/// Whole seconds of a duration as an exact decimal (sub-second parts are kept as nanoseconds).
fn hours(duration: Duration) -> Option<Decimal> {
    let nanos = Decimal::from_i128_with_scale(duration.whole_nanoseconds(), 9);
    nanos.checked_div(SECONDS_PER_HOUR)
}

macro_rules! quantity {
    ($(#[$meta:meta])* $name:ident, $unit:literal) => {
        $(#[$meta])*
        #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize)]
        #[serde(transparent)]
        pub struct $name(#[serde(with = "rust_decimal::serde::str")] Decimal);

        impl $name {
            /// Zero.
            pub const ZERO: Self = Self(Decimal::ZERO);

            /// Wraps an exact decimal in this unit.
            #[must_use]
            pub const fn new(value: Decimal) -> Self {
                Self(value)
            }

            /// The exact value in this type's unit.
            #[must_use]
            pub const fn value(self) -> Decimal {
                self.0
            }

            /// Checked addition; `None` on overflow.
            #[must_use]
            pub fn checked_add(self, other: Self) -> Option<Self> {
                self.0.checked_add(other.0).map(Self)
            }

            /// Checked subtraction; `None` on overflow.
            #[must_use]
            pub fn checked_sub(self, other: Self) -> Option<Self> {
                self.0.checked_sub(other.0).map(Self)
            }

        }

        impl std::ops::Neg for $name {
            type Output = Self;
            /// The same magnitude with the opposite sign.
            fn neg(self) -> Self {
                Self(-self.0)
            }
        }

        impl std::fmt::Display for $name {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                write!(f, "{} {}", self.0.normalize(), $unit)
            }
        }
    };
}

quantity!(
    /// Power in kilowatts. Positive is consumption (import), negative is feed-in (export).
    Kw,
    "kW"
);
quantity!(
    /// Energy in kilowatt-hours.
    Kwh,
    "kWh"
);
quantity!(
    /// Money in euros, kept at full precision until [`Eur::round_cents`].
    Eur,
    "EUR"
);
quantity!(
    /// Energy price in euros per megawatt-hour (day-ahead, intraday, aFRR energy).
    EurPerMwh,
    "EUR/MWh"
);
quantity!(
    /// Capacity price in euros per megawatt and hour (FCR, aFRR capacity).
    EurPerMwPerH,
    "EUR/MW/h"
);

impl Kw {
    /// Power from megawatts, exactly (× 1000).
    #[must_use]
    pub fn from_mw(mw: Decimal) -> Option<Self> {
        mw.checked_mul(THOUSAND).map(Self)
    }

    /// This power in megawatts, exactly.
    #[must_use]
    pub fn to_mw(self) -> Decimal {
        self.0 / THOUSAND
    }

    /// Energy delivered at this power for `duration`; `None` on overflow.
    #[must_use]
    pub fn energy_over(self, duration: Duration) -> Option<Kwh> {
        hours(duration).and_then(|h| self.0.checked_mul(h)).map(Kwh)
    }
}

impl Kwh {
    /// Energy from megawatt-hours, exactly (× 1000).
    #[must_use]
    pub fn from_mwh(mwh: Decimal) -> Option<Self> {
        mwh.checked_mul(THOUSAND).map(Self)
    }

    /// This energy in megawatt-hours, exactly.
    #[must_use]
    pub fn to_mwh(self) -> Decimal {
        self.0 / THOUSAND
    }

    /// Mean power over `duration`; `None` for a zero duration or overflow.
    #[must_use]
    pub fn mean_power_over(self, duration: Duration) -> Option<Kw> {
        hours(duration).and_then(|h| self.0.checked_div(h)).map(Kw)
    }

    /// The value of this energy at `price`; `None` on overflow.
    #[must_use]
    pub fn priced_at(self, price: EurPerMwh) -> Option<Eur> {
        self.to_mwh().checked_mul(price.0).map(Eur)
    }
}

impl EurPerMwPerH {
    /// Capacity remuneration for holding `power` for `duration`; `None` on overflow.
    #[must_use]
    pub fn for_capacity(self, power: Kw, duration: Duration) -> Option<Eur> {
        let mw_h = hours(duration).and_then(|h| power.to_mw().checked_mul(h))?;
        self.0.checked_mul(mw_h).map(Eur)
    }
}

impl Eur {
    /// Rounded to whole cents, half to even (banker's rounding), for statements and invoices.
    #[must_use]
    pub fn round_cents(self) -> Self {
        Self(
            self.0
                .round_dp_with_strategy(2, rust_decimal::RoundingStrategy::MidpointNearestEven),
        )
    }
}

/// Parses a plain decimal as written in data files: optional minus, digits, optional fraction.
/// Underscores, exponents, a leading `+` and whitespace are refused — `1_0.5` is not 10.5.
#[must_use]
pub fn parse_plain(s: &str) -> Option<Decimal> {
    let body = s.strip_prefix('-').unwrap_or(s);
    let (int, frac) = body.split_once('.').unwrap_or((body, ""));
    let digits = |p: &str| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit());
    let plain = digits(int) && (frac.is_empty() && !body.ends_with('.') || digits(frac));
    if plain {
        <Decimal as std::str::FromStr>::from_str(s).ok()
    } else {
        None
    }
}