1use 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
20pub 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
28pub 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 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 d
49}
50
51#[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
95pub 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
115pub 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 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 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 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 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}