use std::collections::HashMap;
use crate::coupling::Coupling;
use crate::error::SimError;
use crate::submodel::SubModel;
#[derive(Debug, Clone)]
pub struct Checkpoint {
pub global_time: f64,
pub models: Vec<(String, Vec<f64>, f64)>,
}
pub struct Simulation {
models: HashMap<String, Box<dyn SubModel>>,
order: Vec<String>,
couplings: Vec<Coupling>,
global_time: f64,
}
impl Simulation {
pub fn new() -> Self {
Self {
models: HashMap::new(),
order: Vec::new(),
couplings: Vec::new(),
global_time: 0.0,
}
}
pub fn add_model(&mut self, model: impl SubModel + 'static) -> Result<(), SimError> {
let id = model.id().to_string();
if self.models.contains_key(&id) {
return Err(SimError::DuplicateModel(id));
}
self.order.push(id.clone());
self.models.insert(id, Box::new(model));
Ok(())
}
pub fn add_coupling(&mut self, coupling: Coupling) {
self.couplings.push(coupling);
}
pub fn model(&self, id: &str) -> Option<&dyn SubModel> {
self.models.get(id).map(|m| m.as_ref())
}
pub fn global_time(&self) -> f64 {
self.global_time
}
pub fn step_until(&mut self, target: f64) -> Result<(), SimError> {
if target <= self.global_time {
return Err(SimError::NonAdvancingStep(target, self.global_time));
}
const EPS: f64 = 1e-12;
while self.global_time < target - EPS {
let mut dt = target - self.global_time;
for id in &self.order {
let m = self.models.get(id).expect("registered model");
let remaining = target - m.time();
if remaining > EPS {
dt = dt.min(remaining).min(m.max_step());
}
}
if dt <= 0.0 {
break;
}
for id in &self.order {
let m = self.models.get_mut(id).expect("registered model");
if m.time() < target - EPS {
m.advance(dt)?;
}
}
self.apply_couplings()?;
self.global_time += dt;
}
self.global_time = target;
Ok(())
}
fn apply_couplings(&mut self) -> Result<(), SimError> {
for c in &self.couplings {
let src = self
.model(c.source())
.ok_or_else(|| SimError::UnknownModel(c.source().to_string()))?
.state()
.to_vec();
let target = self
.models
.get_mut(c.target())
.ok_or_else(|| SimError::UnknownModel(c.target().to_string()))?;
let input = target
.input_mut()
.ok_or_else(|| SimError::CouplingTargetNoInput(c.target().to_string()))?;
c.apply(&src, input);
}
Ok(())
}
pub fn snapshot(&self) -> Checkpoint {
let models = self
.order
.iter()
.map(|id| {
let m = self.models.get(id).expect("registered model");
(id.clone(), m.state().to_vec(), m.time())
})
.collect();
Checkpoint {
global_time: self.global_time,
models,
}
}
pub fn restore(&mut self, checkpoint: &Checkpoint) -> Result<(), SimError> {
for (id, state, time) in &checkpoint.models {
let m = self
.models
.get_mut(id)
.ok_or_else(|| SimError::UnknownModel(id.clone()))?;
m.restore_state(state, *time)?;
}
self.global_time = checkpoint.global_time;
Ok(())
}
}
impl Default for Simulation {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use approx::assert_abs_diff_eq;
use super::*;
use crate::Coupling;
use crate::diffusion_model::DiffusionSubModel;
use crate::ode_model::OdeSubModel;
fn decay(id: &str) -> OdeSubModel {
OdeSubModel::new(id, |_t, y, dydt| dydt[0] = -y[0], vec![1.0], 0.0)
}
#[test]
fn single_ode_matches_analytic() {
let mut sim = Simulation::new();
sim.add_model(decay("decay")).unwrap();
sim.step_until(1.0).unwrap();
let y = sim.model("decay").unwrap().state()[0];
assert_abs_diff_eq!(y, std::f64::consts::E.recip(), epsilon = 1e-3);
}
#[test]
fn non_advancing_step_is_rejected() {
let mut sim = Simulation::new();
sim.add_model(decay("decay")).unwrap();
assert!(matches!(
sim.step_until(0.0),
Err(SimError::NonAdvancingStep(_, _))
));
}
#[test]
fn duplicate_model_is_rejected() {
let mut sim = Simulation::new();
sim.add_model(decay("decay")).unwrap();
assert!(matches!(
sim.add_model(decay("decay")),
Err(SimError::DuplicateModel(_))
));
}
#[test]
fn two_scale_substepping_respects_max_step() {
let mut fast = decay("fast");
fast.set_max_step(0.05);
let mut slow = decay("slow");
slow.set_max_step(0.1);
let mut sim = Simulation::new();
sim.add_model(fast).unwrap();
sim.add_model(slow).unwrap();
sim.step_until(0.2).unwrap();
assert_abs_diff_eq!(sim.model("fast").unwrap().time(), 0.2, epsilon = 1e-9);
assert_abs_diff_eq!(sim.model("slow").unwrap().time(), 0.2, epsilon = 1e-9);
assert_eq!(sim.global_time(), 0.2);
}
#[test]
fn cross_scale_coupling_drives_target() {
let mut source = OdeSubModel::new("src", |_t, _y, dydt| dydt[0] = 1.0, vec![0.0], 0.0);
source.set_max_step(0.1);
let grid = tpt_sci_grid::UniformGrid1D::new(9, 0.0, 1.0).unwrap();
let target = DiffusionSubModel::new(
"field",
grid,
1e-3,
tpt_sci_grid::Boundary::Neumann,
vec![0.0; 9],
)
.unwrap();
let mut sim = Simulation::new();
sim.add_model(source).unwrap();
sim.add_model(target).unwrap();
sim.add_coupling(Coupling::new("src", "field", |src, input| {
for x in input.iter_mut() {
*x = src[0];
}
}));
sim.step_until(0.5).unwrap();
let field = sim.model("field").unwrap().state();
assert!(field.iter().all(|&v| v > 0.0));
}
#[test]
fn checkpoint_round_trips() {
let mut sim = Simulation::new();
sim.add_model(decay("decay")).unwrap();
sim.step_until(0.5).unwrap();
let checkpoint = sim.snapshot();
let at_half = sim.model("decay").unwrap().state()[0];
sim.step_until(1.0).unwrap();
assert_abs_diff_eq!(
sim.model("decay").unwrap().state()[0],
std::f64::consts::E.recip(),
epsilon = 1e-3
);
sim.restore(&checkpoint).unwrap();
assert_abs_diff_eq!(
sim.model("decay").unwrap().state()[0],
at_half,
epsilon = 1e-12
);
assert_abs_diff_eq!(sim.global_time(), 0.5, epsilon = 1e-12);
}
}