qualia_core_db/solvers/calculus/
potential.rs1#[derive(Debug, Clone, Copy, PartialEq)]
4pub enum PotentialError {
5 InvalidGrid,
6 DimensionMismatch,
7 NonFiniteInput,
8 ConvergenceFailed { residual: f64 },
9}
10
11#[repr(C)]
12#[derive(Debug, Clone, Copy, PartialEq)]
13pub struct PoissonGrid {
14 pub width: usize,
15 pub height: usize,
16 pub spacing: f64,
17}
18
19impl PoissonGrid {
20 pub fn point_count(self) -> Option<usize> {
22 self.width.checked_mul(self.height)
23 }
24}
25
26#[repr(C)]
27#[derive(Debug, Clone, Copy, PartialEq)]
28pub struct PoissonReport {
29 pub iterations: u32,
30 pub residual_inf: f64,
31 pub minimum: f64,
32 pub maximum: f64,
33}
34
35pub fn solve_poisson_dirichlet(
37 grid: PoissonGrid,
38 source: &[f64],
39 boundary_values: &[f64],
40 solution: &mut [f64],
41 tolerance: f64,
42 max_iterations: u32,
43) -> Result<PoissonReport, PotentialError> {
44 let count = grid.point_count().ok_or(PotentialError::InvalidGrid)?;
45 if grid.width < 3
46 || grid.height < 3
47 || !grid.spacing.is_finite()
48 || grid.spacing <= 0.0
49 || !tolerance.is_finite()
50 || tolerance <= 0.0
51 || max_iterations == 0
52 {
53 return Err(PotentialError::InvalidGrid);
54 }
55 if source.len() != count || boundary_values.len() != count || solution.len() != count {
56 return Err(PotentialError::DimensionMismatch);
57 }
58 if source
59 .iter()
60 .chain(boundary_values)
61 .any(|value| !value.is_finite())
62 {
63 return Err(PotentialError::NonFiniteInput);
64 }
65
66 for y in 0..grid.height {
67 for x in 0..grid.width {
68 let index = y * grid.width + x;
69 if x == 0 || y == 0 || x + 1 == grid.width || y + 1 == grid.height {
70 solution[index] = boundary_values[index];
71 } else if !solution[index].is_finite() {
72 solution[index] = 0.0;
73 }
74 }
75 }
76
77 let h2 = grid.spacing * grid.spacing;
78 let mut residual = f64::INFINITY;
79 for iteration in 1..=max_iterations {
80 for y in 1..grid.height - 1 {
81 for x in 1..grid.width - 1 {
82 let index = y * grid.width + x;
83 solution[index] = 0.25
84 * (solution[index - 1]
85 + solution[index + 1]
86 + solution[index - grid.width]
87 + solution[index + grid.width]
88 + h2 * source[index]);
89 }
90 }
91
92 residual = 0.0;
93 for y in 1..grid.height - 1 {
94 for x in 1..grid.width - 1 {
95 let index = y * grid.width + x;
96 let discrete = (4.0 * solution[index]
97 - solution[index - 1]
98 - solution[index + 1]
99 - solution[index - grid.width]
100 - solution[index + grid.width])
101 / h2;
102 residual = residual.max((discrete - source[index]).abs());
103 }
104 }
105 if residual <= tolerance {
106 let (minimum, maximum) = solution.iter().fold(
107 (f64::INFINITY, f64::NEG_INFINITY),
108 |(minimum, maximum), value| (minimum.min(*value), maximum.max(*value)),
109 );
110 return Ok(PoissonReport {
111 iterations: iteration,
112 residual_inf: residual,
113 minimum,
114 maximum,
115 });
116 }
117 }
118 Err(PotentialError::ConvergenceFailed { residual })
119}
120
121pub fn discrete_maximum_principle_holds(
123 grid: PoissonGrid,
124 source: &[f64],
125 boundary_values: &[f64],
126 solution: &[f64],
127 tolerance: f64,
128) -> Result<bool, PotentialError> {
129 let count = grid.point_count().ok_or(PotentialError::InvalidGrid)?;
130 if source.len() != count || boundary_values.len() != count || solution.len() != count {
131 return Err(PotentialError::DimensionMismatch);
132 }
133 if source.iter().any(|value| value.abs() > tolerance) {
134 return Ok(false);
135 }
136 let mut boundary_minimum = f64::INFINITY;
137 let mut boundary_maximum = f64::NEG_INFINITY;
138 for y in 0..grid.height {
139 for x in 0..grid.width {
140 if x == 0 || y == 0 || x + 1 == grid.width || y + 1 == grid.height {
141 let value = boundary_values[y * grid.width + x];
142 boundary_minimum = boundary_minimum.min(value);
143 boundary_maximum = boundary_maximum.max(value);
144 }
145 }
146 }
147 Ok(solution.iter().all(|value| {
148 *value >= boundary_minimum - tolerance && *value <= boundary_maximum + tolerance
149 }))
150}
151
152#[cfg(test)]
153mod tests {
154 use super::*;
155
156 #[test]
157 fn manufactured_poisson_solution_converges_with_residual() {
158 const N: usize = 25;
159 let grid = PoissonGrid {
160 width: N,
161 height: N,
162 spacing: 1.0 / (N - 1) as f64,
163 };
164 let mut source = vec![0.0; N * N];
165 let boundary = vec![0.0; N * N];
166 let mut solution = vec![0.0; N * N];
167 for y in 0..N {
168 let yy = y as f64 * grid.spacing;
169 for x in 0..N {
170 let xx = x as f64 * grid.spacing;
171 source[y * N + x] = 2.0 * (yy - yy * yy) + 2.0 * (xx - xx * xx);
172 }
173 }
174 let report =
175 solve_poisson_dirichlet(grid, &source, &boundary, &mut solution, 1e-8, 50_000).unwrap();
176 assert!(report.residual_inf <= 1e-8);
177 let mut maximum_error = 0.0_f64;
178 for y in 0..N {
179 let yy = y as f64 * grid.spacing;
180 for x in 0..N {
181 let xx = x as f64 * grid.spacing;
182 let exact = xx * (1.0 - xx) * yy * (1.0 - yy);
183 maximum_error = maximum_error.max((solution[y * N + x] - exact).abs());
184 }
185 }
186 assert!(maximum_error < 5e-4);
187 }
188
189 #[test]
190 fn harmonic_solution_obeys_discrete_maximum_principle() {
191 const N: usize = 9;
192 let grid = PoissonGrid {
193 width: N,
194 height: N,
195 spacing: 1.0 / (N - 1) as f64,
196 };
197 let source = [0.0; N * N];
198 let mut boundary = [0.0; N * N];
199 for y in 0..N {
200 boundary[y * N + N - 1] = 1.0;
201 }
202 let mut solution = [0.0; N * N];
203 solve_poisson_dirichlet(grid, &source, &boundary, &mut solution, 1e-9, 20_000).unwrap();
204 assert!(
205 discrete_maximum_principle_holds(grid, &source, &boundary, &solution, 1e-9).unwrap()
206 );
207 }
208}