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("choice {position} names {found:?}, but the profile's container there is {expected}")]
111 WrongContainer {
112 position: usize,
114 expected: Id,
116 found: Option<Id>,
118 },
119 #[error("operation mode factor {0} is outside [0, 1]")]
121 BadFactor(f64),
122 #[error("no element of this operation mode covers a fill level of {0}")]
124 FillLevelNotCovered(f64),
125 #[error("no system description for this control type has been seen")]
131 NotDescribed,
132}
133
134#[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#[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#[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#[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#[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#[derive(Debug, Clone, PartialEq)]
220pub struct FrbcResolution<'a> {
221 pub actuator: &'a frbc::ActuatorDescription,
223 pub mode: &'a frbc::OperationMode,
225 pub element: Option<&'a frbc::OperationModeElement>,
228 pub factor: Factor,
230 pub power: Vec<PowerValue>,
232 pub fill_rate: Option<f64>,
234 pub abnormal_only: bool,
236}
237
238pub 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#[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#[derive(Debug, Clone, PartialEq)]
320pub struct OmbcResolution<'a> {
321 pub mode: &'a ombc::OperationMode,
323 pub factor: Factor,
325 pub power: Vec<PowerValue>,
327 pub abnormal_only: bool,
329}
330
331pub 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#[derive(Debug, Clone, PartialEq)]
357pub struct DdbcResolution<'a> {
358 pub actuator: &'a ddbc::ActuatorDescription,
360 pub mode: &'a ddbc::OperationMode,
362 pub factor: Factor,
364 pub power: Vec<PowerValue>,
366 pub supply_rate: f64,
369 pub abnormal_only: bool,
371}
372
373pub 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#[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#[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 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#[must_use]
447pub fn within(limits: Limits, power: f64) -> bool {
448 power >= limits.lower && power <= limits.upper
449}
450
451#[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#[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#[derive(Debug, Clone, PartialEq)]
487pub struct PpbcResolution<'a> {
488 pub profile: &'a ppbc::PowerProfileDefinition,
490 pub container: &'a ppbc::PowerSequenceContainer,
492 pub sequence: &'a ppbc::PowerSequence,
494 pub duration: Duration,
496}
497
498pub 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#[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#[derive(Debug, Clone, PartialEq)]
540pub struct SequenceWindow {
541 pub container: Id,
543 pub sequence: Id,
545 pub earliest_start: Timestamp,
547 pub latest_start: Timestamp,
549 pub duration: Duration,
551 pub max_pause_before: Option<Duration>,
557}
558
559impl SequenceWindow {
560 #[must_use]
562 pub fn is_feasible(&self) -> bool {
563 self.earliest_start <= self.latest_start
564 }
565}
566
567pub fn schedule(
586 profile: &ppbc::PowerProfileDefinition,
587 chosen: &[(Id, Id)],
588) -> Result<Vec<SequenceWindow>, ResolveError> {
589 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 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#[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#[derive(Debug, Clone, PartialEq, thiserror::Error)]
668#[non_exhaustive]
669pub enum ScheduleProblem {
670 #[error("{0}")]
676 NotSchedulable(ResolveError),
677 #[error("{given} start times for {needed} sequences")]
679 WrongCount {
680 given: usize,
682 needed: usize,
684 },
685 #[error("sequence {sequence} starts at {at}, before {not_before}")]
687 TooEarly {
688 sequence: Id,
690 at: Timestamp,
692 not_before: Timestamp,
694 },
695 #[error("sequence {sequence} starts at {at} and would finish after {end_time}")]
697 Overruns {
698 sequence: Id,
700 at: Timestamp,
702 end_time: Timestamp,
704 },
705 #[error("sequence {sequence} idles {idle} after the previous one, but allows only {allowed}")]
709 PauseTooLong {
710 sequence: Id,
712 idle: Duration,
714 allowed: Duration,
716 },
717}
718
719pub 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 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 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 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 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 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 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 assert!(blocked(&[]).is_empty());
985
986 assert!(blocked(&[state(actuator, "2024-01-01T11:00:00Z")]).is_empty());
988
989 assert_eq!(
991 blocked(&[state(actuator, "2024-01-01T13:00:00Z")]),
992 vec![Id::new_const("timer0")]
993 );
994
995 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 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 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 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 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 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 let mut tight = profile.clone();
1186 tight.end_time = "2024-01-01T14:00:00Z".parse().unwrap();
1187 assert!(!is_schedulable(&tight, &chosen));
1188
1189 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 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 assert_eq!(
1219 schedule(&impatient, &chosen).unwrap()[1].latest_start,
1220 windows[1].latest_start
1221 );
1222
1223 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 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 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 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 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}