1use lib_jsl_core::ErrorsJSL;
15use std::collections::BTreeMap;
16
17#[derive(Clone, Copy, Debug, PartialEq)]
19pub enum EndCondition {
20 Dirichlet(f64),
22 Flux(f64),
24}
25
26pub fn fem_1d<P, Q, F>(p: P, q: Q, f: F, nodes: &[f64], left: EndCondition, right: EndCondition) -> Result<Vec<f64>, ErrorsJSL>
28where
29 P: Fn(f64) -> f64,
30 Q: Fn(f64) -> f64,
31 F: Fn(f64) -> f64,
32{
33 let n = nodes.len();
34 if n < 2 || nodes.windows(2).any(|w| w[1] <= w[0]) {
35 return Err(ErrorsJSL::InvalidInputRange("Need at least two strictly increasing nodes."));
36 }
37 let (mut lower, mut diagonal, mut upper, mut load) = (vec![0.0; n], vec![0.0; n], vec![0.0; n], vec![0.0; n]);
39 let gauss = [(0.5 - 0.5 / 3f64.sqrt(), 0.5), (0.5 + 0.5 / 3f64.sqrt(), 0.5)];
40 for e in 0..n - 1 {
41 let (x0, x1) = (nodes[e], nodes[e + 1]);
42 let h = x1 - x0;
43 let mut k = [[0.0; 2]; 2];
44 let mut b = [0.0; 2];
45 for &(s, w) in &gauss {
46 let x = x0 + s * h;
47 let phi = [1.0 - s, s];
48 let dphi = [-1.0 / h, 1.0 / h];
49 let (pv, qv, fv) = (p(x), q(x), f(x));
50 for i in 0..2 {
51 b[i] += w * h * fv * phi[i];
52 for j in 0..2 {
53 k[i][j] += w * h * (pv * dphi[i] * dphi[j] + qv * phi[i] * phi[j]);
54 }
55 }
56 }
57 diagonal[e] += k[0][0];
58 diagonal[e + 1] += k[1][1];
59 upper[e] += k[0][1];
60 lower[e + 1] += k[1][0];
61 load[e] += b[0];
62 load[e + 1] += b[1];
63 }
64 for (end, condition) in [(0, left), (n - 1, right)] {
65 match condition {
66 EndCondition::Flux(g) => load[end] += g,
67 EndCondition::Dirichlet(value) => {
68 if end == 0 {
70 load[1] -= lower[1] * value;
71 lower[1] = 0.0;
72 upper[0] = 0.0;
73 } else {
74 load[n - 2] -= upper[n - 2] * value;
75 upper[n - 2] = 0.0;
76 lower[n - 1] = 0.0;
77 }
78 diagonal[end] = 1.0;
79 load[end] = value;
80 }
81 }
82 }
83 super::finite_differences::solve_tridiagonal(&lower, &diagonal, &upper, &load)
84}
85
86#[derive(Debug, Clone)]
88pub struct TriangleMesh {
89 pub nodes: Vec<[f64; 2]>,
91 pub triangles: Vec<[usize; 3]>,
93}
94
95impl TriangleMesh {
96 pub fn rectangle(width: f64, height: f64, nx: usize, ny: usize) -> Self {
99 let nodes = (0..=ny).flat_map(|j| (0..=nx).map(move |i| [width * i as f64 / nx as f64, height * j as f64 / ny as f64])).collect();
100 let id = |i: usize, j: usize| j * (nx + 1) + i;
101 let triangles = (0..ny).flat_map(|j| (0..nx).flat_map(move |i| [[id(i, j), id(i + 1, j), id(i + 1, j + 1)], [id(i, j), id(i + 1, j + 1), id(i, j + 1)]])).collect();
102 TriangleMesh { nodes, triangles }
103 }
104
105 pub fn box_boundary_nodes(&self) -> Vec<usize> {
107 let (mut lo, mut hi) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]);
108 for p in &self.nodes {
109 for d in 0..2 {
110 lo[d] = lo[d].min(p[d]);
111 hi[d] = hi[d].max(p[d]);
112 }
113 }
114 let tol = 1e-12 * (hi[0] - lo[0]).max(hi[1] - lo[1]);
115 (0..self.nodes.len()).filter(|&i| (0..2).any(|d| (self.nodes[i][d] - lo[d]).abs() < tol || (self.nodes[i][d] - hi[d]).abs() < tol)).collect()
116 }
117}
118
119pub fn fem_poisson_2d<K, F, G>(mesh: &TriangleMesh, k: K, f: F, g: G, dirichlet_nodes: &[usize]) -> Result<Vec<f64>, ErrorsJSL>
122where
123 K: Fn(f64, f64) -> f64,
124 F: Fn(f64, f64) -> f64,
125 G: Fn(f64, f64) -> f64,
126{
127 let n = mesh.nodes.len();
128 if mesh.triangles.iter().flatten().any(|&v| v >= n) || dirichlet_nodes.iter().any(|&v| v >= n) {
129 return Err(ErrorsJSL::InvalidInputRange("Mesh or boundary index out of range."));
130 }
131 if dirichlet_nodes.is_empty() {
132 return Err(ErrorsJSL::InvalidInputRange("Need at least one Dirichlet node for a unique solution."));
133 }
134 let mut rows: Vec<BTreeMap<usize, f64>> = vec![BTreeMap::new(); n];
135 let mut load = vec![0.0; n];
136 for t in &mesh.triangles {
138 let [p0, p1, p2] = [mesh.nodes[t[0]], mesh.nodes[t[1]], mesh.nodes[t[2]]];
139 let area2 = (p1[0] - p0[0]) * (p2[1] - p0[1]) - (p2[0] - p0[0]) * (p1[1] - p0[1]);
140 if area2.abs() < 1e-300 {
141 return Err(ErrorsJSL::InvalidInputRange("Degenerate triangle in the mesh."));
142 }
143 let area = 0.5 * area2.abs();
144 let grad = [
146 [(p1[1] - p2[1]) / area2, (p2[0] - p1[0]) / area2],
147 [(p2[1] - p0[1]) / area2, (p0[0] - p2[0]) / area2],
148 [(p0[1] - p1[1]) / area2, (p1[0] - p0[0]) / area2],
149 ];
150 let centroid = [(p0[0] + p1[0] + p2[0]) / 3.0, (p0[1] + p1[1] + p2[1]) / 3.0];
151 let kc = k(centroid[0], centroid[1]);
152 let mids = [[(p0[0] + p1[0]) / 2.0, (p0[1] + p1[1]) / 2.0], [(p1[0] + p2[0]) / 2.0, (p1[1] + p2[1]) / 2.0], [(p2[0] + p0[0]) / 2.0, (p2[1] + p0[1]) / 2.0]];
154 let fm: Vec<f64> = mids.iter().map(|m| f(m[0], m[1])).collect();
155 let phi_at_mid = [[0.5, 0.0, 0.5], [0.5, 0.5, 0.0], [0.0, 0.5, 0.5]];
157 for a in 0..3 {
158 load[t[a]] += area / 3.0 * (0..3).map(|m| fm[m] * phi_at_mid[a][m]).sum::<f64>();
159 for b in 0..3 {
160 *rows[t[a]].entry(t[b]).or_insert(0.0) += kc * area * (grad[a][0] * grad[b][0] + grad[a][1] * grad[b][1]);
161 }
162 }
163 }
164 let mut fixed = vec![None; n];
167 for &d in dirichlet_nodes {
168 let p = mesh.nodes[d];
169 fixed[d] = Some(g(p[0], p[1]));
170 }
171 for i in 0..n {
172 if fixed[i].is_some() {
173 continue;
174 }
175 let shift: f64 = rows[i].iter().filter_map(|(&j, &v)| fixed[j].map(|gj| v * gj)).sum();
176 load[i] -= shift;
177 }
178 let free: Vec<usize> = (0..n).filter(|&i| fixed[i].is_none()).collect();
179 let mut position = vec![usize::MAX; n];
180 free.iter().enumerate().for_each(|(k, &i)| position[i] = k);
181 let csr: Vec<Vec<(usize, f64)>> = free.iter().map(|&i| rows[i].iter().filter(|(j, _)| position[**j] != usize::MAX).map(|(&j, &v)| (position[j], v)).collect()).collect();
182 let diagonal: Vec<f64> = free.iter().map(|&i| rows[i][&i]).collect();
183 let b: Vec<f64> = free.iter().map(|&i| load[i]).collect();
184 let solution = preconditioned_cg(&csr, &diagonal, &b, 1e-12, 20 * free.len().max(50))?;
186 let mut u: Vec<f64> = fixed.iter().map(|v| v.unwrap_or(0.0)).collect();
187 free.iter().zip(solution).for_each(|(&i, v)| u[i] = v);
188 Ok(u)
189}
190
191fn preconditioned_cg(a: &[Vec<(usize, f64)>], diagonal: &[f64], b: &[f64], tolerance: f64, max_iterations: usize) -> Result<Vec<f64>, ErrorsJSL> {
192 let apply = |v: &[f64]| -> Vec<f64> { a.iter().map(|row| row.iter().map(|&(j, w)| w * v[j]).sum()).collect() };
193 let dot = |x: &[f64], y: &[f64]| x.iter().zip(y).map(|(p, q)| p * q).sum::<f64>();
194 let mut x = vec![0.0; b.len()];
195 let mut r = b.to_vec();
196 let mut z: Vec<f64> = r.iter().zip(diagonal).map(|(ri, d)| ri / d).collect();
197 let mut p = z.clone();
198 let mut rz = dot(&r, &z);
199 let target = tolerance * dot(b, b).sqrt().max(1e-300);
200 for _ in 0..max_iterations {
201 if dot(&r, &r).sqrt() <= target {
202 return Ok(x);
203 }
204 let ap = apply(&p);
205 let alpha = rz / dot(&p, &ap);
206 x.iter_mut().zip(&p).for_each(|(xi, pi)| *xi += alpha * pi);
207 r.iter_mut().zip(&ap).for_each(|(ri, api)| *ri -= alpha * api);
208 z = r.iter().zip(diagonal).map(|(ri, d)| ri / d).collect();
209 let rz_new = dot(&r, &z);
210 let beta = rz_new / rz;
211 p.iter_mut().zip(&z).for_each(|(pi, zi)| *pi = zi + beta * *pi);
212 rz = rz_new;
213 }
214 if dot(&r, &r).sqrt() <= 1e3 * target { Ok(x) } else { Err(ErrorsJSL::RuntimeError("Conjugate gradients did not converge.")) }
215}
216
217#[cfg(test)]
218mod tests {
219 use super::*;
220 use std::f64::consts::PI;
221
222 #[test]
223 fn one_dimensional_problems_converge_and_handle_both_end_conditions() {
224 let error = |n: usize| {
226 let nodes: Vec<f64> = (0..=n).map(|i| i as f64 / n as f64).collect();
227 let u = fem_1d(|_| 1.0, |_| 0.0, |x| PI * PI * (PI * x).sin(), &nodes, EndCondition::Dirichlet(0.0), EndCondition::Dirichlet(0.0)).unwrap();
228 nodes.iter().zip(&u).map(|(x, v)| (v - (PI * x).sin()).abs()).fold(0.0, f64::max)
229 };
230 let (e1, e2) = (error(10), error(20));
231 assert!(e2 < 1e-3 && e1 / e2 > 3.5, "{e1} {e2}");
232 let f = |x: f64| -(2.0 + 4.0 * x) + x * x;
235 let nodes: Vec<f64> = (0..=40).map(|i| i as f64 / 40.0).collect();
236 let u = fem_1d(|x| 1.0 + x, |_| 1.0, f, &nodes, EndCondition::Dirichlet(0.0), EndCondition::Flux(4.0)).unwrap();
237 assert!(nodes.iter().zip(&u).all(|(x, v)| (v - x * x).abs() < 1e-3), "{:?}", &u[38..]);
238 assert!(fem_1d(|_| 1.0, |_| 0.0, |_| 0.0, &[0.0, 0.0], EndCondition::Dirichlet(0.0), EndCondition::Dirichlet(0.0)).is_err());
239 }
240
241 #[test]
242 fn two_dimensional_poisson_converges_at_second_order() {
243 let exact = |x: f64, y: f64| (PI * x).sin() * (PI * y).sin() + x - 2.0 * y;
244 let f = |x: f64, y: f64| 2.0 * PI * PI * (PI * x).sin() * (PI * y).sin();
245 let error = |n: usize| {
246 let mesh = TriangleMesh::rectangle(1.0, 1.0, n, n);
247 let u = fem_poisson_2d(&mesh, |_, _| 1.0, f, exact, &mesh.box_boundary_nodes()).unwrap();
248 mesh.nodes.iter().zip(&u).map(|(p, v)| (v - exact(p[0], p[1])).abs()).fold(0.0, f64::max)
249 };
250 let (coarse, fine) = (error(8), error(16));
251 assert!(fine < 0.01 && coarse / fine > 3.3, "{coarse} {fine}");
252 let mesh = TriangleMesh::rectangle(2.0, 1.0, 6, 3);
254 let u = fem_poisson_2d(&mesh, |_, _| 3.0, |_, _| 0.0, |x, y| 1.0 + 2.0 * x - y, &mesh.box_boundary_nodes()).unwrap();
255 assert!(mesh.nodes.iter().zip(&u).all(|(p, v)| (v - (1.0 + 2.0 * p[0] - p[1])).abs() < 1e-10));
256 assert!(fem_poisson_2d(&mesh, |_, _| 1.0, |_, _| 1.0, |_, _| 0.0, &[]).is_err());
257 }
258}