Skip to main content

scientific_workflow/observation/
plan.rs

1//! Observation plans and schema-bound plans.
2
3use std::collections::HashSet;
4
5use crate::state::advanced::SystemStateSchema;
6
7use super::error::ObservationError;
8use super::stream::{BoundObservationStream, ObservationStream};
9
10/// An immutable application definition of scientific observation.
11#[derive(Clone, Debug, Eq, PartialEq)]
12pub struct ObservationPlan {
13    streams: Box<[ObservationStream]>,
14    iteration_unit: Option<Box<str>>,
15    physical_time_unit: Option<Box<str>>,
16}
17
18impl ObservationPlan {
19    /// Defines one inferred stream named `state` containing every state field.
20    pub fn all_fields() -> Self {
21        Self {
22            streams: vec![
23                ObservationStream::all_fields("state").expect("the inferred name is valid"),
24            ]
25            .into_boxed_slice(),
26            iteration_unit: None,
27            physical_time_unit: None,
28        }
29    }
30
31    /// Defines one inferred stream named `state` containing selected fields.
32    pub fn fields<I, S>(fields: I) -> Result<Self, ObservationError>
33    where
34        I: IntoIterator<Item = S>,
35        S: Into<String>,
36    {
37        Self::streams([ObservationStream::fields("state", fields)?])
38    }
39
40    /// Defines several explicitly named scientific streams.
41    pub fn streams<I>(streams: I) -> Result<Self, ObservationError>
42    where
43        I: IntoIterator<Item = ObservationStream>,
44    {
45        let streams = streams.into_iter().collect::<Vec<_>>();
46        if streams.is_empty() {
47            return Err(ObservationError::EmptyPlan);
48        }
49        let mut names = HashSet::with_capacity(streams.len());
50        for stream in &streams {
51            if !names.insert(stream.name().to_owned()) {
52                return Err(ObservationError::DuplicateStreamName {
53                    stream: stream.name().to_owned(),
54                });
55            }
56        }
57        Ok(Self {
58            streams: streams.into_boxed_slice(),
59            iteration_unit: None,
60            physical_time_unit: None,
61        })
62    }
63
64    /// Attaches an optional scientific unit to the inferred `iteration` axis.
65    pub fn with_iteration_unit(
66        mut self,
67        unit: impl Into<String>,
68    ) -> Result<Self, ObservationError> {
69        self.iteration_unit = Some(normalize_unit("iteration", unit)?);
70        Ok(self)
71    }
72
73    /// Attaches an optional scientific unit to the inferred `physical_time` axis.
74    pub fn with_physical_time_unit(
75        mut self,
76        unit: impl Into<String>,
77    ) -> Result<Self, ObservationError> {
78        self.physical_time_unit = Some(normalize_unit("physical_time", unit)?);
79        Ok(self)
80    }
81}
82
83fn normalize_unit(
84    axis: &'static str,
85    unit: impl Into<String>,
86) -> Result<Box<str>, ObservationError> {
87    let unit = unit.into();
88    let unit = unit.trim();
89    if unit.is_empty() {
90        return Err(ObservationError::EmptyAxisUnit { axis });
91    }
92    Ok(unit.into())
93}
94
95/// An observation plan validated against one immutable state schema.
96#[derive(Clone, Debug)]
97pub(crate) struct BoundObservationPlan {
98    schema: SystemStateSchema,
99    streams: Box<[BoundObservationStream]>,
100    iteration_unit: Option<Box<str>>,
101    physical_time_unit: Option<Box<str>>,
102}
103
104impl BoundObservationPlan {
105    /// Validates and binds an observation plan to a state schema.
106    pub(crate) fn bind(
107        plan: ObservationPlan,
108        schema: &SystemStateSchema,
109    ) -> Result<Self, ObservationError> {
110        let streams = plan
111            .streams
112            .into_vec()
113            .into_iter()
114            .map(|stream| stream.bind(schema))
115            .collect::<Result<Vec<_>, _>>()?;
116        Ok(Self {
117            schema: schema.clone(),
118            streams: streams.into_boxed_slice(),
119            iteration_unit: plan.iteration_unit,
120            physical_time_unit: plan.physical_time_unit,
121        })
122    }
123
124    /// Returns the state schema against which this descriptor was validated.
125    pub(crate) fn schema(&self) -> &SystemStateSchema {
126        &self.schema
127    }
128
129    /// Returns validated streams in deterministic definition order.
130    pub(crate) fn streams(&self) -> &[BoundObservationStream] {
131        &self.streams
132    }
133
134    /// Returns the optional unit of the inferred `iteration` axis.
135    pub(crate) fn iteration_unit(&self) -> Option<&str> {
136        self.iteration_unit.as_deref()
137    }
138
139    /// Returns the optional unit of the inferred `physical_time` axis.
140    pub(crate) fn physical_time_unit(&self) -> Option<&str> {
141        self.physical_time_unit.as_deref()
142    }
143}