Skip to main content

tpt_sci_sim_core/
sim.rs

1use std::collections::HashMap;
2
3use crate::coupling::Coupling;
4use crate::error::SimError;
5use crate::submodel::SubModel;
6
7/// An immutable snapshot of a [`Simulation`]'s state, suitable for
8/// checkpoint/restart.
9///
10/// `Checkpoint` stores the global clock plus each sub-model's state vector and
11/// internal time. It is intentionally plain data (no trait objects) so it can
12/// be serialized by downstream consumers.
13#[derive(Debug, Clone)]
14pub struct Checkpoint {
15    /// Global simulation time at snapshot.
16    pub global_time: f64,
17    /// `(id, state, internal_time)` per sub-model, in registration order.
18    pub models: Vec<(String, Vec<f64>, f64)>,
19}
20
21/// A multi-scale simulation orchestrating a set of [`SubModel`]s.
22///
23/// The orchestrator drives all sub-models forward to a shared target time with
24/// adaptive sub-stepping: each sub-step is the largest `dt` that advances no
25/// model past the target and exceeds no model's `max_step`. After every
26/// sub-step, all registered [`Coupling`]s fire (writing cross-scale inputs),
27/// so models of differing time scales stay coupled without overshooting.
28pub struct Simulation {
29    models: HashMap<String, Box<dyn SubModel>>,
30    order: Vec<String>,
31    couplings: Vec<Coupling>,
32    global_time: f64,
33}
34
35impl Simulation {
36    /// Create an empty simulation at global time `0.0`.
37    pub fn new() -> Self {
38        Self {
39            models: HashMap::new(),
40            order: Vec::new(),
41            couplings: Vec::new(),
42            global_time: 0.0,
43        }
44    }
45
46    /// Register a sub-model. Returns an error if the id is already taken.
47    ///
48    /// # Errors
49    ///
50    /// Returns [`SimError::DuplicateModel`] if a model with the same id is
51    /// already registered.
52    pub fn add_model(&mut self, model: impl SubModel + 'static) -> Result<(), SimError> {
53        let id = model.id().to_string();
54        if self.models.contains_key(&id) {
55            return Err(SimError::DuplicateModel(id));
56        }
57        self.order.push(id.clone());
58        self.models.insert(id, Box::new(model));
59        Ok(())
60    }
61
62    /// Register a cross-scale [`Coupling`]. The source and target models must
63    /// already be registered (or will be — couplings are applied by id at
64    /// `step_until` time, so order does not matter).
65    pub fn add_coupling(&mut self, coupling: Coupling) {
66        self.couplings.push(coupling);
67    }
68
69    /// Borrow a registered model by id.
70    pub fn model(&self, id: &str) -> Option<&dyn SubModel> {
71        self.models.get(id).map(|m| m.as_ref())
72    }
73
74    /// Current global simulation time (the minimum model time, i.e. how far
75    /// all models have been driven together).
76    pub fn global_time(&self) -> f64 {
77        self.global_time
78    }
79
80    /// Advance all sub-models together until the global time reaches `target`.
81    ///
82    /// Sub-steps are chosen so that no model overshoots `target` and no model
83    /// exceeds its `max_step`. After each sub-step every coupling is applied.
84    ///
85    /// # Errors
86    ///
87    /// Returns [`SimError::NonAdvancingStep`] if `target <= global_time`, or
88    /// propagates any error returned by a sub-model's `advance`/`restore_state`
89    /// or by a coupling (e.g. [`SimError::UnknownModel`]).
90    ///
91    /// # Panics
92    ///
93    /// Panics if an internally registered model is missing from the registry
94    /// (a logic invariant; should never happen in practice).
95    pub fn step_until(&mut self, target: f64) -> Result<(), SimError> {
96        if target <= self.global_time {
97            return Err(SimError::NonAdvancingStep(target, self.global_time));
98        }
99        const EPS: f64 = 1e-12;
100        while self.global_time < target - EPS {
101            let mut dt = target - self.global_time;
102            for id in &self.order {
103                let m = self.models.get(id).expect("registered model");
104                let remaining = target - m.time();
105                if remaining > EPS {
106                    dt = dt.min(remaining).min(m.max_step());
107                }
108            }
109            if dt <= 0.0 {
110                break;
111            }
112            for id in &self.order {
113                let m = self.models.get_mut(id).expect("registered model");
114                if m.time() < target - EPS {
115                    m.advance(dt)?;
116                }
117            }
118            self.apply_couplings()?;
119            self.global_time += dt;
120        }
121        self.global_time = target;
122        Ok(())
123    }
124
125    fn apply_couplings(&mut self) -> Result<(), SimError> {
126        for c in &self.couplings {
127            let src = self
128                .model(c.source())
129                .ok_or_else(|| SimError::UnknownModel(c.source().to_string()))?
130                .state()
131                .to_vec();
132            let target = self
133                .models
134                .get_mut(c.target())
135                .ok_or_else(|| SimError::UnknownModel(c.target().to_string()))?;
136            let input = target
137                .input_mut()
138                .ok_or_else(|| SimError::CouplingTargetNoInput(c.target().to_string()))?;
139            c.apply(&src, input);
140        }
141        Ok(())
142    }
143
144    /// Capture a [`Checkpoint`] of the current global time and every model's
145    /// state and internal time.
146    ///
147    /// # Panics
148    ///
149    /// Panics if an internally registered model is missing from the registry
150    /// (a logic invariant; should never happen in practice).
151    pub fn snapshot(&self) -> Checkpoint {
152        let models = self
153            .order
154            .iter()
155            .map(|id| {
156                let m = self.models.get(id).expect("registered model");
157                (id.clone(), m.state().to_vec(), m.time())
158            })
159            .collect();
160        Checkpoint {
161            global_time: self.global_time,
162            models,
163        }
164    }
165
166    /// Restore every model (and the global clock) from a [`Checkpoint`]. Models
167    /// present in the checkpoint but not in the simulation are ignored; models
168    /// in the simulation but missing from the checkpoint keep their current
169    /// state.
170    ///
171    /// # Errors
172    ///
173    /// Returns [`SimError::UnknownModel`] if a model id present in the
174    /// checkpoint is not registered in the simulation, or propagates any error
175    /// from the sub-model's `restore_state` (e.g. a state-length mismatch).
176    pub fn restore(&mut self, checkpoint: &Checkpoint) -> Result<(), SimError> {
177        for (id, state, time) in &checkpoint.models {
178            let m = self
179                .models
180                .get_mut(id)
181                .ok_or_else(|| SimError::UnknownModel(id.clone()))?;
182            m.restore_state(state, *time)?;
183        }
184        self.global_time = checkpoint.global_time;
185        Ok(())
186    }
187}
188
189impl Default for Simulation {
190    fn default() -> Self {
191        Self::new()
192    }
193}
194
195#[cfg(test)]
196mod tests {
197    use approx::assert_abs_diff_eq;
198
199    use super::*;
200    use crate::Coupling;
201    use crate::diffusion_model::DiffusionSubModel;
202    use crate::ode_model::OdeSubModel;
203
204    fn decay(id: &str) -> OdeSubModel {
205        OdeSubModel::new(id, |_t, y, dydt| dydt[0] = -y[0], vec![1.0], 0.0)
206    }
207
208    #[test]
209    fn single_ode_matches_analytic() {
210        let mut sim = Simulation::new();
211        sim.add_model(decay("decay")).unwrap();
212        sim.step_until(1.0).unwrap();
213        let y = sim.model("decay").unwrap().state()[0];
214        assert_abs_diff_eq!(y, std::f64::consts::E.recip(), epsilon = 1e-3);
215    }
216
217    #[test]
218    fn non_advancing_step_is_rejected() {
219        let mut sim = Simulation::new();
220        sim.add_model(decay("decay")).unwrap();
221        assert!(matches!(
222            sim.step_until(0.0),
223            Err(SimError::NonAdvancingStep(_, _))
224        ));
225    }
226
227    #[test]
228    fn duplicate_model_is_rejected() {
229        let mut sim = Simulation::new();
230        sim.add_model(decay("decay")).unwrap();
231        assert!(matches!(
232            sim.add_model(decay("decay")),
233            Err(SimError::DuplicateModel(_))
234        ));
235    }
236
237    #[test]
238    fn two_scale_substepping_respects_max_step() {
239        // Two fast/slow decay ODEs; the orchestrator must sub-divide to honour
240        // the smaller max_step while still landing both at the target time.
241        let mut fast = decay("fast");
242        fast.set_max_step(0.05);
243        let mut slow = decay("slow");
244        slow.set_max_step(0.1);
245
246        let mut sim = Simulation::new();
247        sim.add_model(fast).unwrap();
248        sim.add_model(slow).unwrap();
249        sim.step_until(0.2).unwrap();
250
251        assert_abs_diff_eq!(sim.model("fast").unwrap().time(), 0.2, epsilon = 1e-9);
252        assert_abs_diff_eq!(sim.model("slow").unwrap().time(), 0.2, epsilon = 1e-9);
253        assert_eq!(sim.global_time(), 0.2);
254    }
255
256    #[test]
257    fn cross_scale_coupling_drives_target() {
258        // Source: y' = 1, y(0)=0  ->  drives a diffusion field via coupling.
259        // A small max_step forces the orchestrator to sub-step, so the
260        // one-step-lagged coupling actually feeds the field across sub-steps.
261        let mut source = OdeSubModel::new("src", |_t, _y, dydt| dydt[0] = 1.0, vec![0.0], 0.0);
262        source.set_max_step(0.1);
263        let grid = tpt_sci_grid::UniformGrid1D::new(9, 0.0, 1.0).unwrap();
264        let target = DiffusionSubModel::new(
265            "field",
266            grid,
267            1e-3,
268            tpt_sci_grid::Boundary::Neumann,
269            vec![0.0; 9],
270        )
271        .unwrap();
272
273        let mut sim = Simulation::new();
274        sim.add_model(source).unwrap();
275        sim.add_model(target).unwrap();
276        // Broadcast the source scalar onto every diffusion node.
277        sim.add_coupling(Coupling::new("src", "field", |src, input| {
278            for x in input.iter_mut() {
279                *x = src[0];
280            }
281        }));
282        sim.step_until(0.5).unwrap();
283
284        // The field must have been driven positive by the source forcing.
285        let field = sim.model("field").unwrap().state();
286        assert!(field.iter().all(|&v| v > 0.0));
287    }
288
289    #[test]
290    fn checkpoint_round_trips() {
291        let mut sim = Simulation::new();
292        sim.add_model(decay("decay")).unwrap();
293        sim.step_until(0.5).unwrap();
294        let checkpoint = sim.snapshot();
295        let at_half = sim.model("decay").unwrap().state()[0];
296
297        sim.step_until(1.0).unwrap();
298        assert_abs_diff_eq!(
299            sim.model("decay").unwrap().state()[0],
300            std::f64::consts::E.recip(),
301            epsilon = 1e-3
302        );
303
304        sim.restore(&checkpoint).unwrap();
305        assert_abs_diff_eq!(
306            sim.model("decay").unwrap().state()[0],
307            at_half,
308            epsilon = 1e-12
309        );
310        assert_abs_diff_eq!(sim.global_time(), 0.5, epsilon = 1e-12);
311    }
312}