Skip to main content

s2_kit/types/
frbc.rs

1//! Fill Rate Based Control — anything that stores or buffers energy.
2//!
3//! A battery, an EV, a hot-water tank, a fridge, a building's thermal mass. The Resource
4//! Manager describes a **storage** with a fill level, and one or more **actuators** that
5//! change it; each actuator is a state machine whose states carry both a power and the
6//! rate at which they fill or empty the store.
7//!
8//! The fill level's unit is the Resource Manager's choice — the standard requires only
9//! that the fill *rate* be in that unit per second. The official examples use percent
10//! state of charge for an EV and degrees Celsius for a hot-water buffer; `hems` uses
11//! kilowatt-hours for every store. This crate imposes nothing and interpolates nothing
12//! it was not given.
13
14use alloc::string::String;
15use alloc::vec::Vec;
16
17use bon::Builder;
18use serde::{Deserialize, Serialize};
19
20use super::common::{PowerRange, Timer, Transition};
21use super::{Duration, Id, NumberRange, Timestamp};
22
23// ---------------------------------------------------------------------------
24// Components
25// ---------------------------------------------------------------------------
26
27/// The storage whose fill level the CEM is planning against.
28#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
29#[serde(deny_unknown_fields)]
30#[builder(on(String, into))]
31pub struct StorageDescription {
32    /// Human-readable, for debugging only.
33    #[serde(skip_serializing_if = "Option::is_none")]
34    pub diagnostic_label: Option<String>,
35    /// What the fill level is measured in — "percentage state of charge", "temperature
36    /// in Celsius". For humans; nothing computes with it.
37    #[serde(skip_serializing_if = "Option::is_none")]
38    pub fill_level_label: Option<String>,
39    /// Whether a [`LeakageBehaviour`] may follow.
40    pub provides_leakage_behaviour: bool,
41    /// Whether a [`FillLevelTargetProfile`] may follow.
42    pub provides_fill_level_target_profile: bool,
43    /// Whether a [`UsageForecast`] may follow.
44    pub provides_usage_forecast: bool,
45    /// The range the fill level should stay within.
46    ///
47    /// "When the fill_level is not within this range, the Resource Manager can ignore
48    /// instructions from the CEM (except during abnormal conditions)."
49    pub fill_level_range: NumberRange,
50}
51
52/// How an operation mode behaves over one band of the fill level.
53///
54/// Splitting a mode into elements is how a Resource Manager describes behaviour that is
55/// not linear in the fill level — a heat pump whose efficiency falls as the buffer gets
56/// hotter, say. The elements' `fill_level_range`s must be contiguous.
57#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
58#[serde(deny_unknown_fields)]
59pub struct OperationModeElement {
60    /// The band of fill level this element describes. Start strictly below end.
61    pub fill_level_range: NumberRange,
62    /// Change in fill level per second: the start at factor 0, the end at factor 1.
63    /// Positive fills the store.
64    pub fill_rate: NumberRange,
65    /// The power exchanged with the grid, at most one range per commodity quantity.
66    pub power_ranges: Vec<PowerRange>,
67    /// Cost per second of running in this mode, excluding the commodity itself. The
68    /// range expresses uncertainty and is **not** interpolated by the factor.
69    #[serde(skip_serializing_if = "Option::is_none")]
70    pub running_costs: Option<NumberRange>,
71}
72
73/// One state of an actuator's state machine.
74#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
75#[serde(deny_unknown_fields)]
76#[builder(on(String, into))]
77pub struct OperationMode {
78    /// Unique within the actuator description that contains it.
79    pub id: Id,
80    /// Human-readable, for debugging only.
81    #[serde(skip_serializing_if = "Option::is_none")]
82    pub diagnostic_label: Option<String>,
83    /// How the mode behaves across the fill level. Ranges must be contiguous.
84    pub elements: Vec<OperationModeElement>,
85    /// Whether this mode may only be used during an abnormal condition.
86    pub abnormal_condition_only: bool,
87}
88
89impl OperationMode {
90    /// The element that applies at `fill_level`, if any band covers it.
91    #[must_use]
92    pub fn element_at(&self, fill_level: f64) -> Option<&OperationModeElement> {
93        self.elements
94            .iter()
95            .find(|e| e.fill_level_range.contains(fill_level))
96    }
97}
98
99/// Something the CEM can control that changes the storage's fill level.
100#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
101#[serde(deny_unknown_fields)]
102#[builder(on(String, into))]
103pub struct ActuatorDescription {
104    /// Unique within the Resource Manager for the session.
105    pub id: Id,
106    /// Human-readable, for debugging only.
107    #[serde(skip_serializing_if = "Option::is_none")]
108    pub diagnostic_label: Option<String>,
109    /// The commodities this actuator's modes use.
110    pub supported_commodities: Vec<super::common::Commodity>,
111    /// The states of the machine.
112    pub operation_modes: Vec<OperationMode>,
113    /// The permitted moves between them.
114    pub transitions: Vec<Transition>,
115    /// Timers those moves start or wait for.
116    pub timers: Vec<Timer>,
117}
118
119impl ActuatorDescription {
120    /// The operation mode with this id, if the actuator has one.
121    #[must_use]
122    pub fn operation_mode(&self, id: &Id) -> Option<&OperationMode> {
123        self.operation_modes.iter().find(|m| m.id == *id)
124    }
125
126    /// The timer with this id, if the actuator has one.
127    #[must_use]
128    pub fn timer(&self, id: &Id) -> Option<&Timer> {
129        self.timers.iter().find(|t| t.id == *id)
130    }
131
132    /// The transition from `from` to `to`, if one is described.
133    #[must_use]
134    pub fn transition(&self, from: &Id, to: &Id) -> Option<&Transition> {
135        self.transitions
136            .iter()
137            .find(|t| t.from == *from && t.to == *to)
138    }
139}
140
141/// A fill level the CEM should reach within a period.
142#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
143#[serde(deny_unknown_fields)]
144pub struct FillLevelTargetProfileElement {
145    /// How long this element lasts.
146    pub duration: Duration,
147    /// The band the fill level must be in while it is active. "The CEM must take
148    /// best-effort actions to proactively achieve this target."
149    pub fill_level_range: NumberRange,
150}
151
152/// How fast the store loses charge on its own, over one band of the fill level.
153#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
154#[serde(deny_unknown_fields)]
155pub struct LeakageBehaviourElement {
156    /// The band this element describes.
157    pub fill_level_range: NumberRange,
158    /// Fill level lost per second. **Positive means the level decreases.**
159    pub leakage_rate: f64,
160}
161
162/// Expected demand on the store, over one slice of time.
163///
164/// As with leakage, a **positive rate means the fill level decreases**.
165#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, Builder)]
166#[serde(deny_unknown_fields)]
167pub struct UsageForecastElement {
168    /// How long this slice lasts.
169    pub duration: Duration,
170    /// The 100 % upper bound.
171    #[serde(skip_serializing_if = "Option::is_none")]
172    pub usage_rate_upper_limit: Option<f64>,
173    /// The 95 % upper bound.
174    #[serde(
175        rename = "usage_rate_upper_95PPR",
176        skip_serializing_if = "Option::is_none"
177    )]
178    pub usage_rate_upper_95ppr: Option<f64>,
179    /// The 68 % upper bound.
180    #[serde(
181        rename = "usage_rate_upper_68PPR",
182        skip_serializing_if = "Option::is_none"
183    )]
184    pub usage_rate_upper_68ppr: Option<f64>,
185    /// The most likely usage rate.
186    pub usage_rate_expected: f64,
187    /// The 68 % lower bound.
188    #[serde(
189        rename = "usage_rate_lower_68PPR",
190        skip_serializing_if = "Option::is_none"
191    )]
192    pub usage_rate_lower_68ppr: Option<f64>,
193    /// The 95 % lower bound.
194    #[serde(
195        rename = "usage_rate_lower_95PPR",
196        skip_serializing_if = "Option::is_none"
197    )]
198    pub usage_rate_lower_95ppr: Option<f64>,
199    /// The 100 % lower bound.
200    #[serde(skip_serializing_if = "Option::is_none")]
201    pub usage_rate_lower_limit: Option<f64>,
202}
203
204impl UsageForecastElement {
205    /// The bands from lowest to highest, skipping those that are absent.
206    #[must_use]
207    pub fn bands_ascending(&self) -> [(&'static str, Option<f64>); 7] {
208        [
209            ("usage_rate_lower_limit", self.usage_rate_lower_limit),
210            ("usage_rate_lower_95PPR", self.usage_rate_lower_95ppr),
211            ("usage_rate_lower_68PPR", self.usage_rate_lower_68ppr),
212            ("usage_rate_expected", Some(self.usage_rate_expected)),
213            ("usage_rate_upper_68PPR", self.usage_rate_upper_68ppr),
214            ("usage_rate_upper_95PPR", self.usage_rate_upper_95ppr),
215            ("usage_rate_upper_limit", self.usage_rate_upper_limit),
216        ]
217    }
218}
219
220// ---------------------------------------------------------------------------
221// Messages
222// ---------------------------------------------------------------------------
223
224/// The abstract device: its storage and every actuator that can move it.
225#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
226#[serde(deny_unknown_fields)]
227pub struct SystemDescription {
228    /// This message's identifier.
229    #[cfg_attr(feature = "uuid", builder(default = Id::generate()))]
230    pub message_id: Id,
231    /// When this description becomes valid. In the past means immediately.
232    pub valid_from: Timestamp,
233    /// Every actuator. At least one, at most ten.
234    pub actuators: Vec<ActuatorDescription>,
235    /// The storage they all affect.
236    pub storage: StorageDescription,
237}
238
239impl SystemDescription {
240    /// The actuator with this id, if the description has one.
241    #[must_use]
242    pub fn actuator(&self, id: &Id) -> Option<&ActuatorDescription> {
243        self.actuators.iter().find(|a| a.id == *id)
244    }
245}
246
247/// How full the store is now.
248#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
249#[serde(deny_unknown_fields)]
250pub struct StorageStatus {
251    /// This message's identifier.
252    #[cfg_attr(feature = "uuid", builder(default = Id::generate()))]
253    pub message_id: Id,
254    /// The present fill level, in the unit the description named.
255    pub present_fill_level: f64,
256}
257
258impl StorageStatus {
259    /// A storage status.
260    #[cfg(feature = "uuid")]
261    #[must_use]
262    pub fn new(present_fill_level: f64) -> Self {
263        Self {
264            message_id: Id::generate(),
265            present_fill_level,
266        }
267    }
268}
269
270/// Which operation mode an actuator is in, and how far into it.
271#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
272#[serde(deny_unknown_fields)]
273pub struct ActuatorStatus {
274    /// This message's identifier.
275    #[cfg_attr(feature = "uuid", builder(default = Id::generate()))]
276    pub message_id: Id,
277    /// The actuator this is about.
278    pub actuator_id: Id,
279    /// The mode that is active now.
280    pub active_operation_mode_id: Id,
281    /// Where in that mode's ranges the actuator is running, in `[0, 1]`.
282    pub operation_mode_factor: f64,
283    /// The mode that was active before. Required unless this is the first mode the
284    /// Resource Manager is aware of.
285    #[serde(skip_serializing_if = "Option::is_none")]
286    pub previous_operation_mode_id: Option<Id>,
287    /// When the move from the previous mode began. Required under the same condition.
288    #[serde(skip_serializing_if = "Option::is_none")]
289    pub transition_timestamp: Option<Timestamp>,
290}
291
292/// When one of an actuator's timers finishes.
293#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
294#[serde(deny_unknown_fields)]
295pub struct TimerStatus {
296    /// This message's identifier.
297    #[cfg_attr(feature = "uuid", builder(default = Id::generate()))]
298    pub message_id: Id,
299    /// The timer this is about.
300    pub timer_id: Id,
301    /// The actuator it belongs to.
302    pub actuator_id: Id,
303    /// When it finishes. In the past means it has finished; "if the timer was never
304    /// started, the value can be an arbitrary DateTimeStamp in the past".
305    pub finished_at: Timestamp,
306}
307
308/// The store's standing losses.
309#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
310#[serde(deny_unknown_fields)]
311pub struct LeakageBehaviour {
312    /// This message's identifier.
313    #[cfg_attr(feature = "uuid", builder(default = Id::generate()))]
314    pub message_id: Id,
315    /// When this becomes valid.
316    pub valid_from: Timestamp,
317    /// Contiguous bands of fill level and the rate lost in each.
318    pub elements: Vec<LeakageBehaviourElement>,
319}
320
321/// What the user is expected to take out of the store.
322#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
323#[serde(deny_unknown_fields)]
324pub struct UsageForecast {
325    /// This message's identifier.
326    #[cfg_attr(feature = "uuid", builder(default = Id::generate()))]
327    pub message_id: Id,
328    /// When the forecast starts.
329    pub start_time: Timestamp,
330    /// The slices, in chronological order.
331    pub elements: Vec<UsageForecastElement>,
332}
333
334/// Fill levels the CEM should aim for — an EV's departure charge, for instance.
335#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
336#[serde(deny_unknown_fields)]
337pub struct FillLevelTargetProfile {
338    /// This message's identifier.
339    #[cfg_attr(feature = "uuid", builder(default = Id::generate()))]
340    pub message_id: Id,
341    /// When the profile starts.
342    pub start_time: Timestamp,
343    /// The targets, in chronological order.
344    pub elements: Vec<FillLevelTargetProfileElement>,
345}
346
347/// The CEM asking an actuator to change mode.
348#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
349#[serde(deny_unknown_fields)]
350pub struct Instruction {
351    /// This message's identifier.
352    #[cfg_attr(feature = "uuid", builder(default = Id::generate()))]
353    pub message_id: Id,
354    /// The instruction's own identifier, which the [`InstructionStatusUpdate`] names.
355    ///
356    /// [`InstructionStatusUpdate`]: super::common::InstructionStatusUpdate
357    pub id: Id,
358    /// Which actuator.
359    pub actuator_id: Id,
360    /// Which mode it should move to.
361    ///
362    /// Note that this field is `operation_mode`, not `operation_mode_id` — FRBC is the
363    /// one control type that spells it without the suffix.
364    pub operation_mode: Id,
365    /// Where in the mode's ranges to run, in `[0, 1]`.
366    pub operation_mode_factor: f64,
367    /// When to start. In the past means as soon as possible.
368    pub execution_time: Timestamp,
369    /// Whether this is an abnormal-condition instruction.
370    pub abnormal_condition: bool,
371}
372
373#[cfg(test)]
374mod tests {
375    use super::*;
376    use crate::types::common::CommodityQuantity;
377
378    #[test]
379    fn the_ev_example_from_the_docs_round_trips() {
380        // docs `learn/examples/ev`, the charging operation mode verbatim.
381        let json = r#"{
382          "id": "om2",
383          "diagnostic_label": "Charging",
384          "elements": [
385            {
386              "fill_level_range": { "start_of_range": 0, "end_of_range": 100 },
387              "fill_rate": { "start_of_range": 0.00065, "end_of_range": 0.0051 },
388              "power_ranges": [
389                {
390                  "start_of_range": 1400,
391                  "end_of_range": 11000,
392                  "commodity_quantity": "ELECTRIC.POWER.3_PHASE_SYMMETRIC"
393                }
394              ]
395            }
396          ],
397          "abnormal_condition_only": false
398        }"#;
399        let mode: OperationMode = serde_json::from_str(json).unwrap();
400        assert_eq!(mode.id, "om2");
401        let element = mode.element_at(50.0).unwrap();
402        assert_eq!(element.power_ranges.len(), 1);
403        // The worked number from the documentation: at 1.4 kW the battery fills at
404        // 0.00065 % per second.
405        assert!((element.fill_rate.at_factor(0.0) - 0.000_65).abs() < 1e-12);
406        assert!((element.power_ranges.first().unwrap().at_factor(0.0) - 1400.0).abs() < 1e-9);
407        // No element covers a fill level outside the described band.
408        assert!(mode.element_at(101.0).is_none());
409    }
410
411    #[test]
412    fn a_small_fill_rate_survives_the_json_round_trip() {
413        // The value `hems` found: without serde_json's `float_roundtrip` feature this
414        // comes back as ...4445, and a learned correction drifts every time it is saved.
415        let original = 0.001_319_444_444_444_444_3_f64;
416        let element = LeakageBehaviourElement {
417            fill_level_range: NumberRange::new(0.0, 100.0),
418            leakage_rate: original,
419        };
420        let json = serde_json::to_string(&element).unwrap();
421        let back: LeakageBehaviourElement = serde_json::from_str(&json).unwrap();
422        assert_eq!(
423            back.leakage_rate.to_bits(),
424            original.to_bits(),
425            "fill rates must round-trip bit for bit"
426        );
427    }
428
429    #[test]
430    fn instruction_keeps_the_operation_mode_field_name() {
431        let instruction = Instruction {
432            message_id: Id::new_const("m1"),
433            id: Id::new_const("instr0"),
434            actuator_id: Id::new_const("actuator1"),
435            operation_mode: Id::new_const("om1"),
436            operation_mode_factor: 1.0,
437            execution_time: Timestamp::UNIX_EPOCH,
438            abnormal_condition: false,
439        };
440        let json = serde_json::to_string(&instruction).unwrap();
441        assert!(json.contains(r#""operation_mode":"om1""#));
442        assert!(!json.contains("operation_mode_id"));
443    }
444
445    #[test]
446    fn usage_and_leakage_rates_are_positive_when_the_level_falls() {
447        // A documented sign convention that is easy to get backwards, so it is asserted
448        // here as the place the meaning is recorded.
449        let e = UsageForecastElement::builder()
450            .duration(Duration::from_secs(900))
451            .usage_rate_expected(0.5)
452            .build();
453        assert!(
454            e.usage_rate_expected > 0.0,
455            "positive means the store drains"
456        );
457        let bands: Vec<_> = e.bands_ascending().iter().filter_map(|(_, v)| *v).collect();
458        assert_eq!(bands, alloc::vec![0.5]);
459    }
460
461    #[test]
462    fn power_range_interpolates_between_its_ends() {
463        let r = PowerRange::new(500.0, 2000.0, CommodityQuantity::ElectricPowerL1);
464        assert!((r.at_factor(1.0) - 2000.0).abs() < 1e-9);
465        assert_eq!(r.range(), NumberRange::new(500.0, 2000.0));
466    }
467}