scientific_workflow/state/time.rs
1//! Scientific coordinates attached to one system state.
2
3use super::error::StateError;
4
5/// The scientific time coordinate associated with one system state.
6///
7/// Every state has a deterministic `iteration`. A state may additionally carry
8/// finite `physical_time`, such as seconds or dimensionless model time. This is
9/// distinct from operational wall-clock timestamps recorded by Workflow.
10#[derive(Clone, Copy, Debug, PartialEq)]
11pub struct StateTime {
12 iteration: u64,
13 physical_time: Option<f64>,
14}
15
16impl StateTime {
17 /// Creates an iteration-only state time.
18 pub const fn from_iteration(iteration: u64) -> Self {
19 Self {
20 iteration,
21 physical_time: None,
22 }
23 }
24
25 /// Creates a state time with a finite physical coordinate.
26 ///
27 /// Returns `None` for `NaN` or either infinity. Negative finite values are
28 /// accepted because scientific coordinates may precede an arbitrary origin.
29 pub fn from_iteration_and_physical_time(iteration: u64, physical_time: f64) -> Option<Self> {
30 physical_time.is_finite().then_some(Self {
31 iteration,
32 physical_time: Some(physical_time),
33 })
34 }
35
36 /// Returns the deterministic iteration coordinate.
37 pub const fn iteration(self) -> u64 {
38 self.iteration
39 }
40
41 /// Returns the optional physical coordinate.
42 pub const fn physical_time(self) -> Option<f64> {
43 self.physical_time
44 }
45
46 /// Computes the next state time without mutating a state.
47 ///
48 /// `None` advances only the iteration and preserves the optional physical
49 /// coordinate. `Some(delta)` also advances an existing physical coordinate.
50 pub fn checked_advance(self, physical_time_increment: Option<f64>) -> Result<Self, StateError> {
51 let iteration = self
52 .iteration
53 .checked_add(1)
54 .ok_or(StateError::IterationOverflow {
55 iteration: self.iteration,
56 })?;
57 let physical_time = match (self.physical_time, physical_time_increment) {
58 (physical_time, None) => physical_time,
59 (None, Some(_)) => {
60 return Err(StateError::MissingPhysicalTime {
61 iteration: self.iteration,
62 });
63 }
64 (Some(current), Some(delta)) => {
65 let next = current + delta;
66 if !delta.is_finite() || !next.is_finite() {
67 return Err(StateError::InvalidPhysicalAdvance { current, delta });
68 }
69 Some(next)
70 }
71 };
72 Ok(Self {
73 iteration,
74 physical_time,
75 })
76 }
77}