tpt_sci_sim_core/
diffusion_model.rs1use 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
7pub 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 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 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 pub fn coeff(&self) -> f64 {
69 self.coeff
70 }
71
72 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}