1use std::collections::HashMap;
2
3use crate::coupling::Coupling;
4use crate::error::SimError;
5use crate::submodel::SubModel;
6
7#[derive(Debug, Clone)]
14pub struct Checkpoint {
15 pub global_time: f64,
17 pub models: Vec<(String, Vec<f64>, f64)>,
19}
20
21pub 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 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 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 pub fn add_coupling(&mut self, coupling: Coupling) {
66 self.couplings.push(coupling);
67 }
68
69 pub fn model(&self, id: &str) -> Option<&dyn SubModel> {
71 self.models.get(id).map(|m| m.as_ref())
72 }
73
74 pub fn global_time(&self) -> f64 {
77 self.global_time
78 }
79
80 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 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 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 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 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 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 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}