Skip to main content

s2_kit/model/
explain.rs

1//! Saying, in one value, what an instruction will actually do.
2//!
3//! A Resource Manager logs it so that an operator can see why the device did what it
4//! did. A Customer Energy Manager calls it before sending, so that a plan built from
5//! numbers is checked against the description it was built from. Both are asking the
6//! same question — *what does this instruction mean, given what was described?* — and
7//! both should get the same answer, which is the point of resolving it once here.
8
9use alloc::format;
10use alloc::string::{String, ToString};
11use alloc::vec::Vec;
12
13use super::{
14    Limits, all_limits_at, blocking_timers, resolve_ddbc, resolve_frbc, resolve_ombc, resolve_ppbc,
15    timer_label, transition_duration,
16};
17use crate::message::{Message, MessageKind};
18use crate::types::common::{CommodityQuantity, PowerValue};
19use crate::types::{Duration, Id, Timestamp};
20use crate::validate::Context;
21
22/// What an instruction means, read against the descriptions that were sent.
23#[derive(Debug, Clone, PartialEq)]
24#[non_exhaustive]
25pub struct Explanation {
26    /// The instruction's own identifier.
27    pub instruction_id: Id,
28    /// Which kind of instruction it is.
29    pub kind: MessageKind,
30    /// When it takes effect. In the past means as soon as possible.
31    pub execution_time: Timestamp,
32    /// Whether it is an abnormal-condition instruction.
33    pub abnormal_condition: bool,
34    /// The actuator it addresses, for the control types that have them.
35    pub actuator: Option<Id>,
36    /// The operation mode it selects, with its diagnostic label where there is one.
37    pub operation_mode: Option<(Id, Option<String>)>,
38    /// The factor it asks for.
39    pub factor: Option<f64>,
40    /// The power that factor implies.
41    pub power: Vec<PowerValue>,
42    /// FRBC: how fast the store will fill, in fill-level units per second.
43    pub fill_rate: Option<f64>,
44    /// DDBC: the supply rate the mode will deliver.
45    pub supply_rate: Option<f64>,
46    /// PEBC: the bounds in force when the envelope starts.
47    pub limits: Vec<(CommodityQuantity, Limits)>,
48    /// PPBC: the profile, container and sequence it chose, and how long it takes.
49    pub sequence: Option<(Id, Id, Id, Duration)>,
50    /// How long the move takes to take effect.
51    pub transition_duration: Duration,
52    /// Timers that have not finished and block the move this instruction asks for.
53    pub blocked_by: Vec<(Id, Option<String>)>,
54    /// Whether it uses something marked `abnormal_condition_only` without saying so.
55    pub abnormal_only_misuse: bool,
56    /// Why the instruction could not be read against the description, if it could not.
57    ///
58    /// An instruction naming an actuator nobody described, an operation mode that
59    /// actuator does not have, or a factor outside `[0, 1]` has no power, no fill rate
60    /// and no transition — and an [`Explanation`] that merely left those empty would be
61    /// indistinguishable from one for an instruction that genuinely asks for zero watts.
62    /// [`is_actionable`](Self::is_actionable) is false whenever this is set.
63    pub unresolved: Option<super::ResolveError>,
64    /// Anything else worth saying in a log line.
65    pub notes: Vec<String>,
66}
67
68impl Explanation {
69    /// Whether this instruction can be carried out right now, as far as the description
70    /// can tell.
71    #[must_use]
72    pub fn is_actionable(&self) -> bool {
73        self.unresolved.is_none() && self.blocked_by.is_empty() && !self.abnormal_only_misuse
74    }
75
76    /// The electrical power the instruction implies, if it names one.
77    #[must_use]
78    pub fn electric_power(&self) -> Option<f64> {
79        self.power
80            .iter()
81            .find(|v| {
82                v.commodity_quantity.commodity() == crate::types::common::Commodity::Electricity
83            })
84            .map(|v| v.value)
85    }
86}
87
88impl core::fmt::Display for Explanation {
89    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
90        write!(f, "{} {}", self.kind, self.instruction_id)?;
91        if let Some(actuator) = &self.actuator {
92            write!(f, " on {actuator}")?;
93        }
94        if let Some((mode, label)) = &self.operation_mode {
95            match label {
96                Some(label) => write!(f, " → {label} ({mode})")?,
97                None => write!(f, " → {mode}")?,
98            }
99        }
100        if let Some(factor) = self.factor {
101            write!(f, " at factor {factor}")?;
102        }
103        for value in &self.power {
104            // The unit from the quantity, not a hard-coded `W`: four of the ten
105            // quantities are litres, grams or degrees, and one of them is not a power.
106            write!(
107                f,
108                ", {} {} {}",
109                value.commodity_quantity.as_str(),
110                value.value,
111                value.commodity_quantity.unit()
112            )?;
113        }
114        if let Some(rate) = self.fill_rate {
115            write!(f, ", filling at {rate}/s")?;
116        }
117        if let Some(rate) = self.supply_rate {
118            write!(f, ", supplying {rate}")?;
119        }
120        for (quantity, limits) in &self.limits {
121            write!(
122                f,
123                ", {} bounded to {}..{} {}",
124                quantity.as_str(),
125                limits.lower,
126                limits.upper,
127                quantity.unit()
128            )?;
129        }
130        if let Some((_, _, sequence, duration)) = &self.sequence {
131            write!(f, ", running {sequence} for {duration}")?;
132        }
133        if !self.transition_duration.is_zero() {
134            write!(f, ", taking effect after {}", self.transition_duration)?;
135        }
136        for (timer, label) in &self.blocked_by {
137            match label {
138                Some(label) => write!(f, "; blocked by {label} ({timer})")?,
139                None => write!(f, "; blocked by {timer}")?,
140            }
141        }
142        if let Some(why) = &self.unresolved {
143            write!(f, "; unresolved: {why}")?;
144        }
145        if self.abnormal_only_misuse {
146            write!(
147                f,
148                "; uses an abnormal-condition-only option without saying so"
149            )?;
150        }
151        for note in &self.notes {
152            write!(f, "; {note}")?;
153        }
154        Ok(())
155    }
156}
157
158/// Explain an instruction against the descriptions a session has seen.
159///
160/// `None` for any message that is not an instruction.
161#[must_use]
162#[allow(clippy::too_many_lines)] // one arm per control type; splitting it would hide the symmetry
163pub fn explain(message: &Message, ctx: &Context<'_>) -> Option<Explanation> {
164    let instruction_id = message.instruction_id()?;
165    let mut e = Explanation {
166        instruction_id,
167        kind: message.kind(),
168        execution_time: Timestamp::UNIX_EPOCH,
169        abnormal_condition: false,
170        actuator: None,
171        operation_mode: None,
172        factor: None,
173        power: Vec::new(),
174        fill_rate: None,
175        supply_rate: None,
176        limits: Vec::new(),
177        sequence: None,
178        transition_duration: Duration::ZERO,
179        blocked_by: Vec::new(),
180        abnormal_only_misuse: false,
181        unresolved: None,
182        notes: Vec::new(),
183    };
184
185    match message {
186        Message::FrbcInstruction(i) => {
187            e.execution_time = i.execution_time;
188            e.abnormal_condition = i.abnormal_condition;
189            e.actuator = Some(i.actuator_id);
190            e.factor = Some(i.operation_mode_factor);
191            let Some(system) = ctx.frbc else {
192                e.notes
193                    .push("no FRBC.SystemDescription has been seen".into());
194                e.unresolved = Some(super::ResolveError::NotDescribed);
195                return Some(e);
196            };
197            match resolve_frbc(system, i, ctx.fill_level) {
198                Ok(r) => {
199                    e.operation_mode = Some((r.mode.id, r.mode.diagnostic_label.clone()));
200                    e.power = r.power;
201                    e.fill_rate = r.fill_rate;
202                    e.abnormal_only_misuse = r.abnormal_only && !i.abnormal_condition;
203                    if !system
204                        .storage
205                        .fill_level_range
206                        .contains(ctx.fill_level.unwrap_or(f64::NAN))
207                        && ctx.fill_level.is_some()
208                    {
209                        e.notes.push(
210                            "the fill level is outside the storage's range, so the Resource \
211                             Manager may ignore this"
212                                .into(),
213                        );
214                    }
215                    note_transition(
216                        &mut e,
217                        ctx,
218                        &i.actuator_id,
219                        &i.operation_mode,
220                        &r.actuator.transitions,
221                        &r.actuator.timers,
222                    );
223                }
224                Err(err) => {
225                    e.notes.push(err.to_string());
226                    e.unresolved = Some(err);
227                }
228            }
229        }
230        Message::OmbcInstruction(i) => {
231            e.execution_time = i.execution_time;
232            e.abnormal_condition = i.abnormal_condition;
233            e.factor = Some(i.operation_mode_factor);
234            let Some(system) = ctx.ombc else {
235                e.notes
236                    .push("no OMBC.SystemDescription has been seen".into());
237                e.unresolved = Some(super::ResolveError::NotDescribed);
238                return Some(e);
239            };
240            match resolve_ombc(system, i) {
241                Ok(r) => {
242                    e.operation_mode = Some((r.mode.id, r.mode.diagnostic_label.clone()));
243                    e.power = r.power;
244                    e.abnormal_only_misuse = r.abnormal_only && !i.abnormal_condition;
245                    note_transition(
246                        &mut e,
247                        ctx,
248                        &Id::NIL,
249                        &i.operation_mode_id,
250                        &system.transitions,
251                        &system.timers,
252                    );
253                }
254                Err(err) => {
255                    e.notes.push(err.to_string());
256                    e.unresolved = Some(err);
257                }
258            }
259        }
260        Message::DdbcInstruction(i) => {
261            e.execution_time = i.execution_time;
262            e.abnormal_condition = i.abnormal_condition;
263            e.actuator = Some(i.actuator_id);
264            e.factor = Some(i.operation_mode_factor);
265            let Some(system) = ctx.ddbc else {
266                e.notes
267                    .push("no DDBC.SystemDescription has been seen".into());
268                e.unresolved = Some(super::ResolveError::NotDescribed);
269                return Some(e);
270            };
271            match resolve_ddbc(system, i) {
272                Ok(r) => {
273                    e.operation_mode = Some((r.mode.id, r.mode.diagnostic_label.clone()));
274                    e.power = r.power;
275                    e.supply_rate = Some(r.supply_rate);
276                    e.abnormal_only_misuse = r.abnormal_only && !i.abnormal_condition;
277                    note_transition(
278                        &mut e,
279                        ctx,
280                        &i.actuator_id,
281                        &i.operation_mode_id,
282                        &r.actuator.transitions,
283                        &r.actuator.timers,
284                    );
285                }
286                Err(err) => {
287                    e.notes.push(err.to_string());
288                    e.unresolved = Some(err);
289                }
290            }
291        }
292        Message::PebcInstruction(i) => {
293            e.execution_time = i.execution_time;
294            e.abnormal_condition = i.abnormal_condition;
295            e.limits = all_limits_at(i, i.execution_time);
296            if e.limits.is_empty() {
297                e.notes
298                    .push("the envelope bounds nothing at its own execution time".into());
299            }
300            if !ctx
301                .pebc_constraints
302                .iter()
303                .any(|c| c.id == i.power_constraints_id)
304                && !ctx.pebc_constraints.is_empty()
305            {
306                e.notes.push(format!(
307                    "{} names no published PEBC.PowerConstraints",
308                    i.power_constraints_id
309                ));
310            }
311        }
312        Message::PpbcScheduleInstruction(i) => {
313            e.execution_time = i.execution_time;
314            e.abnormal_condition = i.abnormal_condition;
315            note_sequence(
316                &mut e,
317                ctx,
318                i.power_profile_id,
319                i.sequence_container_id,
320                i.power_sequence_id,
321            );
322        }
323        Message::PpbcStartInterruptionInstruction(i) => {
324            e.execution_time = i.execution_time;
325            e.abnormal_condition = i.abnormal_condition;
326            note_sequence(
327                &mut e,
328                ctx,
329                i.power_profile_id,
330                i.sequence_container_id,
331                i.power_sequence_id,
332            );
333            e.notes.push("pauses the sequence".into());
334        }
335        Message::PpbcEndInterruptionInstruction(i) => {
336            e.execution_time = i.execution_time;
337            e.abnormal_condition = i.abnormal_condition;
338            note_sequence(
339                &mut e,
340                ctx,
341                i.power_profile_id,
342                i.sequence_container_id,
343                i.power_sequence_id,
344            );
345            e.notes.push("resumes the sequence".into());
346        }
347        _ => return None,
348    }
349
350    if let Some(now) = ctx.now
351        && e.execution_time <= now
352    {
353        e.notes
354            .push("execution time has passed, so this means as soon as possible".into());
355    }
356    Some(e)
357}
358
359fn note_transition(
360    e: &mut Explanation,
361    ctx: &Context<'_>,
362    actuator: &Id,
363    to: &Id,
364    transitions: &[crate::types::common::Transition],
365    timers: &[crate::types::common::Timer],
366) {
367    let Some(active) = ctx
368        .active_modes
369        .iter()
370        .find(|(a, _)| a == actuator)
371        .map(|(_, m)| *m)
372    else {
373        return;
374    };
375    if active == *to {
376        e.notes
377            .push("already in this operation mode; only the factor changes".into());
378        return;
379    }
380    e.transition_duration = transition_duration(transitions, &active, to);
381    if let Some(now) = ctx.now {
382        e.blocked_by = blocking_timers(transitions, &active, to, actuator, ctx.timers, now)
383            .into_iter()
384            .map(|id| (id, timer_label(timers, &id).map(ToString::to_string)))
385            .collect();
386    }
387    if transitions
388        .iter()
389        .all(|t| !(t.from == active && t.to == *to))
390    {
391        e.notes
392            .push(format!("no transition is described from {active}"));
393    }
394}
395
396fn note_sequence(e: &mut Explanation, ctx: &Context<'_>, profile: Id, container: Id, sequence: Id) {
397    match resolve_ppbc(ctx.ppbc_profiles, &profile, &container, &sequence) {
398        Ok(r) => e.sequence = Some((profile, container, sequence, r.duration)),
399        Err(err) => {
400            e.sequence = Some((profile, container, sequence, Duration::ZERO));
401            if !ctx.ppbc_profiles.is_empty() {
402                e.notes.push(err.to_string());
403            }
404        }
405    }
406}
407
408#[cfg(test)]
409mod tests {
410    #[test]
411    fn an_instruction_that_did_not_resolve_is_not_actionable() {
412        use super::*;
413        use crate::model::ResolveError;
414        use crate::types::common::{Commodity, NumberRange, PowerRange};
415        use crate::types::frbc;
416        use alloc::vec;
417
418        // `is_actionable` used to mean "nothing is blocking it", which is true of an
419        // instruction whose actuator nobody described — it has no transitions, so nothing
420        // can block it. An application that asked the question got `true` and an empty
421        // `power`, which is indistinguishable from an instruction that genuinely asks for
422        // zero watts.
423        let system = frbc::SystemDescription {
424            message_id: Id::new_const("m1"),
425            valid_from: Timestamp::UNIX_EPOCH,
426            actuators: vec![frbc::ActuatorDescription {
427                id: Id::new_const("actuator1"),
428                diagnostic_label: None,
429                supported_commodities: vec![Commodity::Electricity],
430                operation_modes: vec![frbc::OperationMode {
431                    id: Id::new_const("om1"),
432                    diagnostic_label: None,
433                    elements: vec![frbc::OperationModeElement {
434                        fill_level_range: NumberRange::new(0.0, 100.0),
435                        fill_rate: NumberRange::new(0.0, 0.002),
436                        power_ranges: vec![PowerRange::new(
437                            0.0,
438                            5000.0,
439                            CommodityQuantity::ElectricPower3PhaseSymmetric,
440                        )],
441                        running_costs: None,
442                    }],
443                    abnormal_condition_only: false,
444                }],
445                transitions: vec![],
446                timers: vec![],
447            }],
448            storage: frbc::StorageDescription {
449                diagnostic_label: None,
450                fill_level_label: None,
451                provides_leakage_behaviour: false,
452                provides_fill_level_target_profile: false,
453                provides_usage_forecast: false,
454                fill_level_range: NumberRange::new(0.0, 100.0),
455            },
456        };
457        let ctx = Context {
458            frbc: Some(&system),
459            ..Context::empty()
460        };
461        let instruct = |actuator: &'static str, factor: f64| {
462            Message::from(frbc::Instruction {
463                message_id: Id::new_const("m2"),
464                id: Id::new_const("i1"),
465                actuator_id: Id::new_const(actuator),
466                operation_mode: Id::new_const("om1"),
467                operation_mode_factor: factor,
468                execution_time: Timestamp::UNIX_EPOCH,
469                abnormal_condition: false,
470            })
471        };
472
473        // The happy case still is actionable.
474        let good = explain(&instruct("actuator1", 0.5), &ctx).expect("an instruction");
475        assert!(good.unresolved.is_none());
476        assert!(good.is_actionable());
477        assert!(!good.power.is_empty());
478
479        // An actuator nobody described.
480        let ghost = explain(&instruct("ghost", 0.5), &ctx).expect("an instruction");
481        assert_eq!(
482            ghost.unresolved,
483            Some(ResolveError::UnknownActuator(Id::new_const("ghost")))
484        );
485        assert!(!ghost.is_actionable());
486        assert!(ghost.power.is_empty());
487        assert!(ghost.to_string().contains("unresolved"));
488
489        // A factor the arithmetic cannot use.
490        let bad = explain(&instruct("actuator1", 1.3), &ctx).expect("an instruction");
491        assert_eq!(bad.unresolved, Some(ResolveError::BadFactor(1.3)));
492        assert!(!bad.is_actionable());
493
494        // And no description at all is its own answer, not a silently empty one.
495        let blind = explain(&instruct("actuator1", 0.5), &Context::empty()).expect("one");
496        assert_eq!(blind.unresolved, Some(ResolveError::NotDescribed));
497        assert!(!blind.is_actionable());
498    }
499
500    use super::*;
501    use crate::types::common::{Commodity, NumberRange, PowerRange, Transition};
502    use crate::types::frbc;
503    use alloc::vec;
504
505    fn system() -> frbc::SystemDescription {
506        frbc::SystemDescription {
507            message_id: Id::new_const("m1"),
508            valid_from: Timestamp::UNIX_EPOCH,
509            actuators: vec![frbc::ActuatorDescription {
510                id: Id::new_const("actuator1"),
511                diagnostic_label: Some("EV charger".into()),
512                supported_commodities: vec![Commodity::Electricity],
513                operation_modes: vec![
514                    frbc::OperationMode {
515                        id: Id::new_const("om1"),
516                        diagnostic_label: Some("Off".into()),
517                        elements: vec![frbc::OperationModeElement {
518                            fill_level_range: NumberRange::new(0.0, 100.0),
519                            fill_rate: NumberRange::exactly(0.0),
520                            power_ranges: vec![PowerRange::exactly(
521                                0.0,
522                                CommodityQuantity::ElectricPower3PhaseSymmetric,
523                            )],
524                            running_costs: None,
525                        }],
526                        abnormal_condition_only: false,
527                    },
528                    frbc::OperationMode {
529                        id: Id::new_const("om2"),
530                        diagnostic_label: Some("Charging".into()),
531                        elements: vec![frbc::OperationModeElement {
532                            fill_level_range: NumberRange::new(0.0, 100.0),
533                            fill_rate: NumberRange::new(0.000_65, 0.0051),
534                            power_ranges: vec![PowerRange::new(
535                                1400.0,
536                                11_000.0,
537                                CommodityQuantity::ElectricPower3PhaseSymmetric,
538                            )],
539                            running_costs: None,
540                        }],
541                        abnormal_condition_only: false,
542                    },
543                ],
544                transitions: vec![Transition {
545                    id: Id::new_const("transition1"),
546                    from: Id::new_const("om1"),
547                    to: Id::new_const("om2"),
548                    start_timers: vec![],
549                    blocking_timers: vec![Id::new_const("timer0")],
550                    transition_costs: None,
551                    transition_duration: Some(Duration::from_secs(3)),
552                    abnormal_condition_only: false,
553                }],
554                timers: vec![crate::types::common::Timer {
555                    id: Id::new_const("timer0"),
556                    diagnostic_label: Some("Minimum off time".into()),
557                    duration: Duration::from_secs(3600),
558                }],
559            }],
560            storage: frbc::StorageDescription {
561                diagnostic_label: None,
562                fill_level_label: None,
563                provides_leakage_behaviour: false,
564                provides_fill_level_target_profile: false,
565                provides_usage_forecast: false,
566                fill_level_range: NumberRange::new(0.0, 100.0),
567            },
568        }
569    }
570
571    fn instruction() -> Message {
572        Message::from(frbc::Instruction {
573            message_id: Id::new_const("m2"),
574            id: Id::new_const("instr0"),
575            actuator_id: Id::new_const("actuator1"),
576            operation_mode: Id::new_const("om2"),
577            operation_mode_factor: 0.5,
578            execution_time: "2024-01-01T12:00:00Z".parse().unwrap(),
579            abnormal_condition: false,
580        })
581    }
582
583    #[test]
584    fn an_explanation_names_the_power_and_the_mode_a_human_would_recognise() {
585        let system = system();
586        let ctx = Context {
587            frbc: Some(&system),
588            fill_level: Some(50.0),
589            ..Context::empty()
590        };
591        let e = explain(&instruction(), &ctx).unwrap();
592        assert_eq!(e.operation_mode.clone().unwrap().1.unwrap(), "Charging");
593        assert!((e.power[0].value - 6200.0).abs() < 1e-9);
594        assert!(e.is_actionable());
595        let rendered = e.to_string();
596        assert!(rendered.contains("Charging"), "{rendered}");
597        assert!(rendered.contains("6200"), "{rendered}");
598    }
599
600    #[test]
601    fn an_explanation_says_when_a_timer_is_in_the_way() {
602        let system = system();
603        let now: Timestamp = "2024-01-01T12:00:00Z".parse().unwrap();
604        let active = [(Id::new_const("actuator1"), Id::new_const("om1"))];
605        let timers = [crate::validate::TimerState {
606            actuator: Id::new_const("actuator1"),
607            timer: Id::new_const("timer0"),
608            finished_at: "2024-01-01T12:30:00Z".parse().unwrap(),
609        }];
610        let ctx = Context {
611            frbc: Some(&system),
612            fill_level: Some(50.0),
613            active_modes: &active,
614            timers: &timers,
615            now: Some(now),
616            ..Context::empty()
617        };
618        let e = explain(&instruction(), &ctx).unwrap();
619        assert!(!e.is_actionable());
620        assert_eq!(e.blocked_by.len(), 1);
621        assert_eq!(e.blocked_by[0].1.as_deref(), Some("Minimum off time"));
622        assert_eq!(e.transition_duration, Duration::from_secs(3));
623        assert!(e.to_string().contains("Minimum off time"));
624    }
625
626    #[test]
627    fn an_explanation_without_a_description_says_so_rather_than_guessing() {
628        let e = explain(&instruction(), &Context::empty()).unwrap();
629        assert!(e.power.is_empty());
630        assert_eq!(e.notes, vec!["no FRBC.SystemDescription has been seen"]);
631    }
632
633    #[test]
634    fn nothing_to_explain_about_a_measurement() {
635        let m = Message::from(frbc::StorageStatus {
636            message_id: Id::new_const("m1"),
637            present_fill_level: 50.0,
638        });
639        assert!(explain(&m, &Context::empty()).is_none());
640    }
641}