Skip to main content

s2_kit/types/
pebc.rs

1//! Power Envelope Based Control — a device that cannot be driven, only bounded.
2//!
3//! Curtailable PV, a wallbox that can only be limited. The Resource Manager publishes
4//! [`PowerConstraints`] saying *within what bounds* the CEM may set a limit, and
5//! optionally an [`EnergyConstraint`] saying how much energy must still flow over a
6//! period. The CEM answers with an [`Instruction`] carrying the actual envelope.
7//!
8//! Remember the sign convention: production is negative. A 4 kWp array that may be
9//! curtailed freely has a `LOWER_LIMIT` range of `-4000..0` and an `UPPER_LIMIT` range of
10//! `0..0` (docs `learn/examples/pv`).
11
12use alloc::vec::Vec;
13
14use bon::Builder;
15use serde::{Deserialize, Serialize};
16
17use super::common::CommodityQuantity;
18use super::{Duration, Id, NumberRange, Timestamp};
19
20/// Which end of an envelope a constraint or limit describes.
21#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
22#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
23pub enum PowerEnvelopeLimitType {
24    /// The ceiling: the Resource Manager is asked to stay at or below it.
25    UpperLimit,
26    /// The floor: the Resource Manager is asked to stay at or above it.
27    LowerLimit,
28}
29
30/// What happens to the energy a limit prevents.
31#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
32#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
33pub enum PowerEnvelopeConsequenceType {
34    /// "the limited load or generated will be lost and not reappear in the future" — a
35    /// curtailed solar panel.
36    Vanish,
37    /// "the limited load or generation will be postponed to a later moment" — a deferred
38    /// charge.
39    Defer,
40}
41
42/// One bound the CEM is allowed to choose within.
43///
44/// Several ranges with the same quantity and limit type are explicitly allowed, and
45/// together they describe a union — a device that can curtail to 0 or to between 1 and
46/// 4 kW but not in between.
47#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, Builder)]
48#[serde(deny_unknown_fields)]
49pub struct AllowedLimitRange {
50    /// Which quantity this applies to.
51    pub commodity_quantity: CommodityQuantity,
52    /// Whether it bounds the ceiling or the floor.
53    pub limit_type: PowerEnvelopeLimitType,
54    /// The values the CEM may choose between, start at or below end.
55    pub range_boundary: NumberRange,
56    /// Whether this range may only be used during an abnormal condition.
57    pub abnormal_condition_only: bool,
58}
59
60/// One step of an envelope: a ceiling and a floor, for a while.
61#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
62#[serde(deny_unknown_fields)]
63pub struct PowerEnvelopeElement {
64    /// How long this step lasts.
65    pub duration: Duration,
66    /// The ceiling. Must be at or above `lower_limit`.
67    pub upper_limit: f64,
68    /// The floor. Must be at or below `upper_limit`.
69    pub lower_limit: f64,
70}
71
72impl PowerEnvelopeElement {
73    /// A step.
74    #[must_use]
75    pub const fn new(duration: Duration, lower_limit: f64, upper_limit: f64) -> Self {
76        Self {
77            duration,
78            upper_limit,
79            lower_limit,
80        }
81    }
82}
83
84/// A sequence of steps bounding one commodity quantity over time.
85#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
86#[serde(deny_unknown_fields)]
87pub struct PowerEnvelope {
88    /// Unique within the Resource Manager for the session.
89    pub id: Id,
90    /// Which quantity this envelope bounds.
91    pub commodity_quantity: CommodityQuantity,
92    /// The steps, in chronological order.
93    pub power_envelope_elements: Vec<PowerEnvelopeElement>,
94}
95
96impl PowerEnvelope {
97    /// The total time the envelope covers.
98    #[must_use]
99    pub fn total_duration(&self) -> Duration {
100        self.power_envelope_elements
101            .iter()
102            .fold(Duration::ZERO, |acc, e| {
103                acc.checked_add(e.duration).unwrap_or(acc)
104            })
105    }
106
107    /// The step in force `offset` after the envelope's start.
108    ///
109    /// `None` once the envelope has run out — at which point the Resource Manager is
110    /// unbounded again, which is why this is an `Option` rather than a clamped edge.
111    #[must_use]
112    pub fn element_at(&self, offset: Duration) -> Option<&PowerEnvelopeElement> {
113        let mut elapsed = 0u64;
114        let target = offset.as_millis();
115        for element in &self.power_envelope_elements {
116            let end = elapsed.saturating_add(element.duration.as_millis());
117            if target < end {
118                return Some(element);
119            }
120            elapsed = end;
121        }
122        None
123    }
124}
125
126/// The bounds within which the CEM may set an envelope.
127#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
128#[serde(deny_unknown_fields)]
129pub struct PowerConstraints {
130    /// This message's identifier.
131    #[cfg_attr(feature = "uuid", builder(default = Id::generate()))]
132    pub message_id: Id,
133    /// The constraints' own identifier, which an [`Instruction`] refers back to.
134    pub id: Id,
135    /// When they become valid.
136    pub valid_from: Timestamp,
137    /// When they stop being valid. Absent means open-ended.
138    #[serde(skip_serializing_if = "Option::is_none")]
139    pub valid_until: Option<Timestamp>,
140    /// What happens to energy a limit prevents.
141    pub consequence_type: PowerEnvelopeConsequenceType,
142    /// At least one `UPPER_LIMIT` range and one `LOWER_LIMIT` range.
143    pub allowed_limit_ranges: Vec<AllowedLimitRange>,
144}
145
146impl PowerConstraints {
147    /// Whether these constraints are in force at `now`.
148    #[must_use]
149    pub fn is_valid_at(&self, now: Timestamp) -> bool {
150        now >= self.valid_from && self.valid_until.is_none_or(|until| now < until)
151    }
152
153    /// The allowed ranges for one quantity and limit type.
154    pub fn ranges_for(
155        &self,
156        quantity: CommodityQuantity,
157        limit_type: PowerEnvelopeLimitType,
158    ) -> impl Iterator<Item = &AllowedLimitRange> {
159        self.allowed_limit_ranges
160            .iter()
161            .filter(move |r| r.commodity_quantity == quantity && r.limit_type == limit_type)
162    }
163}
164
165/// How much energy must still flow over a period, whatever envelope is applied.
166#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
167#[serde(deny_unknown_fields)]
168pub struct EnergyConstraint {
169    /// This message's identifier.
170    #[cfg_attr(feature = "uuid", builder(default = Id::generate()))]
171    pub message_id: Id,
172    /// The constraint's own identifier.
173    pub id: Id,
174    /// When it becomes valid.
175    pub valid_from: Timestamp,
176    /// When it stops being valid.
177    pub valid_until: Timestamp,
178    /// The highest average power over the period. Multiply by the period for energy.
179    pub upper_average_power: f64,
180    /// The lowest average power over the period.
181    ///
182    /// The schema's description for this field says it "Must be greater than or equal to
183    /// lower_average_power", which is a copy-paste of the line above it; it must of
184    /// course be *at most* `upper_average_power` (erratum E3).
185    pub lower_average_power: f64,
186    /// Which quantity both averages refer to.
187    pub commodity_quantity: CommodityQuantity,
188}
189
190/// The envelope the CEM wants followed.
191#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
192#[serde(deny_unknown_fields)]
193pub struct Instruction {
194    /// This message's identifier.
195    #[cfg_attr(feature = "uuid", builder(default = Id::generate()))]
196    pub message_id: Id,
197    /// The instruction's own identifier.
198    pub id: Id,
199    /// When the envelope starts. In the past means as soon as possible.
200    pub execution_time: Timestamp,
201    /// Whether this is an abnormal-condition instruction.
202    pub abnormal_condition: bool,
203    /// The [`PowerConstraints`] this envelope was chosen within.
204    pub power_constraints_id: Id,
205    /// At most one envelope per commodity quantity.
206    pub power_envelopes: Vec<PowerEnvelope>,
207}
208
209impl Instruction {
210    /// The envelope for one quantity, if this instruction carries one.
211    #[must_use]
212    pub fn envelope_for(&self, quantity: CommodityQuantity) -> Option<&PowerEnvelope> {
213        self.power_envelopes
214            .iter()
215            .find(|e| e.commodity_quantity == quantity)
216    }
217}
218
219#[cfg(test)]
220mod tests {
221    use super::*;
222
223    #[test]
224    fn the_pv_example_from_the_docs_parses() {
225        // docs `learn/examples/pv`, verbatim.
226        let json = r#"{
227          "message_id": "aaaaaaaa-0000-0000-0000-000000000001",
228          "id": "powerConstraint1",
229          "valid_from": "2024-08-24T14:15:22Z",
230          "valid_until": "2024-08-25T14:15:22Z",
231          "consequence_type": "VANISH",
232          "allowed_limit_ranges": [
233            {
234              "commodity_quantity": "ELECTRIC.POWER.L1",
235              "limit_type": "LOWER_LIMIT",
236              "range_boundary": { "start_of_range": -4000, "end_of_range": 0 },
237              "abnormal_condition_only": false
238            },
239            {
240              "commodity_quantity": "ELECTRIC.POWER.L1",
241              "limit_type": "UPPER_LIMIT",
242              "range_boundary": { "start_of_range": 0, "end_of_range": 0 },
243              "abnormal_condition_only": false
244            }
245          ]
246        }"#;
247        let c: PowerConstraints = serde_json::from_str(json).unwrap();
248        assert_eq!(c.id, "powerConstraint1");
249        assert_eq!(c.consequence_type, PowerEnvelopeConsequenceType::Vanish);
250        let lower: Vec<_> = c
251            .ranges_for(
252                CommodityQuantity::ElectricPowerL1,
253                PowerEnvelopeLimitType::LowerLimit,
254            )
255            .collect();
256        assert_eq!(lower.len(), 1);
257        // Production is negative: the array may be curtailed anywhere in -4000..0.
258        assert!(lower[0].range_boundary.contains(-2000.0));
259        assert!(!lower[0].range_boundary.contains(-5000.0));
260    }
261
262    #[test]
263    fn validity_window_is_half_open_and_tolerates_an_open_end() {
264        let from: Timestamp = "2024-08-24T14:00:00Z".parse().unwrap();
265        let until: Timestamp = "2024-08-24T15:00:00Z".parse().unwrap();
266        let c = PowerConstraints {
267            message_id: Id::new_const("m1"),
268            id: Id::new_const("pc1"),
269            valid_from: from,
270            valid_until: Some(until),
271            consequence_type: PowerEnvelopeConsequenceType::Vanish,
272            allowed_limit_ranges: Vec::new(),
273        };
274        assert!(!c.is_valid_at("2024-08-24T13:59:59Z".parse().unwrap()));
275        assert!(c.is_valid_at(from));
276        assert!(c.is_valid_at("2024-08-24T14:59:59Z".parse().unwrap()));
277        assert!(!c.is_valid_at(until));
278
279        let open = PowerConstraints {
280            valid_until: None,
281            ..c
282        };
283        assert!(open.is_valid_at("2099-01-01T00:00:00Z".parse().unwrap()));
284    }
285
286    #[test]
287    fn an_envelope_runs_out_rather_than_clamping() {
288        let e = PowerEnvelope {
289            id: Id::new_const("pe1"),
290            commodity_quantity: CommodityQuantity::ElectricPowerL1,
291            power_envelope_elements: alloc::vec![
292                PowerEnvelopeElement::new(Duration::from_secs(60), -2000.0, 0.0),
293                PowerEnvelopeElement::new(Duration::from_secs(60), -1000.0, 0.0),
294            ],
295        };
296        assert_eq!(e.total_duration(), Duration::from_secs(120));
297        assert_eq!(e.element_at(Duration::ZERO).unwrap().lower_limit, -2000.0);
298        assert_eq!(
299            e.element_at(Duration::from_secs(59)).unwrap().lower_limit,
300            -2000.0
301        );
302        assert_eq!(
303            e.element_at(Duration::from_secs(60)).unwrap().lower_limit,
304            -1000.0
305        );
306        // Past the end the Resource Manager is unbounded again, which is a different
307        // thing from "bounded by the last step for ever".
308        assert!(e.element_at(Duration::from_secs(120)).is_none());
309    }
310}