Skip to main content

tpt_sci_sim_core/
diffusion_model.rs

1use tpt_math_linalg::tpt_math_linalg_dense::{DMatrix, DVector};
2use tpt_sci_grid::{Boundary, UniformGrid1D, laplacian_1d};
3
4use crate::SimError;
5use crate::submodel::SubModel;
6
7/// A [`SubModel`] integrating the 1-D diffusion equation on a uniform grid
8/// with explicit Euler time stepping.
9///
10/// The discrete semi-discrete system is
11/// `∂u/∂t = D · L u + s`, where `L` is the [`laplacian_1d`] assembled by
12/// [`tpt_sci_grid`], `D` is the diffusion coefficient, and `s` is an optional
13/// per-node forcing term. The forcing is held in the model's **input buffer**,
14/// so a coupling can drive the field from another sub-model's state — the
15/// canonical cross-scale pattern (e.g. a fast reaction ODE feeding a slow
16/// diffusion field).
17pub struct DiffusionSubModel {
18    id: String,
19    laplacian: DMatrix,
20    coeff: f64,
21    state: Vec<f64>,
22    input: Vec<f64>,
23    time: f64,
24    max_step: f64,
25}
26
27impl DiffusionSubModel {
28    /// Build a diffusion sub-model on `grid` with diffusion coefficient `coeff`
29    /// and boundary condition `bc`. The initial field is `u0` (one value per
30    /// grid node).
31    ///
32    /// # Errors
33    ///
34    /// Returns [`SimError::Advance`] if `u0`'s length does not match the number
35    /// of grid nodes.
36    pub fn new(
37        id: &str,
38        grid: UniformGrid1D,
39        coeff: f64,
40        bc: Boundary,
41        u0: Vec<f64>,
42    ) -> Result<Self, SimError> {
43        if u0.len() != grid.n() {
44            return Err(SimError::Advance(
45                id.to_string(),
46                format!(
47                    "initial field length {} != grid size {}",
48                    u0.len(),
49                    grid.n()
50                ),
51            ));
52        }
53        // Stability-limited explicit-Euler step for 1-D diffusion on a uniform
54        // grid: dt <= dx^2 / (2 D). Use a safe fraction of that.
55        let stability = grid.dx() * grid.dx() / (2.0 * coeff.max(f64::MIN_POSITIVE));
56        Ok(Self {
57            id: id.to_string(),
58            laplacian: laplacian_1d(&grid, bc),
59            coeff,
60            state: u0.clone(),
61            input: vec![0.0; u0.len()],
62            time: 0.0,
63            max_step: 0.9 * stability,
64        })
65    }
66
67    /// Diffusion coefficient.
68    pub fn coeff(&self) -> f64 {
69        self.coeff
70    }
71
72    /// Largest stable internal step (derived from the explicit-Euler stability
73    /// limit on construction; can be overridden with `set_max_step`).
74    pub fn set_max_step(&mut self, max_step: f64) {
75        self.max_step = max_step;
76    }
77}
78
79impl SubModel for DiffusionSubModel {
80    fn id(&self) -> &str {
81        &self.id
82    }
83
84    fn time(&self) -> f64 {
85        self.time
86    }
87
88    fn max_step(&self) -> f64 {
89        self.max_step
90    }
91
92    fn advance(&mut self, dt: f64) -> Result<(), SimError> {
93        let u = DVector::from_vec(self.state.clone());
94        let lap = self.laplacian.clone() * u;
95        let mut next = self.state.clone();
96        for i in 0..next.len() {
97            next[i] += dt * (self.coeff * lap[i] + self.input[i]);
98        }
99        self.state = next;
100        self.time += dt;
101        Ok(())
102    }
103
104    fn state(&self) -> &[f64] {
105        &self.state
106    }
107
108    fn input_mut(&mut self) -> Option<&mut [f64]> {
109        Some(&mut self.input)
110    }
111
112    fn restore_state(&mut self, state: &[f64], time: f64) -> Result<(), SimError> {
113        if state.len() != self.state.len() {
114            return Err(SimError::Advance(
115                self.id.clone(),
116                format!(
117                    "checkpoint state length {} != model state length {}",
118                    state.len(),
119                    self.state.len()
120                ),
121            ));
122        }
123        self.state = state.to_vec();
124        self.time = time;
125        Ok(())
126    }
127}