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::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    ///
21    /// This declaration is infallible. Binding later rejects an empty state
22    /// schema because every observation stream must contain at least one field.
23    pub fn all_fields() -> Self {
24        Self {
25            streams: vec![
26                ObservationStream::all_fields("state").expect("the inferred name is valid"),
27            ]
28            .into_boxed_slice(),
29            iteration_unit: None,
30            physical_time_unit: None,
31        }
32    }
33
34    /// Defines one inferred stream named `state` containing selected fields.
35    ///
36    /// Field names are trimmed and must be nonempty and unique. Their existence
37    /// is checked later against the execution unit's state schema.
38    ///
39    /// # Errors
40    ///
41    /// Returns [`ObservationError::EmptyFieldName`],
42    /// [`ObservationError::EmptyFieldSelection`], or
43    /// [`ObservationError::DuplicateField`] for an invalid declaration.
44    pub fn fields<I, S>(fields: I) -> Result<Self, ObservationError>
45    where
46        I: IntoIterator<Item = S>,
47        S: Into<String>,
48    {
49        Self::streams([ObservationStream::fields("state", fields)?])
50    }
51
52    /// Defines several explicitly named scientific streams.
53    ///
54    /// Definition order is retained. Stream constructors already normalize
55    /// names; this operation rejects an empty plan and repeated normalized
56    /// names.
57    ///
58    /// # Errors
59    ///
60    /// Returns [`ObservationError::EmptyPlan`] or
61    /// [`ObservationError::DuplicateStreamName`].
62    pub fn streams<I>(streams: I) -> Result<Self, ObservationError>
63    where
64        I: IntoIterator<Item = ObservationStream>,
65    {
66        let streams = streams.into_iter().collect::<Vec<_>>();
67        if streams.is_empty() {
68            return Err(ObservationError::EmptyPlan);
69        }
70        let mut names = HashSet::with_capacity(streams.len());
71        for stream in &streams {
72            if !names.insert(stream.name().to_owned()) {
73                return Err(ObservationError::DuplicateStreamName {
74                    stream: stream.name().to_owned(),
75                });
76            }
77        }
78        Ok(Self {
79            streams: streams.into_boxed_slice(),
80            iteration_unit: None,
81            physical_time_unit: None,
82        })
83    }
84
85    /// Attaches an optional scientific unit to the inferred `iteration` axis.
86    ///
87    /// Surrounding whitespace is removed.
88    ///
89    /// # Errors
90    ///
91    /// Returns [`ObservationError::EmptyAxisUnit`] when the normalized unit is
92    /// empty.
93    pub fn with_iteration_unit(
94        mut self,
95        unit: impl Into<String>,
96    ) -> Result<Self, ObservationError> {
97        self.iteration_unit = Some(normalize_unit("iteration", unit)?);
98        Ok(self)
99    }
100
101    /// Attaches an optional scientific unit to the inferred `physical_time` axis.
102    ///
103    /// Surrounding whitespace is removed.
104    ///
105    /// # Errors
106    ///
107    /// Returns [`ObservationError::EmptyAxisUnit`] when the normalized unit is
108    /// empty.
109    pub fn with_physical_time_unit(
110        mut self,
111        unit: impl Into<String>,
112    ) -> Result<Self, ObservationError> {
113        self.physical_time_unit = Some(normalize_unit("physical_time", unit)?);
114        Ok(self)
115    }
116}
117
118fn normalize_unit(
119    axis: &'static str,
120    unit: impl Into<String>,
121) -> Result<Box<str>, ObservationError> {
122    let unit = unit.into();
123    let unit = unit.trim();
124    if unit.is_empty() {
125        return Err(ObservationError::EmptyAxisUnit { axis });
126    }
127    Ok(unit.into())
128}
129
130/// An observation plan validated against one immutable state schema.
131#[derive(Clone, Debug)]
132pub(crate) struct BoundObservationPlan {
133    schema: SystemStateSchema,
134    streams: Box<[BoundObservationStream]>,
135    iteration_unit: Option<Box<str>>,
136    physical_time_unit: Option<Box<str>>,
137}
138
139impl BoundObservationPlan {
140    /// Validates and binds an observation plan to a state schema.
141    pub(crate) fn bind(
142        plan: ObservationPlan,
143        schema: &SystemStateSchema,
144    ) -> Result<Self, ObservationError> {
145        let streams = plan
146            .streams
147            .into_vec()
148            .into_iter()
149            .map(|stream| stream.bind(schema))
150            .collect::<Result<Vec<_>, _>>()?;
151        Ok(Self {
152            schema: schema.clone(),
153            streams: streams.into_boxed_slice(),
154            iteration_unit: plan.iteration_unit,
155            physical_time_unit: plan.physical_time_unit,
156        })
157    }
158
159    /// Returns the state schema against which this descriptor was validated.
160    pub(crate) fn schema(&self) -> &SystemStateSchema {
161        &self.schema
162    }
163
164    /// Returns validated streams in deterministic definition order.
165    pub(crate) fn streams(&self) -> &[BoundObservationStream] {
166        &self.streams
167    }
168
169    /// Returns the optional unit of the inferred `iteration` axis.
170    pub(crate) fn iteration_unit(&self) -> Option<&str> {
171        self.iteration_unit.as_deref()
172    }
173
174    /// Returns the optional unit of the inferred `physical_time` axis.
175    pub(crate) fn physical_time_unit(&self) -> Option<&str> {
176        self.physical_time_unit.as_deref()
177    }
178}