1pub 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#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
46pub struct Factor(f64);
47
48impl Factor {
49 pub const ZERO: Self = Self(0.0);
51 pub const ONE: Self = Self(1.0);
53
54 #[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 #[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 #[must_use]
75 pub const fn get(self) -> f64 {
76 self.0
77 }
78}
79
80#[derive(Debug, Clone, Copy, PartialEq)]
82pub struct Limits {
83 pub upper: f64,
85 pub lower: f64,
87}
88
89#[derive(Debug, Clone, PartialEq, thiserror::Error)]
91#[non_exhaustive]
92pub enum ResolveError {
93 #[error("{0} is not an actuator of this system")]
95 UnknownActuator(Id),
96 #[error("{0} is not an operation mode of that actuator")]
98 UnknownOperationMode(Id),
99 #[error("{0} was never published")]
101 UnknownSequence(Id),
102 #[error("operation mode factor {0} is outside [0, 1]")]
104 BadFactor(f64),
105 #[error("no element of this operation mode covers a fill level of {0}")]
107 FillLevelNotCovered(f64),
108}
109
110#[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#[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#[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#[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#[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#[derive(Debug, Clone, PartialEq)]
196pub struct FrbcResolution<'a> {
197 pub actuator: &'a frbc::ActuatorDescription,
199 pub mode: &'a frbc::OperationMode,
201 pub element: Option<&'a frbc::OperationModeElement>,
204 pub factor: Factor,
206 pub power: Vec<PowerValue>,
208 pub fill_rate: Option<f64>,
210 pub abnormal_only: bool,
212}
213
214pub 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#[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#[derive(Debug, Clone, PartialEq)]
296pub struct OmbcResolution<'a> {
297 pub mode: &'a ombc::OperationMode,
299 pub factor: Factor,
301 pub power: Vec<PowerValue>,
303 pub abnormal_only: bool,
305}
306
307pub 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#[derive(Debug, Clone, PartialEq)]
333pub struct DdbcResolution<'a> {
334 pub actuator: &'a ddbc::ActuatorDescription,
336 pub mode: &'a ddbc::OperationMode,
338 pub factor: Factor,
340 pub power: Vec<PowerValue>,
342 pub supply_rate: f64,
345 pub abnormal_only: bool,
347}
348
349pub 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#[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#[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 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#[must_use]
422pub fn within(limits: Limits, power: f64) -> bool {
423 power >= limits.lower && power <= limits.upper
424}
425
426#[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#[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#[derive(Debug, Clone, PartialEq)]
462pub struct PpbcResolution<'a> {
463 pub profile: &'a ppbc::PowerProfileDefinition,
465 pub container: &'a ppbc::PowerSequenceContainer,
467 pub sequence: &'a ppbc::PowerSequence,
469 pub duration: Duration,
471}
472
473pub 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#[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#[derive(Debug, Clone, PartialEq)]
515pub struct SequenceWindow {
516 pub container: Id,
518 pub sequence: Id,
520 pub earliest_start: Timestamp,
522 pub latest_start: Timestamp,
524 pub duration: Duration,
526 pub max_pause_before: Option<Duration>,
532}
533
534impl SequenceWindow {
535 #[must_use]
537 pub fn is_feasible(&self) -> bool {
538 self.earliest_start <= self.latest_start
539 }
540}
541
542pub 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 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 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#[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#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
629#[non_exhaustive]
630pub enum ScheduleProblem {
631 #[error("{given} start times for {needed} sequences")]
633 WrongCount {
634 given: usize,
636 needed: usize,
638 },
639 #[error("sequence {sequence} starts at {at}, before {not_before}")]
641 TooEarly {
642 sequence: Id,
644 at: Timestamp,
646 not_before: Timestamp,
648 },
649 #[error("sequence {sequence} starts at {at} and would finish after {end_time}")]
651 Overruns {
652 sequence: Id,
654 at: Timestamp,
656 end_time: Timestamp,
658 },
659 #[error("sequence {sequence} idles {idle} after the previous one, but allows only {allowed}")]
663 PauseTooLong {
664 sequence: Id,
666 idle: Duration,
668 allowed: Duration,
670 },
671}
672
673pub 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 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 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 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 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 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 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 assert!(blocked(&[]).is_empty());
942
943 assert!(blocked(&[state(actuator, "2024-01-01T11:00:00Z")]).is_empty());
945
946 assert_eq!(
948 blocked(&[state(actuator, "2024-01-01T13:00:00Z")]),
949 vec![Id::new_const("timer0")]
950 );
951
952 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 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 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 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 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 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 let mut tight = profile.clone();
1143 tight.end_time = "2024-01-01T14:00:00Z".parse().unwrap();
1144 assert!(!is_schedulable(&tight, &chosen));
1145
1146 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 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 assert_eq!(
1176 schedule(&impatient, &chosen).unwrap()[1].latest_start,
1177 windows[1].latest_start
1178 );
1179
1180 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 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}