Skip to main content

s2_kit/model/
mod.rs

1//! The virtual device: what an instruction actually *means*.
2//!
3//! S2's three state-machine control types describe an abstract device, and an
4//! instruction names a state and a number between zero and one. Turning that into watts
5//! needs the description that was sent — the S2 documentation, *Operation modes* gives the
6//! arithmetic: `power = (end − start) × factor + start`.
7//!
8//! Both roles need exactly the same arithmetic, and they must not disagree about it. A
9//! Resource Manager reads an instruction and works out what its hardware should do; a
10//! Customer Energy Manager works out what to ask for, and later reconciles the
11//! measurement it gets back. Two implementations of one formula is how those two stop
12//! agreeing, so there is one here and both sides call it.
13//!
14//! Everything in this module is a pure function of a description, an instruction and —
15//! where a rate depends on it — a fill level. Nothing reads a clock.
16//!
17//! ```
18//! use s2_kit::prelude::*;
19//! use s2_kit::model;
20//!
21//! // The heat pump from docs `learn/examples/heat-pump`: 500 W to 2000 W.
22//! let range = PowerRange::new(500.0, 2000.0, CommodityQuantity::ElectricPowerL1);
23//! assert_eq!(model::interpolate(&[range], 0.0)[0].value, 500.0);
24//! assert_eq!(model::interpolate(&[range], 1.0)[0].value, 2000.0);
25//! assert_eq!(model::interpolate(&[range], 0.5)[0].value, 1250.0);
26//! ```
27
28pub mod explain;
29
30use alloc::vec::Vec;
31
32use crate::types::common::{
33    CommodityQuantity, NumberRange, PowerRange, PowerValue, Timer, Transition,
34};
35use crate::types::{Duration, Id, Timestamp, ddbc, frbc, ombc, pebc, ppbc};
36use crate::validate::TimerState;
37
38pub use explain::{Explanation, explain};
39
40/// An operation-mode factor: a number in `[0, 1]`.
41///
42/// The wire type is a bare `f64`, because a message carrying 1.3 has to be
43/// representable so the validator can name it. This is the checked form the arithmetic
44/// uses.
45#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
46pub struct Factor(f64);
47
48impl Factor {
49    /// Fully at the start of every range.
50    pub const ZERO: Self = Self(0.0);
51    /// Fully at the end of every range.
52    pub const ONE: Self = Self(1.0);
53
54    /// A factor, if `value` is within `[0, 1]`.
55    #[must_use]
56    pub fn try_new(value: f64) -> Option<Self> {
57        (value.is_finite() && (0.0..=1.0).contains(&value)).then_some(Self(value))
58    }
59
60    /// A factor, clamping anything outside `[0, 1]`.
61    ///
62    /// For a Resource Manager that has decided to be generous with a peer that is
63    /// slightly out of range. The validator will still have reported it.
64    #[must_use]
65    pub fn clamping(value: f64) -> Self {
66        if value.is_nan() {
67            Self(0.0)
68        } else {
69            Self(value.clamp(0.0, 1.0))
70        }
71    }
72
73    /// The number.
74    #[must_use]
75    pub const fn get(self) -> f64 {
76        self.0
77    }
78}
79
80/// A ceiling and a floor, as a `PEBC.Instruction` sets them.
81#[derive(Debug, Clone, Copy, PartialEq)]
82pub struct Limits {
83    /// The most the resource may consume (or the least it may produce).
84    pub upper: f64,
85    /// The least the resource may consume (or the most it may produce).
86    pub lower: f64,
87}
88
89/// Why an instruction could not be read against the description that was sent.
90#[derive(Debug, Clone, PartialEq, thiserror::Error)]
91#[non_exhaustive]
92pub enum ResolveError {
93    /// The instruction names an actuator the description does not have.
94    #[error("{0} is not an actuator of this system")]
95    UnknownActuator(Id),
96    /// The instruction names an operation mode the actuator does not have.
97    #[error("{0} is not an operation mode of that actuator")]
98    UnknownOperationMode(Id),
99    /// The instruction names a profile, container or sequence that was never published.
100    #[error("{0} was never published")]
101    UnknownSequence(Id),
102    /// The factor is outside `[0, 1]`.
103    #[error("operation mode factor {0} is outside [0, 1]")]
104    BadFactor(f64),
105    /// No element of the operation mode covers the present fill level.
106    #[error("no element of this operation mode covers a fill level of {0}")]
107    FillLevelNotCovered(f64),
108}
109
110/// The power a set of ranges implies at a factor.
111///
112/// One value per commodity quantity, in the order the ranges were given.
113#[must_use]
114pub fn interpolate(ranges: &[PowerRange], factor: f64) -> Vec<PowerValue> {
115    ranges
116        .iter()
117        .map(|r| PowerValue::new(r.commodity_quantity, r.at_factor(factor)))
118        .collect()
119}
120
121/// The factor that produces `power` for `quantity`, if the ranges determine one.
122#[must_use]
123pub fn factor_for_power(
124    ranges: &[PowerRange],
125    quantity: CommodityQuantity,
126    power: f64,
127) -> Option<f64> {
128    ranges
129        .iter()
130        .find(|r| r.commodity_quantity == quantity)
131        .and_then(|r| r.range().factor_of(power))
132}
133
134/// Which timers block a move from `from` to `to`, given what is known about them.
135///
136/// A timer nobody has reported on does **not** block: `S2J messages/*.TimerStatus`
137/// says an unstarted timer carries "an arbitrary DateTimeStamp in the past", so silence
138/// tells us nothing, and refusing on silence would stall a session on a timer that was
139/// never started.
140/// `actuator` scopes the lookup: timer identifiers are unique only within the actuator
141/// description that declares them, so `Id::NIL` is OMBC's stand-in for "the system
142/// description itself".
143#[must_use]
144pub fn blocking_timers(
145    transitions: &[Transition],
146    from: &Id,
147    to: &Id,
148    actuator: &Id,
149    known: &[TimerState],
150    now: Timestamp,
151) -> Vec<Id> {
152    transitions
153        .iter()
154        .find(|t| t.from == *from && t.to == *to)
155        .map(|t| {
156            t.blocking_timers
157                .iter()
158                .filter(|id| {
159                    known.iter().any(|state| {
160                        state.actuator == *actuator
161                            && state.timer == **id
162                            && state.finished_at > now
163                    })
164                })
165                .copied()
166                .collect()
167        })
168        .unwrap_or_default()
169}
170
171/// How long a transition takes to take effect. Absent means negligible.
172#[must_use]
173pub fn transition_duration(transitions: &[Transition], from: &Id, to: &Id) -> Duration {
174    transitions
175        .iter()
176        .find(|t| t.from == *from && t.to == *to)
177        .and_then(|t| t.transition_duration)
178        .unwrap_or(Duration::ZERO)
179}
180
181/// The timer with this identifier, for a diagnostic.
182#[must_use]
183pub fn timer_label<'a>(timers: &'a [Timer], id: &Id) -> Option<&'a str> {
184    timers
185        .iter()
186        .find(|t| t.id == *id)
187        .and_then(|t| t.diagnostic_label.as_deref())
188}
189
190// ---------------------------------------------------------------------------
191// Fill Rate Based Control
192// ---------------------------------------------------------------------------
193
194/// What an `FRBC.Instruction` means, read against the system description.
195#[derive(Debug, Clone, PartialEq)]
196pub struct FrbcResolution<'a> {
197    /// The actuator it addresses.
198    pub actuator: &'a frbc::ActuatorDescription,
199    /// The operation mode it selects.
200    pub mode: &'a frbc::OperationMode,
201    /// The element of that mode which applies at the present fill level, when one is
202    /// known.
203    pub element: Option<&'a frbc::OperationModeElement>,
204    /// The factor, checked.
205    pub factor: Factor,
206    /// The power that factor implies, one value per commodity quantity.
207    pub power: Vec<PowerValue>,
208    /// How fast the store fills, in fill-level units per second. Positive fills.
209    pub fill_rate: Option<f64>,
210    /// Whether the mode may only be used during an abnormal condition.
211    pub abnormal_only: bool,
212}
213
214/// Read an `FRBC.Instruction` against the description that was sent.
215///
216/// `fill_level` selects which element of the operation mode applies; without it the
217/// power is still resolved from the first element, because every element of a mode
218/// covers the same commodity quantities, but `fill_rate` is left unanswered.
219pub fn resolve_frbc<'a>(
220    system: &'a frbc::SystemDescription,
221    instruction: &frbc::Instruction,
222    fill_level: Option<f64>,
223) -> Result<FrbcResolution<'a>, ResolveError> {
224    let actuator = system
225        .actuator(&instruction.actuator_id)
226        .ok_or(ResolveError::UnknownActuator(instruction.actuator_id))?;
227    let mode = actuator.operation_mode(&instruction.operation_mode).ok_or(
228        ResolveError::UnknownOperationMode(instruction.operation_mode),
229    )?;
230    let factor = Factor::try_new(instruction.operation_mode_factor)
231        .ok_or(ResolveError::BadFactor(instruction.operation_mode_factor))?;
232
233    let element = match fill_level {
234        Some(level) => Some(
235            mode.element_at(level)
236                .ok_or(ResolveError::FillLevelNotCovered(level))?,
237        ),
238        None => mode.elements.first(),
239    };
240
241    let power = element.map(|e| interpolate(&e.power_ranges, factor.get()));
242    Ok(FrbcResolution {
243        actuator,
244        mode,
245        element,
246        factor,
247        power: power.unwrap_or_default(),
248        fill_rate: element.map(|e| e.fill_rate.at_factor(factor.get())),
249        abnormal_only: mode.abnormal_condition_only,
250    })
251}
252
253/// Where the fill level ends up after `duration` in one operation mode.
254///
255/// Integrates the mode's fill rate, the storage's leakage and the user's expected usage
256/// over one step, using the element that applies at each moment. Leakage and usage are
257/// *positive when the level falls*, which is the standard's convention and the one thing
258/// about FRBC that is easiest to get backwards.
259///
260/// Deliberately a simple forward integration: the caller chooses the step, and a CEM
261/// that wants more accuracy calls it with smaller ones.
262#[must_use]
263pub fn project_fill_level(
264    mode: &frbc::OperationMode,
265    factor: Factor,
266    from: f64,
267    duration: Duration,
268    leakage: Option<&[frbc::LeakageBehaviourElement]>,
269    usage_rate: Option<f64>,
270) -> f64 {
271    let seconds = duration.as_secs_f64();
272    if seconds <= 0.0 {
273        return from;
274    }
275    let fill_rate = mode
276        .element_at(from)
277        .map_or(0.0, |e| e.fill_rate.at_factor(factor.get()));
278    let leak = leakage
279        .and_then(|elements| {
280            elements
281                .iter()
282                .find(|e| e.fill_level_range.contains(from))
283                .map(|e| e.leakage_rate)
284        })
285        .unwrap_or(0.0);
286    let usage = usage_rate.unwrap_or(0.0);
287    from + (fill_rate - leak - usage) * seconds
288}
289
290// ---------------------------------------------------------------------------
291// Operation Mode Based Control
292// ---------------------------------------------------------------------------
293
294/// What an `OMBC.Instruction` means.
295#[derive(Debug, Clone, PartialEq)]
296pub struct OmbcResolution<'a> {
297    /// The mode it selects.
298    pub mode: &'a ombc::OperationMode,
299    /// The factor, checked.
300    pub factor: Factor,
301    /// The power that factor implies.
302    pub power: Vec<PowerValue>,
303    /// Whether the mode may only be used during an abnormal condition.
304    pub abnormal_only: bool,
305}
306
307/// Read an `OMBC.Instruction` against the description that was sent.
308pub fn resolve_ombc<'a>(
309    system: &'a ombc::SystemDescription,
310    instruction: &ombc::Instruction,
311) -> Result<OmbcResolution<'a>, ResolveError> {
312    let mode = system
313        .operation_mode(&instruction.operation_mode_id)
314        .ok_or(ResolveError::UnknownOperationMode(
315            instruction.operation_mode_id,
316        ))?;
317    let factor = Factor::try_new(instruction.operation_mode_factor)
318        .ok_or(ResolveError::BadFactor(instruction.operation_mode_factor))?;
319    Ok(OmbcResolution {
320        mode,
321        factor,
322        power: interpolate(&mode.power_ranges, factor.get()),
323        abnormal_only: mode.abnormal_condition_only,
324    })
325}
326
327// ---------------------------------------------------------------------------
328// Demand Driven Based Control
329// ---------------------------------------------------------------------------
330
331/// What a `DDBC.Instruction` means.
332#[derive(Debug, Clone, PartialEq)]
333pub struct DdbcResolution<'a> {
334    /// The actuator it addresses.
335    pub actuator: &'a ddbc::ActuatorDescription,
336    /// The mode it selects.
337    pub mode: &'a ddbc::OperationMode,
338    /// The factor, checked.
339    pub factor: Factor,
340    /// The power that factor implies.
341    pub power: Vec<PowerValue>,
342    /// The supply rate the mode delivers at that factor — what the CEM matches against
343    /// the demand.
344    pub supply_rate: f64,
345    /// Whether the mode may only be used during an abnormal condition.
346    pub abnormal_only: bool,
347}
348
349/// Read a `DDBC.Instruction` against the description that was sent.
350pub fn resolve_ddbc<'a>(
351    system: &'a ddbc::SystemDescription,
352    instruction: &ddbc::Instruction,
353) -> Result<DdbcResolution<'a>, ResolveError> {
354    let actuator = system
355        .actuator(&instruction.actuator_id)
356        .ok_or(ResolveError::UnknownActuator(instruction.actuator_id))?;
357    let mode = actuator
358        .operation_mode(&instruction.operation_mode_id)
359        .ok_or(ResolveError::UnknownOperationMode(
360            instruction.operation_mode_id,
361        ))?;
362    let factor = Factor::try_new(instruction.operation_mode_factor)
363        .ok_or(ResolveError::BadFactor(instruction.operation_mode_factor))?;
364    Ok(DdbcResolution {
365        actuator,
366        mode,
367        factor,
368        power: interpolate(&mode.power_ranges, factor.get()),
369        supply_rate: mode.supply_range.at_factor(factor.get()),
370        abnormal_only: mode.abnormal_condition_only,
371    })
372}
373
374/// Which actuators and modes together meet a demand, cheapest supply first.
375///
376/// A convenience for a CEM driving a hybrid system: it answers "what combination of
377/// modes supplies at least this much?" without prescribing a policy.
378#[must_use]
379pub fn supply_range_of(actuator: &ddbc::ActuatorDescription) -> NumberRange {
380    let mut low = f64::INFINITY;
381    let mut high = f64::NEG_INFINITY;
382    for mode in &actuator.operation_modes {
383        let (a, b) = mode.supply_range.ordered();
384        low = low.min(a);
385        high = high.max(b);
386    }
387    if low.is_finite() && high.is_finite() {
388        NumberRange::new(low, high)
389    } else {
390        NumberRange::new(0.0, 0.0)
391    }
392}
393
394// ---------------------------------------------------------------------------
395// Power Envelope Based Control
396// ---------------------------------------------------------------------------
397
398/// The limits a `PEBC.Instruction` puts on one quantity at a moment.
399///
400/// `None` when the instruction says nothing about that quantity at that moment — either
401/// it carries no envelope for it, or the envelope has run out. An envelope that has run
402/// out leaves the resource unbounded again, which is a different thing from being held
403/// at its last step for ever.
404#[must_use]
405pub fn limits_at(
406    instruction: &pebc::Instruction,
407    quantity: CommodityQuantity,
408    at: Timestamp,
409) -> Option<Limits> {
410    let envelope = instruction.envelope_for(quantity)?;
411    // `S2J messages/PEBC.Instruction.execution_time`: in the past means "as soon as
412    // possible", so an envelope whose execution time has passed is measured from then.
413    let offset = at.checked_duration_since(instruction.execution_time)?;
414    envelope.element_at(offset).map(|e| Limits {
415        upper: e.upper_limit,
416        lower: e.lower_limit,
417    })
418}
419
420/// Whether a power obeys the limits.
421#[must_use]
422pub fn within(limits: Limits, power: f64) -> bool {
423    power >= limits.lower && power <= limits.upper
424}
425
426/// The envelope the resource is under for each quantity the instruction bounds.
427#[must_use]
428pub fn all_limits_at(
429    instruction: &pebc::Instruction,
430    at: Timestamp,
431) -> Vec<(CommodityQuantity, Limits)> {
432    instruction
433        .power_envelopes
434        .iter()
435        .filter_map(|e| {
436            limits_at(instruction, e.commodity_quantity, at).map(|l| (e.commodity_quantity, l))
437        })
438        .collect()
439}
440
441/// The average power an energy constraint demands over its window, as a range.
442#[must_use]
443pub fn energy_window(constraint: &pebc::EnergyConstraint) -> Option<(Duration, NumberRange)> {
444    let window = constraint
445        .valid_until
446        .checked_duration_since(constraint.valid_from)?;
447    Some((
448        window,
449        NumberRange::new(
450            constraint.lower_average_power,
451            constraint.upper_average_power,
452        ),
453    ))
454}
455
456// ---------------------------------------------------------------------------
457// Power Profile Based Control
458// ---------------------------------------------------------------------------
459
460/// What a PPBC instruction means.
461#[derive(Debug, Clone, PartialEq)]
462pub struct PpbcResolution<'a> {
463    /// The profile.
464    pub profile: &'a ppbc::PowerProfileDefinition,
465    /// The container within it.
466    pub container: &'a ppbc::PowerSequenceContainer,
467    /// The sequence that was chosen.
468    pub sequence: &'a ppbc::PowerSequence,
469    /// How long that sequence takes.
470    pub duration: Duration,
471}
472
473/// Read a PPBC instruction's three identifiers against the profile that was published.
474pub fn resolve_ppbc<'a>(
475    profiles: &'a [ppbc::PowerProfileDefinition],
476    profile_id: &Id,
477    container_id: &Id,
478    sequence_id: &Id,
479) -> Result<PpbcResolution<'a>, ResolveError> {
480    let profile = profiles
481        .iter()
482        .find(|p| p.id == *profile_id)
483        .ok_or(ResolveError::UnknownSequence(*profile_id))?;
484    let (container, sequence) = profile
485        .resolve(container_id, sequence_id)
486        .ok_or(ResolveError::UnknownSequence(*sequence_id))?;
487    Ok(PpbcResolution {
488        profile,
489        container,
490        sequence,
491        duration: sequence.total_duration(),
492    })
493}
494
495/// The power a sequence draws `offset` after it started.
496#[must_use]
497pub fn sequence_power_at(
498    sequence: &ppbc::PowerSequence,
499    offset: Duration,
500) -> Option<&[crate::types::common::PowerForecastValue]> {
501    let mut elapsed = 0u64;
502    let target = offset.as_millis();
503    for element in &sequence.elements {
504        let end = elapsed.saturating_add(element.duration.as_millis());
505        if target < end {
506            return Some(&element.power_values);
507        }
508        elapsed = end;
509    }
510    None
511}
512
513/// Where one chosen sequence has to fall for the whole profile to fit its window.
514#[derive(Debug, Clone, PartialEq)]
515pub struct SequenceWindow {
516    /// The container the choice was made in.
517    pub container: Id,
518    /// The sequence chosen from it.
519    pub sequence: Id,
520    /// The earliest it may start: the profile opens, or its predecessor finishes.
521    pub earliest_start: Timestamp,
522    /// The latest it may start and still leave room for every sequence after it.
523    pub latest_start: Timestamp,
524    /// How long it runs.
525    pub duration: Duration,
526    /// The longest it may idle after its predecessor finished, when the sequence says.
527    ///
528    /// This is a constraint *between* two starts, not a bound on this one, so it cannot
529    /// be folded into `latest_start` — see [`schedule`]. [`starts_are_feasible`] is what
530    /// applies it.
531    pub max_pause_before: Option<Duration>,
532}
533
534impl SequenceWindow {
535    /// Whether there is any start time at all that works.
536    #[must_use]
537    pub fn is_feasible(&self) -> bool {
538        self.earliest_start <= self.latest_start
539    }
540}
541
542/// When each chosen sequence may run, given that containers run in the order the profile
543/// lists them.
544///
545/// `S2J messages/PPBC.PowerProfileDefinition.power_sequences_containers`:
546/// "PPBC.PowerSequenceContainers must be placed in chronological order." A container has
547/// no timestamp, so that is an interpretation rather than a checkable rule: container 0's
548/// chosen sequence runs, then container 1's, all inside `start_time .. end_time`. The
549/// latest a sequence may start is therefore `end_time` minus everything still to come,
550/// not minus its own duration (D32).
551///
552/// [`max_pause_before`](crate::types::ppbc::PowerSequence::max_pause_before) is carried on
553/// each window but not folded into it: it bounds the gap between two starts, so it can
554/// only reject a schedule. [`starts_are_feasible`] applies it.
555///
556/// `chosen` names one sequence per container, in container order; every container must
557/// appear.
558pub fn schedule(
559    profile: &ppbc::PowerProfileDefinition,
560    chosen: &[(Id, Id)],
561) -> Result<Vec<SequenceWindow>, ResolveError> {
562    if chosen.len() != profile.power_sequence_containers.len() {
563        // Naming the first container with no choice is more useful than a count.
564        let missing = profile
565            .power_sequence_containers
566            .iter()
567            .find(|c| !chosen.iter().any(|(container, _)| container == &c.id))
568            .map_or(profile.id, |c| c.id);
569        return Err(ResolveError::UnknownSequence(missing));
570    }
571
572    let mut resolved = Vec::with_capacity(chosen.len());
573    for (container_id, sequence_id) in chosen {
574        let (container, sequence) = profile
575            .resolve(container_id, sequence_id)
576            .ok_or(ResolveError::UnknownSequence(*sequence_id))?;
577        resolved.push((container, sequence));
578    }
579
580    // Backwards: how much time everything from `k` onwards needs.
581    let mut tail = Vec::with_capacity(resolved.len());
582    let mut running = Duration::ZERO;
583    for (_, sequence) in resolved.iter().rev() {
584        running = running
585            .checked_add(sequence.total_duration())
586            .ok_or(ResolveError::UnknownSequence(profile.id))?;
587        tail.push(running);
588    }
589    tail.reverse();
590
591    let mut out: Vec<SequenceWindow> = Vec::with_capacity(resolved.len());
592    for (index, (container, sequence)) in resolved.iter().enumerate() {
593        let duration = sequence.total_duration();
594        let needed = tail.get(index).copied().unwrap_or(duration);
595        let earliest_start = match out.last() {
596            None => profile.start_time,
597            Some(previous) => previous
598                .earliest_start
599                .checked_add(previous.duration)
600                .unwrap_or(previous.earliest_start),
601        };
602        let latest_start = profile
603            .end_time
604            .checked_sub(needed)
605            .unwrap_or(profile.start_time);
606
607        out.push(SequenceWindow {
608            container: container.id,
609            sequence: sequence.id,
610            earliest_start,
611            latest_start,
612            duration,
613            max_pause_before: sequence.max_pause_before,
614        });
615    }
616    Ok(out)
617}
618
619/// Whether a set of choices can be run inside the profile's window at all.
620///
621/// The question a CEM asks before it commits to a `PPBC.ScheduleInstruction`.
622#[must_use]
623pub fn is_schedulable(profile: &ppbc::PowerProfileDefinition, chosen: &[(Id, Id)]) -> bool {
624    schedule(profile, chosen).is_ok_and(|w| w.iter().all(SequenceWindow::is_feasible))
625}
626
627/// Why a concrete set of start times will not do.
628#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
629#[non_exhaustive]
630pub enum ScheduleProblem {
631    /// One start time per chosen sequence is needed, and a different number was given.
632    #[error("{given} start times for {needed} sequences")]
633    WrongCount {
634        /// How many were given.
635        given: usize,
636        /// How many were needed.
637        needed: usize,
638    },
639    /// A sequence starts before the profile opens, or before its predecessor finishes.
640    #[error("sequence {sequence} starts at {at}, before {not_before}")]
641    TooEarly {
642        /// Which sequence.
643        sequence: Id,
644        /// When it was asked to start.
645        at: Timestamp,
646        /// The earliest it may.
647        not_before: Timestamp,
648    },
649    /// A sequence would still be running when the profile's window closes.
650    #[error("sequence {sequence} starts at {at} and would finish after {end_time}")]
651    Overruns {
652        /// Which sequence.
653        sequence: Id,
654        /// When it was asked to start.
655        at: Timestamp,
656        /// When the window closes.
657        end_time: Timestamp,
658    },
659    /// The device would idle longer than the sequence allows.
660    ///
661    /// `S2J schemas/PPBC.PowerSequence.max_pause_before`.
662    #[error("sequence {sequence} idles {idle} after the previous one, but allows only {allowed}")]
663    PauseTooLong {
664        /// Which sequence.
665        sequence: Id,
666        /// How long the gap is.
667        idle: Duration,
668        /// How long it may be.
669        allowed: Duration,
670    },
671}
672
673/// Whether concrete start times run the profile as the standard says it must be run.
674///
675/// Checks what [`schedule`] cannot: that the sequences are in order, that none overlaps
676/// its predecessor, that the last one finishes inside the window, and that no gap exceeds
677/// the following sequence's `max_pause_before`. `starts` is one instant per entry of
678/// `chosen`, in the same order.
679pub fn starts_are_feasible(
680    profile: &ppbc::PowerProfileDefinition,
681    chosen: &[(Id, Id)],
682    starts: &[Timestamp],
683) -> Result<(), ScheduleProblem> {
684    let windows = schedule(profile, chosen).map_err(|_| ScheduleProblem::WrongCount {
685        given: starts.len(),
686        needed: chosen.len(),
687    })?;
688    if starts.len() != windows.len() {
689        return Err(ScheduleProblem::WrongCount {
690            given: starts.len(),
691            needed: windows.len(),
692        });
693    }
694
695    let mut previous_end: Option<Timestamp> = None;
696    for (window, start) in windows.iter().zip(starts) {
697        let not_before = previous_end.unwrap_or(profile.start_time);
698        if *start < not_before {
699            return Err(ScheduleProblem::TooEarly {
700                sequence: window.sequence,
701                at: *start,
702                not_before,
703            });
704        }
705        if let (Some(end), Some(allowed)) = (previous_end, window.max_pause_before) {
706            let idle = start.saturating_duration_since(end);
707            if idle > allowed {
708                return Err(ScheduleProblem::PauseTooLong {
709                    sequence: window.sequence,
710                    idle,
711                    allowed,
712                });
713            }
714        }
715        let end = start
716            .checked_add(window.duration)
717            .unwrap_or(profile.end_time);
718        if end > profile.end_time {
719            return Err(ScheduleProblem::Overruns {
720                sequence: window.sequence,
721                at: *start,
722                end_time: profile.end_time,
723            });
724        }
725        previous_end = Some(end);
726    }
727    Ok(())
728}
729
730#[cfg(test)]
731mod tests {
732    use super::*;
733    use crate::types::common::Commodity;
734    use alloc::string::ToString;
735    use alloc::vec;
736
737    fn charging_mode() -> frbc::OperationMode {
738        // docs `learn/examples/ev`: 1.4 kW to 11 kW, filling at 0.00065 to 0.0051 %/s.
739        frbc::OperationMode {
740            id: Id::new_const("om2"),
741            diagnostic_label: None,
742            elements: vec![frbc::OperationModeElement {
743                fill_level_range: NumberRange::new(0.0, 100.0),
744                fill_rate: NumberRange::new(0.000_65, 0.0051),
745                power_ranges: vec![PowerRange::new(
746                    1400.0,
747                    11_000.0,
748                    CommodityQuantity::ElectricPower3PhaseSymmetric,
749                )],
750                running_costs: None,
751            }],
752            abnormal_condition_only: false,
753        }
754    }
755
756    fn ev_system() -> frbc::SystemDescription {
757        frbc::SystemDescription {
758            message_id: Id::new_const("m1"),
759            valid_from: Timestamp::UNIX_EPOCH,
760            actuators: vec![frbc::ActuatorDescription {
761                id: Id::new_const("actuator1"),
762                diagnostic_label: None,
763                supported_commodities: vec![Commodity::Electricity],
764                operation_modes: vec![
765                    frbc::OperationMode {
766                        id: Id::new_const("om1"),
767                        diagnostic_label: None,
768                        elements: vec![frbc::OperationModeElement {
769                            fill_level_range: NumberRange::new(0.0, 100.0),
770                            fill_rate: NumberRange::exactly(0.0),
771                            power_ranges: vec![PowerRange::exactly(
772                                0.0,
773                                CommodityQuantity::ElectricPower3PhaseSymmetric,
774                            )],
775                            running_costs: None,
776                        }],
777                        abnormal_condition_only: false,
778                    },
779                    charging_mode(),
780                ],
781                transitions: vec![
782                    Transition::simple(
783                        Id::new_const("transition1"),
784                        Id::new_const("om1"),
785                        Id::new_const("om2"),
786                    ),
787                    Transition::simple(
788                        Id::new_const("transition2"),
789                        Id::new_const("om2"),
790                        Id::new_const("om1"),
791                    ),
792                ],
793                timers: vec![],
794            }],
795            storage: frbc::StorageDescription {
796                diagnostic_label: None,
797                fill_level_label: Some("EV Battery SoC".into()),
798                provides_leakage_behaviour: false,
799                provides_fill_level_target_profile: true,
800                provides_usage_forecast: false,
801                fill_level_range: NumberRange::new(0.0, 100.0),
802            },
803        }
804    }
805
806    fn charge_at(factor: f64) -> frbc::Instruction {
807        frbc::Instruction {
808            message_id: Id::new_const("m2"),
809            id: Id::new_const("instr0"),
810            actuator_id: Id::new_const("actuator1"),
811            operation_mode: Id::new_const("om2"),
812            operation_mode_factor: factor,
813            execution_time: Timestamp::UNIX_EPOCH,
814            abnormal_condition: false,
815        }
816    }
817
818    #[test]
819    fn an_instruction_resolves_to_the_power_the_documentation_says() {
820        let system = ev_system();
821        let resolved = resolve_frbc(&system, &charge_at(0.0), Some(50.0)).unwrap();
822        assert_eq!(resolved.mode.id, "om2");
823        assert!((resolved.power[0].value - 1400.0).abs() < 1e-9);
824        assert!((resolved.fill_rate.unwrap() - 0.000_65).abs() < 1e-12);
825
826        let resolved = resolve_frbc(&system, &charge_at(1.0), Some(50.0)).unwrap();
827        assert!((resolved.power[0].value - 11_000.0).abs() < 1e-9);
828        assert!((resolved.fill_rate.unwrap() - 0.0051).abs() < 1e-12);
829
830        // Halfway is halfway, in both quantities.
831        let resolved = resolve_frbc(&system, &charge_at(0.5), Some(50.0)).unwrap();
832        assert!((resolved.power[0].value - 6200.0).abs() < 1e-9);
833    }
834
835    #[test]
836    fn resolution_refuses_what_was_never_described() {
837        let system = ev_system();
838        let mut bad = charge_at(0.5);
839        bad.actuator_id = Id::new_const("nope");
840        assert_eq!(
841            resolve_frbc(&system, &bad, None),
842            Err(ResolveError::UnknownActuator(Id::new_const("nope")))
843        );
844
845        let mut bad = charge_at(0.5);
846        bad.operation_mode = Id::new_const("om9");
847        assert_eq!(
848            resolve_frbc(&system, &bad, None),
849            Err(ResolveError::UnknownOperationMode(Id::new_const("om9")))
850        );
851
852        assert_eq!(
853            resolve_frbc(&system, &charge_at(1.3), None),
854            Err(ResolveError::BadFactor(1.3))
855        );
856
857        // A fill level no element covers is a description that does not answer the
858        // question, not a fill rate of zero.
859        assert_eq!(
860            resolve_frbc(&system, &charge_at(0.5), Some(150.0)),
861            Err(ResolveError::FillLevelNotCovered(150.0))
862        );
863    }
864
865    #[test]
866    fn the_factor_and_the_power_are_inverses() {
867        let system = ev_system();
868        let resolved = resolve_frbc(&system, &charge_at(0.37), Some(10.0)).unwrap();
869        let back = factor_for_power(
870            &resolved.element.unwrap().power_ranges,
871            CommodityQuantity::ElectricPower3PhaseSymmetric,
872            resolved.power[0].value,
873        )
874        .unwrap();
875        assert!((back - 0.37).abs() < 1e-12);
876    }
877
878    #[test]
879    fn projection_uses_the_element_that_applies_and_the_right_signs() {
880        let mode = charging_mode();
881        // An hour at full power: 0.0051 %/s * 3600 s = 18.36 %.
882        let after = project_fill_level(
883            &mode,
884            Factor::ONE,
885            50.0,
886            Duration::from_secs(3600),
887            None,
888            None,
889        );
890        assert!((after - 68.36).abs() < 1e-9, "{after}");
891
892        // Leakage and usage are positive when the level *falls*.
893        let leakage = [frbc::LeakageBehaviourElement {
894            fill_level_range: NumberRange::new(0.0, 100.0),
895            leakage_rate: 0.001,
896        }];
897        let after = project_fill_level(
898            &mode,
899            Factor::ZERO,
900            50.0,
901            Duration::from_secs(1000),
902            Some(&leakage),
903            Some(0.002),
904        );
905        // (0.00065 - 0.001 - 0.002) * 1000 = -2.35
906        assert!((after - 47.65).abs() < 1e-9, "{after}");
907    }
908
909    #[test]
910    fn a_timer_nobody_reported_on_does_not_block() {
911        let transitions = vec![Transition {
912            id: Id::new_const("t1"),
913            from: Id::new_const("om1"),
914            to: Id::new_const("om2"),
915            start_timers: vec![],
916            blocking_timers: vec![Id::new_const("timer0")],
917            transition_costs: None,
918            transition_duration: None,
919            abnormal_condition_only: false,
920        }];
921        let now: Timestamp = "2024-01-01T12:00:00Z".parse().unwrap();
922
923        let actuator = Id::new_const("actuator1");
924        let state = |actuator: Id, at: &str| TimerState {
925            actuator,
926            timer: Id::new_const("timer0"),
927            finished_at: at.parse().unwrap(),
928        };
929        let blocked = |known: &[TimerState]| {
930            blocking_timers(
931                &transitions,
932                &Id::new_const("om1"),
933                &Id::new_const("om2"),
934                &actuator,
935                known,
936                now,
937            )
938        };
939
940        // Nothing known about the timer: not blocked.
941        assert!(blocked(&[]).is_empty());
942
943        // Finished in the past: not blocked.
944        assert!(blocked(&[state(actuator, "2024-01-01T11:00:00Z")]).is_empty());
945
946        // Finishes later: blocked.
947        assert_eq!(
948            blocked(&[state(actuator, "2024-01-01T13:00:00Z")]),
949            vec![Id::new_const("timer0")]
950        );
951
952        // The same timer identifier, running, but on a *different* actuator. Timer ids
953        // are unique only within the actuator description that declares them, so this
954        // must not block: `S2J schemas/Timer.id`.
955        assert!(blocked(&[state(Id::new_const("actuator2"), "2024-01-01T13:00:00Z")]).is_empty());
956    }
957
958    #[test]
959    fn an_envelope_bounds_only_while_it_lasts() {
960        let start: Timestamp = "2024-08-24T15:00:00Z".parse().unwrap();
961        let instruction = pebc::Instruction {
962            message_id: Id::new_const("m1"),
963            id: Id::new_const("envelope1"),
964            execution_time: start,
965            abnormal_condition: false,
966            power_constraints_id: Id::new_const("powerConstraint1"),
967            power_envelopes: vec![pebc::PowerEnvelope {
968                id: Id::new_const("pe_xxx"),
969                commodity_quantity: CommodityQuantity::ElectricPowerL1,
970                power_envelope_elements: vec![pebc::PowerEnvelopeElement::new(
971                    Duration::from_secs(3600),
972                    -2000.0,
973                    0.0,
974                )],
975            }],
976        };
977
978        let during = limits_at(
979            &instruction,
980            CommodityQuantity::ElectricPowerL1,
981            "2024-08-24T15:30:00Z".parse().unwrap(),
982        )
983        .unwrap();
984        assert_eq!(
985            during,
986            Limits {
987                upper: 0.0,
988                lower: -2000.0
989            }
990        );
991        assert!(within(during, -1500.0));
992        assert!(!within(during, -2500.0));
993
994        // Before it starts and after it ends, the resource is unbounded.
995        assert!(
996            limits_at(
997                &instruction,
998                CommodityQuantity::ElectricPowerL1,
999                "2024-08-24T14:59:59Z".parse().unwrap()
1000            )
1001            .is_none()
1002        );
1003        assert!(
1004            limits_at(
1005                &instruction,
1006                CommodityQuantity::ElectricPowerL1,
1007                "2024-08-24T16:00:00Z".parse().unwrap()
1008            )
1009            .is_none()
1010        );
1011        // And it says nothing about a quantity it does not carry.
1012        assert!(
1013            limits_at(
1014                &instruction,
1015                CommodityQuantity::ElectricPowerL2,
1016                "2024-08-24T15:30:00Z".parse().unwrap()
1017            )
1018            .is_none()
1019        );
1020    }
1021
1022    #[test]
1023    fn a_sequence_knows_its_own_shape() {
1024        let sequence = ppbc::PowerSequence {
1025            id: Id::new_const("s1"),
1026            elements: vec![
1027                ppbc::PowerSequenceElement {
1028                    duration: Duration::from_secs(600),
1029                    power_values: vec![crate::types::common::PowerForecastValue::expected(
1030                        2000.0,
1031                        CommodityQuantity::ElectricPowerL1,
1032                    )],
1033                },
1034                ppbc::PowerSequenceElement {
1035                    duration: Duration::from_secs(1800),
1036                    power_values: vec![crate::types::common::PowerForecastValue::expected(
1037                        500.0,
1038                        CommodityQuantity::ElectricPowerL1,
1039                    )],
1040                },
1041            ],
1042            is_interruptible: true,
1043            max_pause_before: None,
1044            abnormal_condition_only: false,
1045        };
1046        assert_eq!(sequence.total_duration(), Duration::from_secs(2400));
1047        assert_eq!(
1048            sequence_power_at(&sequence, Duration::from_secs(0)).unwrap()[0].value_expected,
1049            2000.0
1050        );
1051        assert_eq!(
1052            sequence_power_at(&sequence, Duration::from_secs(1200)).unwrap()[0].value_expected,
1053            500.0
1054        );
1055        assert!(sequence_power_at(&sequence, Duration::from_secs(2400)).is_none());
1056
1057        let profile = ppbc::PowerProfileDefinition {
1058            message_id: Id::new_const("m1"),
1059            id: Id::new_const("p1"),
1060            start_time: "2024-01-01T08:00:00Z".parse().unwrap(),
1061            end_time: "2024-01-01T20:00:00Z".parse().unwrap(),
1062            power_sequence_containers: vec![ppbc::PowerSequenceContainer {
1063                id: Id::new_const("c1"),
1064                power_sequences: vec![sequence.clone()],
1065            }],
1066        };
1067        // One container: the latest start is the window's end less this sequence.
1068        let windows = schedule(&profile, &[(Id::new_const("c1"), Id::new_const("s1"))]).unwrap();
1069        assert_eq!(windows.len(), 1);
1070        assert_eq!(
1071            windows[0].earliest_start.to_string(),
1072            "2024-01-01T08:00:00Z"
1073        );
1074        assert_eq!(windows[0].latest_start.to_string(), "2024-01-01T19:20:00Z");
1075        assert!(windows[0].is_feasible());
1076        let resolved = resolve_ppbc(
1077            core::slice::from_ref(&profile),
1078            &Id::new_const("p1"),
1079            &Id::new_const("c1"),
1080            &Id::new_const("s1"),
1081        )
1082        .unwrap();
1083        assert_eq!(resolved.duration, Duration::from_secs(2400));
1084    }
1085
1086    #[test]
1087    fn a_profile_of_several_containers_leaves_room_for_the_ones_that_follow() {
1088        // Three containers, one hour each, in a five-hour window. The obvious "latest
1089        // start = end_time − my own duration" would let container 0 start at 16:00 and
1090        // the profile would overrun by two hours. Containers run in the order the
1091        // profile lists them, so each has to leave room for the rest.
1092        let hour = Duration::from_secs(3600);
1093        let step = |id: &'static str, pause: Option<Duration>| ppbc::PowerSequenceContainer {
1094            id: Id::new_const(id),
1095            power_sequences: vec![ppbc::PowerSequence {
1096                id: Id::new_const("sq"),
1097                elements: vec![ppbc::PowerSequenceElement {
1098                    duration: hour,
1099                    power_values: vec![],
1100                }],
1101                is_interruptible: false,
1102                max_pause_before: pause,
1103                abnormal_condition_only: false,
1104            }],
1105        };
1106        let profile = ppbc::PowerProfileDefinition {
1107            message_id: Id::new_const("m1"),
1108            id: Id::new_const("p1"),
1109            start_time: "2024-01-01T12:00:00Z".parse().unwrap(),
1110            end_time: "2024-01-01T17:00:00Z".parse().unwrap(),
1111            power_sequence_containers: vec![step("c1", None), step("c2", None), step("c3", None)],
1112        };
1113        let chosen = [
1114            (Id::new_const("c1"), Id::new_const("sq")),
1115            (Id::new_const("c2"), Id::new_const("sq")),
1116            (Id::new_const("c3"), Id::new_const("sq")),
1117        ];
1118
1119        let windows = schedule(&profile, &chosen).unwrap();
1120        let at = |i: usize| {
1121            (
1122                windows[i].earliest_start.to_string(),
1123                windows[i].latest_start.to_string(),
1124            )
1125        };
1126        // Three hours of work in a five-hour window: two hours of slack, shared.
1127        assert_eq!(
1128            at(0),
1129            ("2024-01-01T12:00:00Z".into(), "2024-01-01T14:00:00Z".into())
1130        );
1131        assert_eq!(
1132            at(1),
1133            ("2024-01-01T13:00:00Z".into(), "2024-01-01T15:00:00Z".into())
1134        );
1135        assert_eq!(
1136            at(2),
1137            ("2024-01-01T14:00:00Z".into(), "2024-01-01T16:00:00Z".into())
1138        );
1139        assert!(is_schedulable(&profile, &chosen));
1140
1141        // A window too short for the whole task is infeasible, and says which step fails.
1142        let mut tight = profile.clone();
1143        tight.end_time = "2024-01-01T14:00:00Z".parse().unwrap();
1144        assert!(!is_schedulable(&tight, &chosen));
1145
1146        // Concrete start times are where `max_pause_before` bites. It is a bound on the
1147        // *gap*, so it constrains a schedule rather than a window: back to back is fine,
1148        // and so is any delay the window allows — until a sequence says otherwise.
1149        let back_to_back = [
1150            "2024-01-01T12:00:00Z".parse().unwrap(),
1151            "2024-01-01T13:00:00Z".parse().unwrap(),
1152            "2024-01-01T14:00:00Z".parse().unwrap(),
1153        ];
1154        assert_eq!(
1155            starts_are_feasible(&profile, &chosen, &back_to_back),
1156            Ok(())
1157        );
1158
1159        let spread_out = [
1160            "2024-01-01T12:00:00Z".parse().unwrap(),
1161            "2024-01-01T14:00:00Z".parse().unwrap(),
1162            "2024-01-01T15:00:00Z".parse().unwrap(),
1163        ];
1164        assert_eq!(starts_are_feasible(&profile, &chosen, &spread_out), Ok(()));
1165
1166        // The same spread, but now the middle step may idle only fifteen minutes.
1167        let mut impatient = profile.clone();
1168        impatient.power_sequence_containers[1] = step("c2", Some(Duration::from_secs(900)));
1169        assert!(matches!(
1170            starts_are_feasible(&impatient, &chosen, &spread_out),
1171            Err(ScheduleProblem::PauseTooLong { idle, allowed, .. })
1172                if idle == Duration::from_secs(3600) && allowed == Duration::from_secs(900)
1173        ));
1174        // Its window is unchanged, because a pause is not a bound on one start.
1175        assert_eq!(
1176            schedule(&impatient, &chosen).unwrap()[1].latest_start,
1177            windows[1].latest_start
1178        );
1179
1180        // Overlapping the predecessor, and overrunning the window, are the other two.
1181        let overlapping = [
1182            "2024-01-01T12:00:00Z".parse().unwrap(),
1183            "2024-01-01T12:30:00Z".parse().unwrap(),
1184            "2024-01-01T14:00:00Z".parse().unwrap(),
1185        ];
1186        assert!(matches!(
1187            starts_are_feasible(&profile, &chosen, &overlapping),
1188            Err(ScheduleProblem::TooEarly { .. })
1189        ));
1190        let too_late = [
1191            "2024-01-01T13:00:00Z".parse().unwrap(),
1192            "2024-01-01T15:00:00Z".parse().unwrap(),
1193            "2024-01-01T16:30:00Z".parse().unwrap(),
1194        ];
1195        assert!(matches!(
1196            starts_are_feasible(&profile, &chosen, &too_late),
1197            Err(ScheduleProblem::Overruns { .. })
1198        ));
1199
1200        // A profile is the whole task: leaving a container unchosen is an error, and the
1201        // error names the container nobody chose for.
1202        let partial = [(Id::new_const("c1"), Id::new_const("sq"))];
1203        assert_eq!(
1204            schedule(&profile, &partial),
1205            Err(ResolveError::UnknownSequence(Id::new_const("c2")))
1206        );
1207    }
1208
1209    #[test]
1210    fn a_factor_refuses_what_is_out_of_range_and_clamps_on_request() {
1211        assert!(Factor::try_new(-0.1).is_none());
1212        assert!(Factor::try_new(1.1).is_none());
1213        assert!(Factor::try_new(f64::NAN).is_none());
1214        assert_eq!(Factor::try_new(0.5).unwrap().get(), 0.5);
1215        assert_eq!(Factor::clamping(1.3).get(), 1.0);
1216        assert_eq!(Factor::clamping(-4.0).get(), 0.0);
1217        assert_eq!(Factor::clamping(f64::NAN).get(), 0.0);
1218    }
1219}