Skip to main content

lib_jsl_integration/pde/
spectral.rs

1//! Spectral methods: Chebyshev collocation and Fourier differentiation.
2//!
3//! For smooth solutions these converge exponentially fast in the number of points, far beyond
4//! the algebraic rates of finite differences and finite elements.
5//!
6//! * [`chebyshev_differentiation_matrix`] on the Chebyshev-Gauss-Lobatto points (Trefethen,
7//!   *Spectral Methods in MATLAB*), and [`chebyshev_bvp`] solving
8//!   `u'' + p(x) u' + q(x) u = f(x)` with Dirichlet ends by collocation.
9//! * [`fourier_derivative`] of periodic samples by the FFT, and [`periodic_heat`], which advances
10//!   the periodic heat equation exactly in Fourier space.
11//!
12//! See the book entry [Spectral methods](https://jwkunz.github.io/lib_jsl/book/integration/spectral-methods.html).
13
14use crate::stiff_ode::Lu;
15use lib_jsl_core::ErrorsJSL;
16use lib_jsl_ffts::{Fft, FftDirection, FftEngine1D, FftOrdering, FftScaleFactor};
17use num_complex::Complex;
18use std::f64::consts::{PI, TAU};
19
20/// The `n + 1` Chebyshev-Gauss-Lobatto points `x_j = cos(πj/n)`, from 1 down to −1.
21pub fn chebyshev_points(n: usize) -> Vec<f64> {
22    if n == 0 {
23        return vec![1.0];
24    }
25    (0..=n).map(|j| (PI * j as f64 / n as f64).cos()).collect()
26}
27
28/// The `(n+1) × (n+1)` differentiation matrix on [`chebyshev_points`]: `(D u)_i ≈ u'(x_i)`,
29/// exact for polynomials of degree `n`. The diagonal uses the negative-row-sum trick for
30/// accuracy.
31pub fn chebyshev_differentiation_matrix(n: usize) -> Vec<Vec<f64>> {
32    let x = chebyshev_points(n);
33    if n == 0 {
34        return vec![vec![0.0]];
35    }
36    // ANCHOR: cheb_matrix
37    let c: Vec<f64> = (0..=n).map(|i| if i == 0 || i == n { 2.0 } else { 1.0 } * if i % 2 == 0 { 1.0 } else { -1.0 }).collect();
38    let mut d = vec![vec![0.0; n + 1]; n + 1];
39    for i in 0..=n {
40        for j in 0..=n {
41            if i != j {
42                d[i][j] = c[i] / c[j] / (x[i] - x[j]);
43            }
44        }
45        d[i][i] = -d[i].iter().sum::<f64>();
46    }
47    // ANCHOR_END: cheb_matrix
48    d
49}
50
51/// Solves `u'' + p(x) u' + q(x) u = f(x)` on `[a, b]` with `u(a) = ua`, `u(b) = ub` by Chebyshev
52/// collocation at `n + 1` points. Returns the points (from `b` down to `a`) and the solution.
53#[allow(clippy::too_many_arguments)]
54pub fn chebyshev_bvp<P, Q, F>(p: P, q: Q, f: F, a: f64, b: f64, ua: f64, ub: f64, n: usize) -> Result<(Vec<f64>, Vec<f64>), ErrorsJSL>
55where
56    P: Fn(f64) -> f64,
57    Q: Fn(f64) -> f64,
58    F: Fn(f64) -> f64,
59{
60    if n < 2 || !(b > a) {
61        return Err(ErrorsJSL::InvalidInputRange("Need n >= 2 and a < b."));
62    }
63    let scale = 2.0 / (b - a);
64    let xs: Vec<f64> = chebyshev_points(n).iter().map(|&x| a + (b - a) * (x + 1.0) / 2.0).collect();
65    let d = chebyshev_differentiation_matrix(n);
66    let size = n + 1;
67    let d2: Vec<Vec<f64>> = (0..size).map(|i| (0..size).map(|j| (0..size).map(|k| d[i][k] * d[k][j]).sum::<f64>()).collect()).collect();
68    let mut matrix = vec![vec![0.0; size]; size];
69    let mut rhs = vec![0.0; size];
70    for i in 0..size {
71        if i == 0 || i == n {
72            matrix[i][i] = 1.0;
73            rhs[i] = if i == 0 { ub } else { ua };
74            continue;
75        }
76        let (pi, qi) = (p(xs[i]), q(xs[i]));
77        for j in 0..size {
78            matrix[i][j] = scale * scale * d2[i][j] + pi * scale * d[i][j] + if i == j { qi } else { 0.0 };
79        }
80        rhs[i] = f(xs[i]);
81    }
82    let u = Lu::new(matrix)?.solve(&rhs);
83    Ok((xs, u))
84}
85
86fn wavenumbers(n: usize, length: f64) -> Vec<f64> {
87    (0..n).map(|m| { let k = if m <= n / 2 { m as f64 } else { m as f64 - n as f64 }; TAU * k / length }).collect()
88}
89
90fn transform(u: &[Complex<f64>], direction: FftDirection) -> Result<Vec<Complex<f64>>, ErrorsJSL> {
91    let scale = if matches!(direction, FftDirection::Forward) { FftScaleFactor::None } else { FftScaleFactor::N };
92    Fft::with_plan(u.len(), scale, direction, FftOrdering::Standard)?.execute(u)
93}
94
95/// The `order`-th derivative of the periodic function sampled at `u.len()` equispaced points over
96/// one period `length`, by multiplying its spectrum by `(ik)^order`. For odd orders and even
97/// lengths the Nyquist mode is zeroed (its derivative is not representable).
98pub fn fourier_derivative(u: &[f64], order: u32, length: f64) -> Result<Vec<f64>, ErrorsJSL> {
99    let n = u.len();
100    if n == 0 || !(length > 0.0) {
101        return Err(ErrorsJSL::InvalidInputRange("Need samples and a positive period."));
102    }
103    let input: Vec<Complex<f64>> = u.iter().map(|&v| Complex::new(v, 0.0)).collect();
104    let mut spectrum = transform(&input, FftDirection::Forward)?;
105    for (m, (s, k)) in spectrum.iter_mut().zip(wavenumbers(n, length)).enumerate() {
106        if order % 2 == 1 && n.is_multiple_of(2) && m == n / 2 {
107            *s = Complex::new(0.0, 0.0);
108        } else {
109            *s *= Complex::new(0.0, k).powu(order);
110        }
111    }
112    Ok(transform(&spectrum, FftDirection::Inverse)?.iter().map(|c| c.re).collect())
113}
114
115/// Advances `u_t = α u_xx` with periodic boundaries over `length` exactly in Fourier space:
116/// each mode decays by `e^{−α k² t}`. Exact in time and spectrally accurate in space.
117pub fn periodic_heat(u0: &[f64], alpha: f64, t: f64, length: f64) -> Result<Vec<f64>, ErrorsJSL> {
118    if u0.is_empty() || !(length > 0.0) || !(alpha >= 0.0) || !(t >= 0.0) {
119        return Err(ErrorsJSL::InvalidInputRange("Need samples, a positive period and non-negative α and t."));
120    }
121    let input: Vec<Complex<f64>> = u0.iter().map(|&v| Complex::new(v, 0.0)).collect();
122    let mut spectrum = transform(&input, FftDirection::Forward)?;
123    for (s, k) in spectrum.iter_mut().zip(wavenumbers(u0.len(), length)) {
124        *s *= (-alpha * k * k * t).exp();
125    }
126    Ok(transform(&spectrum, FftDirection::Inverse)?.iter().map(|c| c.re).collect())
127}
128
129#[cfg(test)]
130mod tests {
131    use super::*;
132
133    #[test]
134    fn chebyshev_differentiation_converges_spectrally() {
135        let error = |n: usize| {
136            let x = chebyshev_points(n);
137            let d = chebyshev_differentiation_matrix(n);
138            let u: Vec<f64> = x.iter().map(|v| (v * 2.0).exp() * v.sin()).collect();
139            (0..=n).map(|i| {
140                let du: f64 = (0..=n).map(|j| d[i][j] * u[j]).sum();
141                (du - (2.0 * x[i]).exp() * (2.0 * x[i].sin() + x[i].cos())).abs()
142            }).fold(0.0, f64::max)
143        };
144        assert!(error(8) > 1e-6 && error(24) < 1e-11, "{} {}", error(8), error(24));
145        // Exact for polynomials of degree n.
146        let d = chebyshev_differentiation_matrix(4);
147        let x = chebyshev_points(4);
148        assert!((0..5).all(|i| ((0..5).map(|j| d[i][j] * x[j].powi(4)).sum::<f64>() - 4.0 * x[i].powi(3)).abs() < 1e-12));
149    }
150
151    #[test]
152    fn chebyshev_bvp_reaches_machine_precision() {
153        // Trefethen's program 13: u'' = e^{4x}, u(±1) = 0.
154        let exact = |x: f64| ((4.0 * x).exp() - x * 4f64.sinh() - 4f64.cosh()) / 16.0;
155        let (xs, u) = chebyshev_bvp(|_| 0.0, |_| 0.0, |x| (4.0 * x).exp(), -1.0, 1.0, 0.0, 0.0, 24).unwrap();
156        assert!(xs.iter().zip(&u).all(|(x, v)| (v - exact(*x)).abs() < 1e-12));
157        // Variable coefficients on another interval: u'' + u' / x − u / x² = 0 has u = x on [1, 3]
158        // (written with p = 1/x, q = −1/x²), plus Dirichlet data u(1) = 1, u(3) = 3.
159        let (xs, u) = chebyshev_bvp(|x| 1.0 / x, |x| -1.0 / (x * x), |_| 0.0, 1.0, 3.0, 1.0, 3.0, 12).unwrap();
160        assert!(xs.iter().zip(&u).all(|(x, v)| (v - x).abs() < 1e-12));
161        assert!(chebyshev_bvp(|_| 0.0, |_| 0.0, |_| 0.0, 1.0, 0.0, 0.0, 0.0, 8).is_err());
162    }
163
164    #[test]
165    fn fourier_methods_are_spectrally_accurate() {
166        let n = 32;
167        let x: Vec<f64> = (0..n).map(|i| TAU * i as f64 / n as f64).collect();
168        let u: Vec<f64> = x.iter().map(|v| v.sin().exp()).collect();
169        let du = fourier_derivative(&u, 1, TAU).unwrap();
170        assert!(x.iter().zip(&du).all(|(v, d)| (d - v.cos() * v.sin().exp()).abs() < 1e-12));
171        let d2 = fourier_derivative(&u, 2, TAU).unwrap();
172        assert!(x.iter().zip(&d2).all(|(v, d)| (d - (v.cos().powi(2) - v.sin()) * v.sin().exp()).abs() < 1e-11));
173        // Heat: sin(3x) decays by e^{−9αt}.
174        let u0: Vec<f64> = x.iter().map(|v| (3.0 * v).sin() + 2.0).collect();
175        let u = periodic_heat(&u0, 0.1, 0.5, TAU).unwrap();
176        assert!(x.iter().zip(&u).all(|(v, w)| (w - (2.0 + (-0.9f64 * 0.5).exp() * (3.0 * v).sin())).abs() < 1e-13));
177        assert!(fourier_derivative(&[], 1, 1.0).is_err());
178    }
179}