Skip to main content

lib_jsl_integration/pde/
finite_differences.rs

1//! Finite difference solvers for model partial differential equations.
2//!
3//! * The heat equation `u_t = α u_xx` on `[0, L]` with Dirichlet ends: explicit FTCS (stable for
4//!   `r = α Δt / Δx² ≤ ½`) and Crank-Nicolson (unconditionally stable, second order in time and
5//!   space), the latter solving a tridiagonal system per step by the Thomas algorithm.
6//! * The wave equation `u_tt = c² u_xx` with fixed ends by the explicit leapfrog scheme (stable
7//!   for Courant number `c Δt / Δx ≤ 1`, exact on the grid when it equals one).
8//! * The Poisson equation `−∇²u = f` on a rectangle with Dirichlet data, by the five-point stencil
9//!   solved matrix-free with conjugate gradients.
10//!
11//! See the book entry [Finite difference methods](https://jwkunz.github.io/lib_jsl/book/integration/finite-differences.html).
12
13use lib_jsl_core::ErrorsJSL;
14
15/// Solves the tridiagonal system with sub-diagonal `a`, diagonal `b`, super-diagonal `c`
16/// (`a[0]` and `c[n−1]` unused) by the Thomas algorithm.
17pub fn solve_tridiagonal(a: &[f64], b: &[f64], c: &[f64], d: &[f64]) -> Result<Vec<f64>, ErrorsJSL> {
18    let n = d.len();
19    if a.len() != n || b.len() != n || c.len() != n || n == 0 {
20        return Err(ErrorsJSL::IncompatibleArraySizes((a.len(), n)));
21    }
22    // ANCHOR: thomas
23    let mut cp = vec![0.0; n];
24    let mut dp = vec![0.0; n];
25    let mut denominator = b[0];
26    if denominator == 0.0 {
27        return Err(ErrorsJSL::RuntimeError("Zero pivot in the tridiagonal solve."));
28    }
29    cp[0] = c[0] / denominator;
30    dp[0] = d[0] / denominator;
31    for i in 1..n {
32        denominator = b[i] - a[i] * cp[i - 1];
33        if denominator == 0.0 {
34            return Err(ErrorsJSL::RuntimeError("Zero pivot in the tridiagonal solve."));
35        }
36        cp[i] = c[i] / denominator;
37        dp[i] = (d[i] - a[i] * dp[i - 1]) / denominator;
38    }
39    let mut x = dp;
40    for i in (0..n - 1).rev() {
41        x[i] -= cp[i] * x[i + 1];
42    }
43    // ANCHOR_END: thomas
44    Ok(x)
45}
46
47/// The time-stepping scheme for [`heat_equation_1d`].
48#[derive(Clone, Copy, Debug, PartialEq, Eq)]
49pub enum HeatScheme {
50    /// Forward Euler in time, central in space.
51    Explicit,
52    /// The trapezoidal (Crank-Nicolson) average of explicit and implicit steps.
53    CrankNicolson,
54}
55
56/// Advances `u_t = α u_xx` on a uniform grid of `u0.len()` points spanning `[0, length]`
57/// (endpoints included and held at `left` and `right`) through `steps` steps of size `dt`.
58#[allow(clippy::too_many_arguments)]
59pub fn heat_equation_1d(u0: &[f64], length: f64, alpha: f64, dt: f64, steps: usize, left: f64, right: f64, scheme: HeatScheme) -> Result<Vec<f64>, ErrorsJSL> {
60    let n = u0.len();
61    if n < 3 || !(length > 0.0) || !(alpha > 0.0) || !(dt > 0.0) {
62        return Err(ErrorsJSL::InvalidInputRange("Need at least 3 points and positive length, diffusivity and step."));
63    }
64    let dx = length / (n - 1) as f64;
65    let r = alpha * dt / (dx * dx);
66    if scheme == HeatScheme::Explicit && r > 0.5 {
67        return Err(ErrorsJSL::InvalidInputRange("The explicit scheme is unstable for α Δt / Δx² > 1/2."));
68    }
69    let mut u = u0.to_vec();
70    u[0] = left;
71    u[n - 1] = right;
72    let m = n - 2;
73    let (a, b, c) = (vec![-r / 2.0; m], vec![1.0 + r; m], vec![-r / 2.0; m]);
74    for _ in 0..steps {
75        let next: Vec<f64> = match scheme {
76            HeatScheme::Explicit => (1..n - 1).map(|i| u[i] + r * (u[i - 1] - 2.0 * u[i] + u[i + 1])).collect(),
77            HeatScheme::CrankNicolson => {
78                let mut rhs: Vec<f64> = (1..n - 1).map(|i| u[i] + 0.5 * r * (u[i - 1] - 2.0 * u[i] + u[i + 1])).collect();
79                rhs[0] += 0.5 * r * left;
80                rhs[m - 1] += 0.5 * r * right;
81                solve_tridiagonal(&a, &b, &c, &rhs)?
82            }
83        };
84        u[1..n - 1].copy_from_slice(&next);
85    }
86    Ok(u)
87}
88
89/// Advances `u_tt = c² u_xx` with fixed ends `u = 0` from displacement `u0` and velocity `v0` on
90/// a uniform grid spanning `[0, length]`, by leapfrog with a Taylor first step; returns the
91/// displacement after `steps` steps of size `dt`.
92pub fn wave_equation_1d(u0: &[f64], v0: &[f64], length: f64, speed: f64, dt: f64, steps: usize) -> Result<Vec<f64>, ErrorsJSL> {
93    let n = u0.len();
94    if n < 3 || v0.len() != n || !(length > 0.0) || !(speed > 0.0) || !(dt > 0.0) {
95        return Err(ErrorsJSL::InvalidInputRange("Need matching grids of at least 3 points and positive parameters."));
96    }
97    let dx = length / (n - 1) as f64;
98    let courant2 = (speed * dt / dx).powi(2);
99    if courant2 > 1.0 + 1e-12 {
100        return Err(ErrorsJSL::InvalidInputRange("Leapfrog is unstable for a Courant number above one."));
101    }
102    let laplacian = |u: &[f64], i: usize| u[i - 1] - 2.0 * u[i] + u[i + 1];
103    let mut previous = u0.to_vec();
104    previous[0] = 0.0;
105    previous[n - 1] = 0.0;
106    if steps == 0 {
107        return Ok(previous);
108    }
109    let mut current = previous.clone();
110    for i in 1..n - 1 {
111        current[i] = previous[i] + dt * v0[i] + 0.5 * courant2 * laplacian(&previous, i);
112    }
113    for _ in 1..steps {
114        let mut next = vec![0.0; n];
115        for i in 1..n - 1 {
116            next[i] = 2.0 * current[i] - previous[i] + courant2 * laplacian(&current, i);
117        }
118        previous = current;
119        current = next;
120    }
121    Ok(current)
122}
123
124/// Solves `−∇²u = f` on `[0, width] × [0, height]` with `u = g` on the boundary, on an
125/// `nx × ny` grid of points including the boundary. Returns `u[j][i]` at `(i Δx, j Δy)`. The
126/// five-point system is symmetric positive definite and is solved by conjugate gradients to a
127/// relative residual of `1e-12`.
128pub fn poisson_2d<F, G>(f: F, boundary: G, width: f64, height: f64, nx: usize, ny: usize) -> Result<Vec<Vec<f64>>, ErrorsJSL>
129where
130    F: Fn(f64, f64) -> f64,
131    G: Fn(f64, f64) -> f64,
132{
133    if nx < 3 || ny < 3 || !(width > 0.0) || !(height > 0.0) {
134        return Err(ErrorsJSL::InvalidInputRange("Need at least 3 × 3 points on a positive rectangle."));
135    }
136    let (dx, dy) = (width / (nx - 1) as f64, height / (ny - 1) as f64);
137    let (ix, iy) = (nx - 2, ny - 2);
138    let (cx, cy) = (1.0 / (dx * dx), 1.0 / (dy * dy));
139    let point = |i: usize, j: usize| (i as f64 * dx, j as f64 * dy);
140    let mut u = vec![vec![0.0; nx]; ny];
141    for (j, row) in u.iter_mut().enumerate() {
142        for (i, v) in row.iter_mut().enumerate() {
143            if i == 0 || j == 0 || i == nx - 1 || j == ny - 1 {
144                let (x, y) = point(i, j);
145                *v = boundary(x, y);
146            }
147        }
148    }
149    // Right-hand side with the boundary values moved over.
150    let index = |i: usize, j: usize| (j - 1) * ix + (i - 1);
151    let mut b = vec![0.0; ix * iy];
152    for j in 1..ny - 1 {
153        for i in 1..nx - 1 {
154            let (x, y) = point(i, j);
155            let mut value = f(x, y);
156            if i == 1 {
157                value += cx * u[j][0];
158            }
159            if i == nx - 2 {
160                value += cx * u[j][nx - 1];
161            }
162            if j == 1 {
163                value += cy * u[0][i];
164            }
165            if j == ny - 2 {
166                value += cy * u[ny - 1][i];
167            }
168            b[index(i, j)] = value;
169        }
170    }
171    let apply = |v: &[f64]| -> Vec<f64> {
172        let mut out = vec![0.0; v.len()];
173        for j in 1..ny - 1 {
174            for i in 1..nx - 1 {
175                let k = index(i, j);
176                let mut s = 2.0 * (cx + cy) * v[k];
177                if i > 1 {
178                    s -= cx * v[k - 1];
179                }
180                if i < nx - 2 {
181                    s -= cx * v[k + 1];
182                }
183                if j > 1 {
184                    s -= cy * v[k - ix];
185                }
186                if j < ny - 2 {
187                    s -= cy * v[k + ix];
188                }
189                out[k] = s;
190            }
191        }
192        out
193    };
194    let x = conjugate_gradient(apply, &b, 1e-12, 10 * (ix * iy).max(100))?;
195    for j in 1..ny - 1 {
196        for i in 1..nx - 1 {
197            u[j][i] = x[index(i, j)];
198        }
199    }
200    Ok(u)
201}
202
203/// Conjugate gradients for a symmetric positive-definite operator `apply`, from zero, to the
204/// relative residual `tolerance`. If `max_iterations` is reached first, a solution whose residual
205/// is within a factor 1000 of the target is still returned (rounding often stalls the last digits);
206/// otherwise the result is an error.
207pub fn conjugate_gradient<A: Fn(&[f64]) -> Vec<f64>>(apply: A, b: &[f64], tolerance: f64, max_iterations: usize) -> Result<Vec<f64>, ErrorsJSL> {
208    let dot = |a: &[f64], c: &[f64]| a.iter().zip(c).map(|(p, q)| p * q).sum::<f64>();
209    let mut x = vec![0.0; b.len()];
210    let mut r = b.to_vec();
211    let mut p = r.clone();
212    let mut rr = dot(&r, &r);
213    let target = tolerance * tolerance * rr.max(1e-300);
214    for _ in 0..max_iterations {
215        if rr <= target {
216            return Ok(x);
217        }
218        let ap = apply(&p);
219        let pap = dot(&p, &ap);
220        if pap <= 0.0 {
221            return Err(ErrorsJSL::RuntimeError("The operator is not positive definite."));
222        }
223        let alpha = rr / pap;
224        x.iter_mut().zip(&p).for_each(|(xi, pi)| *xi += alpha * pi);
225        r.iter_mut().zip(&ap).for_each(|(ri, api)| *ri -= alpha * api);
226        let rr_new = dot(&r, &r);
227        let beta = rr_new / rr;
228        p.iter_mut().zip(&r).for_each(|(pi, ri)| *pi = ri + beta * *pi);
229        rr = rr_new;
230    }
231    if rr <= target * 1e6 { Ok(x) } else { Err(ErrorsJSL::RuntimeError("Conjugate gradients did not converge.")) }
232}
233
234#[cfg(test)]
235mod tests {
236    use super::*;
237    use std::f64::consts::PI;
238
239    #[test]
240    fn heat_equation_decays_a_sine_mode_at_the_exact_rate() {
241        let (n, alpha, t) = (41, 0.5, 0.2);
242        let x: Vec<f64> = (0..n).map(|i| i as f64 / (n - 1) as f64).collect();
243        let u0: Vec<f64> = x.iter().map(|&v| (PI * v).sin()).collect();
244        let exact = |v: f64| (-alpha * PI * PI * t).exp() * (PI * v).sin();
245        let dx = 1.0 / (n - 1) as f64;
246        let dt = 0.4 * dx * dx / alpha;
247        let steps = (t / dt).round() as usize;
248        let explicit = heat_equation_1d(&u0, 1.0, alpha, t / steps as f64, steps, 0.0, 0.0, HeatScheme::Explicit).unwrap();
249        let cn = heat_equation_1d(&u0, 1.0, alpha, 0.01, 20, 0.0, 0.0, HeatScheme::CrankNicolson).unwrap();
250        for (i, &v) in x.iter().enumerate() {
251            // The spatial truncation error at Δx = 1/40 is about 2e-4.
252            assert!((explicit[i] - exact(v)).abs() < 5e-4 && (cn[i] - exact(v)).abs() < 5e-4, "x={v}");
253        }
254        // Crank-Nicolson is second order in time: halving Δt quarters the temporal error (on a
255        // fine grid where the spatial error is negligible).
256        let fine: Vec<f64> = (0..401).map(|i| (PI * i as f64 / 400.0).sin()).collect();
257        let error = |steps: usize| {
258            let u = heat_equation_1d(&fine, 1.0, alpha, t / steps as f64, steps, 0.0, 0.0, HeatScheme::CrankNicolson).unwrap();
259            (u[200] - exact(0.5)).abs()
260        };
261        let ratio = error(5) / error(10);
262        assert!(ratio > 3.5 && ratio < 4.5, "{ratio}");
263        assert!(heat_equation_1d(&u0, 1.0, alpha, 1.0, 1, 0.0, 0.0, HeatScheme::Explicit).is_err());
264    }
265
266    #[test]
267    fn wave_equation_is_exact_at_unit_courant_number() {
268        // A standing wave sin(πx) cos(πct).
269        let (n, c) = (51, 1.0);
270        let dx = 1.0 / (n - 1) as f64;
271        let u0: Vec<f64> = (0..n).map(|i| (PI * i as f64 * dx).sin()).collect();
272        let u = wave_equation_1d(&u0, &vec![0.0; n], 1.0, c, dx, 75).unwrap();
273        let t = 75.0 * dx;
274        assert!(u.iter().enumerate().all(|(i, v)| (v - (PI * i as f64 * dx).sin() * (PI * c * t).cos()).abs() < 2e-4));
275        assert!(wave_equation_1d(&u0, &vec![0.0; n], 1.0, c, 1.5 * dx, 1).is_err());
276    }
277
278    #[test]
279    fn poisson_converges_at_second_order() {
280        // −∇²u = 2π² sin(πx) sin(πy) has u = sin(πx) sin(πy); plus a harmonic boundary part x²−y².
281        let exact = |x: f64, y: f64| (PI * x).sin() * (PI * y).sin() + x * x - y * y;
282        let f = |x: f64, y: f64| 2.0 * PI * PI * (PI * x).sin() * (PI * y).sin();
283        let error = |n: usize| {
284            let u = poisson_2d(f, exact, 1.0, 1.0, n, n).unwrap();
285            let h = 1.0 / (n - 1) as f64;
286            (0..n).flat_map(|j| (0..n).map(move |i| (i, j))).map(|(i, j)| (u[j][i] - exact(i as f64 * h, j as f64 * h)).abs()).fold(0.0, f64::max)
287        };
288        let (coarse, fine) = (error(17), error(33));
289        assert!(fine < 1e-3 && coarse / fine > 3.6 && coarse / fine < 4.4, "{coarse} {fine}");
290        assert!(solve_tridiagonal(&[0.0, 1.0], &[2.0, 2.0], &[1.0, 0.0], &[3.0, 3.0]).unwrap().iter().all(|v| (v - 1.0).abs() < 1e-15));
291    }
292}