Skip to main content

energy_tariff/
lib.rs

1//! Types and calculations for a site's electricity contracts.
2//!
3//! The tariff is data: a [`SiteTariff`] holds contracts, and each contract holds
4//! the charges that apply. This crate computes each charge that is present. It
5//! does not open files, fetch prices, read invoices, or predict peaks.
6//!
7//! Parse with [`SiteTariff::from_json`] and [`SiteTariff::from_toml`]. Both
8//! encodings share one serde schema. File open is the caller's job.
9//!
10//! ```
11//! use energy_tariff::{SiteTariff, TariffError};
12//!
13//! fn load(toml: &str, json: &str) -> Result<SiteTariff, TariffError> {
14//!     let from_toml = SiteTariff::from_toml(toml)?;
15//!     let from_json = SiteTariff::from_json(json)?;
16//!     assert_eq!(from_toml, from_json);
17//!     Ok(from_toml)
18//! }
19//!
20//! # // SYNTHETIC. Not a real site.
21//! # let toml = concat!(
22//! #     "site = \"synthetic-readme\"\n\n",
23//! #     "[[contracts]]\n",
24//! #     "name = \"primary\"\n",
25//! #     "applies_to = \"site\"\n",
26//! #     "period = { start = \"2026-01-01\", end = \"2026-12-31\" }\n\n",
27//! #     "[[contracts.charges]]\n",
28//! #     "type = \"energy\"\n",
29//! #     "kind = \"dam_indexed\"\n",
30//! # );
31//! # let json = r#"{"site":"synthetic-readme","contracts":[{"name":"primary","applies_to":"site","period":{"start":"2026-01-01","end":"2026-12-31"},"charges":[{"type":"energy","kind":"dam_indexed"}]}]}"#;
32//! # load(toml, json).expect("SYNTHETIC");
33//! ```
34
35#![deny(missing_docs)]
36
37mod bill;
38mod contract;
39mod demand;
40mod facilities;
41mod ledgers;
42mod parse;
43mod peak;
44mod settlement;
45mod tou;
46
47pub use bill::{MonthBill, MonthInputs, month_bill};
48pub use contract::{
49    CalendarDate, Charge, ChargeName, DateRange, FixedCharge, Kilowatt, KilowattHour, MeterScope,
50    Minutes, PassThrough, RateUnit, RateWithSource, SiteAlias, SiteTariff, TimeOfUse, Usd,
51    UsdPerMwh, YearMonth,
52};
53pub use demand::{
54    DemandCharge, DemandHistory, DemandResult, Ratchet, demand_bill, demand_charge,
55    marginal_demand_value,
56};
57pub use facilities::{FacilitiesBasis, FacilitiesCharge, facilities_bill};
58pub use ledgers::{LedgerInputs, ledgers};
59pub use peak::{CoincidentPeakRule, PeakExposure, coincident_peak_exposure};
60pub use settlement::{
61    EnergyAdder, EnergyPrices, HedgedRate, Settlement, energy_bill, energy_bill_local,
62};
63pub use tou::{CivilMinute, TouPeriod, TouSchedule};
64
65/// Why a constructor, parse, or calculation refused its input.
66#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
67pub enum TariffError {
68    /// No text at all, which names no site.
69    #[error("a site alias cannot be empty; it looks like synthetic-4cp")]
70    EmptySiteAlias,
71    /// A character an alias cannot hold.
72    #[error("`{alias}` is not a site alias: `{character}` is not one of a-z, 0-9 or -")]
73    SiteAliasCharacter {
74        /// The rejected alias text.
75        alias: String,
76        /// The first character that is not `a-z`, `0-9`, or `-`.
77        character: char,
78    },
79    /// A contract with no name cannot be told apart from another.
80    #[error("a contract name cannot be empty")]
81    EmptyContractName,
82    /// A meter scope with no text names no meter.
83    #[error("a meter scope cannot be empty")]
84    EmptyMeterScope,
85    /// Rate value is negative or not finite.
86    #[error("rate is negative or not finite: {value}")]
87    IllegalRate {
88        /// The rejected number, as text so NaN and infinities still print.
89        value: String,
90    },
91    /// Demand interval length is not 15 or 30 minutes.
92    #[error("demand window must be 15 or 30 minutes, got {0}")]
93    InvalidWindow(u16),
94    /// Ratchet percent is not in `(0, 100]`.
95    #[error("ratchet pct must be in (0, 100], got {0}")]
96    InvalidRatchetPct(String),
97    /// Ratchet lookback of zero months is not a lookback.
98    #[error("ratchet months must be at least 1, got {0}")]
99    InvalidRatchetMonths(u32),
100    /// Coincident-peak count is not 4 or 12.
101    #[error("intervals_per_year must be 4 or 12, got {0}")]
102    InvalidIntervalsPerYear(u8),
103    /// Interval length of zero minutes is not an interval.
104    #[error("interval minutes must be positive, got {0}")]
105    InvalidIntervalMinutes(u16),
106    /// Calendar month outside 1..=12.
107    #[error("month {0} is not in 1..=12")]
108    InvalidMonth(u8),
109    /// Text is not a calendar day in `YYYY-MM-DD`.
110    #[error("date `{0}` is not YYYY-MM-DD")]
111    InvalidDate(String),
112    /// Range starts after it ends.
113    #[error("date range starts after it ends")]
114    InvertedDateRange,
115    /// Hour-of-day outside 0..=23.
116    #[error("time-of-use hour {0} is not in 0..=23")]
117    InvalidHour(u8),
118    /// Minute of day outside the legal window.
119    #[error("minute {0} is outside 0..1440 (end may be 1440)")]
120    InvalidMinute(u16),
121    /// ISO weekday outside 1..=7.
122    #[error("ISO weekday {0} is not in 1..=7")]
123    InvalidWeekday(u8),
124    /// Time-of-use period with no name.
125    #[error("a time-of-use period name cannot be empty")]
126    EmptyTouName,
127    /// Time-of-use period that names no month.
128    #[error("a time-of-use period has no months")]
129    EmptyTouMonths,
130    /// Time-of-use period that names no weekday.
131    #[error("a time-of-use period has no weekdays")]
132    EmptyTouWeekdays,
133    /// The same month listed twice in one period.
134    #[error("duplicate month {0} in a time-of-use period")]
135    DuplicateTouMonth(u8),
136    /// The same weekday listed twice in one period.
137    #[error("duplicate weekday {0} in a time-of-use period")]
138    DuplicateTouWeekday(u8),
139    /// `start_min >= end_min`, so the window contains no minute.
140    #[error("time-of-use window is empty")]
141    EmptyTouWindow,
142    /// Schedule with no periods.
143    #[error("time-of-use schedule has no periods")]
144    EmptyTouSchedule,
145    /// Two periods cover the same local minute.
146    #[error("time-of-use periods `{first}` and `{second}` overlap")]
147    OverlappingTouPeriods {
148        /// Name of the earlier period.
149        first: String,
150        /// Name of the later period.
151        second: String,
152    },
153    /// Civil time fell in no period.
154    #[error("civil time matches no time-of-use period")]
155    UnmatchedCivilTime,
156    /// Load hour fell in no period.
157    #[error("time-of-use interval {index} matches no period")]
158    UnmatchedTouInterval {
159        /// Index into the load slice.
160        index: usize,
161    },
162    /// Load hours and civil times have different lengths.
163    #[error("load length {load} does not match civil-time length {local}")]
164    CivilTimeLengthMismatch {
165        /// Length of the load series.
166        load: usize,
167        /// Length of the civil-time series.
168        local: usize,
169    },
170    /// Time-of-use settlement billed without civil time.
171    #[error("time-of-use energy needs civil local time")]
172    MissingCivilTime,
173    /// Adder of zero is the unit settlement, not an adder variant.
174    #[error("an energy adder of zero is the unit settlement, not an adder")]
175    ZeroAdder,
176    /// `contract_kw` basis without a quantity.
177    #[error("facilities basis contract_kw needs contract_kw")]
178    MissingContractKw,
179    /// `ratcheted_peak` basis that also carries a contract quantity.
180    #[error("facilities basis ratcheted_peak does not take contract_kw")]
181    UnexpectedContractKw,
182    /// `ratcheted_peak` facilities with no demand charge on the same contract.
183    #[error("facilities basis ratcheted_peak needs a demand charge")]
184    RatchetedPeakWithoutDemand,
185    /// Supplied coincident-peak kW count does not match the rule.
186    #[error("coincident-peak intervals: expected {expected}, got {got}")]
187    IntervalCountMismatch {
188        /// Count the rule requires.
189        expected: usize,
190        /// Count the caller supplied.
191        got: usize,
192    },
193    /// Energy load hours and the price series are different lengths.
194    #[error("load length {load} does not match price length {prices}")]
195    SeriesLengthMismatch {
196        /// Length of the load series.
197        load: usize,
198        /// Length of the price series.
199        prices: usize,
200    },
201    /// JSON text did not match the schema, or a constructor refused a value.
202    #[error("JSON: {0}")]
203    Json(String),
204    /// TOML text did not match the schema, or a constructor refused a value.
205    #[error("TOML: {0}")]
206    Toml(String),
207}
208
209impl From<serde_json::Error> for TariffError {
210    fn from(error: serde_json::Error) -> Self {
211        Self::Json(error.to_string())
212    }
213}
214
215impl From<toml::de::Error> for TariffError {
216    fn from(error: toml::de::Error) -> Self {
217        Self::Toml(error.to_string())
218    }
219}
220
221impl From<toml::ser::Error> for TariffError {
222    fn from(error: toml::ser::Error) -> Self {
223        Self::Toml(error.to_string())
224    }
225}
226
227pub(crate) fn illegal_rate(value: f64) -> TariffError {
228    TariffError::IllegalRate {
229        value: value.to_string(),
230    }
231}
232
233pub(crate) fn require_non_negative_finite(value: f64) -> Result<f64, TariffError> {
234    if value.is_finite() && value >= 0.0 {
235        Ok(value)
236    } else {
237        Err(illegal_rate(value))
238    }
239}