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