1use crate::discrete::cross_correlation::CorrelationMode;
22use crate::discrete::fft_cross_correlation::fft_cross_correlate;
23use lib_jsl_core::ErrorsJSL;
24use ndarray::Array2;
25use num_complex::Complex;
26use std::f64::consts::PI;
27
28const DAUBECHIES: [&[f64]; 10] = [
31 &[
32 std::f64::consts::FRAC_1_SQRT_2, std::f64::consts::FRAC_1_SQRT_2,
33 ],
34 &[
35 0.48296291314453416, 0.8365163037378079,
36 0.2241438680420134, -0.12940952255126037,
37 ],
38 &[
39 0.33267055295008263, 0.8068915093110925,
40 0.45987750211849154, -0.13501102001025458,
41 -0.08544127388202666, 0.03522629188570953,
42 ],
43 &[
44 0.2303778133088965, 0.7148465705529157,
45 0.6308807679298589, -0.027983769416859854,
46 -0.18703481171909309, 0.030841381835560764,
47 0.0328830116668852, -0.010597401785069032,
48 ],
49 &[
50 0.16010239797419293, 0.6038292697971896,
51 0.7243085284377729, 0.13842814590132074,
52 -0.24229488706638203, -0.032244869584638375,
53 0.07757149384004572, -0.006241490212798274,
54 -0.012580751999081999, 0.0033357252854737712,
55 ],
56 &[
57 0.11154074335010947, 0.49462389039845306,
58 0.7511339080210954, 0.31525035170919763,
59 -0.22626469396543983, -0.12976686756726194,
60 0.09750160558732304, 0.027522865530305727,
61 -0.03158203931748603, 0.0005538422011614961,
62 0.004777257510945511, -0.0010773010853084796,
63 ],
64 &[
65 0.07785205408500918, 0.3965393194819173,
66 0.7291320908462351, 0.4697822874051931,
67 -0.14390600392856498, -0.22403618499387498,
68 0.07130921926683026, 0.08061260915108308,
69 -0.03802993693501441, -0.01657454163066688,
70 0.01255099855609984, 0.0004295779729213665,
71 -0.0018016407040474908, 0.00035371379997452024,
72 ],
73 &[
74 0.05441584224310401, 0.31287159091429995,
75 0.6756307362972898, 0.5853546836542067,
76 -0.015829105256349306, -0.2840155429615469,
77 0.0004724845739132828, 0.12874742662047847,
78 -0.017369301001807547, -0.044088253930794755,
79 0.013981027917398282, 0.008746094047405777,
80 -0.004870352993451574, -0.00039174037337694705,
81 0.0006754494064505693, -0.00011747678412476953,
82 ],
83 &[
84 0.038077947363878345, 0.24383467461259034,
85 0.6048231236901112, 0.6572880780513005,
86 0.13319738582500756, -0.2932737832791749,
87 -0.09684078322297646, 0.14854074933810638,
88 0.03072568147933338, -0.06763282906132997,
89 0.00025094711483145197, 0.022361662123679096,
90 -0.004723204757751397, -0.00428150368246343,
91 0.0018476468830562265, 0.00023038576352319597,
92 -0.0002519631889427101, 3.93473203162716e-05,
93 ],
94 &[
95 0.026670057900555554, 0.1881768000776915,
96 0.5272011889317256, 0.6884590394536035,
97 0.2811723436605775, -0.24984642432731538,
98 -0.19594627437737705, 0.12736934033579325,
99 0.09305736460357235, -0.07139414716639708,
100 -0.029457536821875813, 0.033212674059341,
101 0.0036065535669561697, -0.010733175483330575,
102 0.001395351747052901, 0.001992405295185056,
103 -0.0006858566949597116, -0.00011646685512928545,
104 9.358867032006959e-05, -1.3264202894521244e-05,
105 ],
106];
107
108#[derive(Clone, Copy, Debug, PartialEq, Eq)]
110pub enum Wavelet {
111 Haar,
113 Daubechies(usize),
115}
116
117impl Wavelet {
118 pub fn scaling_filter(&self) -> Result<Vec<f64>, ErrorsJSL> {
120 let n = match self {
121 Wavelet::Haar => 1,
122 Wavelet::Daubechies(n) => *n,
123 };
124 if !(1..=10).contains(&n) {
125 return Err(ErrorsJSL::InvalidInputRange("Daubechies order must be between 1 and 10"));
126 }
127 Ok(DAUBECHIES[n - 1].to_vec())
128 }
129
130 pub fn wavelet_filter(&self) -> Result<Vec<f64>, ErrorsJSL> {
132 let h = self.scaling_filter()?;
133 let l = h.len();
134 Ok((0..l).map(|n| if n % 2 == 0 { h[l - 1 - n] } else { -h[l - 1 - n] }).collect())
135 }
136}
137
138fn check_even(n: usize, filter_len: usize) -> Result<(), ErrorsJSL> {
139 if n < filter_len || !n.is_multiple_of(2) {
140 return Err(ErrorsJSL::InvalidInputRange("Signal length must be even and at least the filter length"));
141 }
142 Ok(())
143}
144
145pub fn dwt(x: &[f64], wavelet: Wavelet) -> Result<(Vec<f64>, Vec<f64>), ErrorsJSL> {
147 let h = wavelet.scaling_filter()?;
148 let g = wavelet.wavelet_filter()?;
149 let n = x.len();
150 check_even(n, h.len())?;
151 let analyse = |f: &[f64]| -> Vec<f64> { (0..n / 2).map(|k| f.iter().enumerate().map(|(i, c)| c * x[(2 * k + i) % n]).sum()).collect() };
153 Ok((analyse(&h), analyse(&g)))
154 }
156
157pub fn idwt(approximation: &[f64], detail: &[f64], wavelet: Wavelet) -> Result<Vec<f64>, ErrorsJSL> {
159 if approximation.len() != detail.len() {
160 return Err(ErrorsJSL::IncompatibleArraySizes((approximation.len(), detail.len())));
161 }
162 let h = wavelet.scaling_filter()?;
163 let g = wavelet.wavelet_filter()?;
164 let n = 2 * approximation.len();
165 check_even(n, h.len())?;
166 let mut x = vec![0.0; n];
167 for k in 0..n / 2 {
168 for (i, (hi, gi)) in h.iter().zip(&g).enumerate() {
169 x[(2 * k + i) % n] += approximation[k] * hi + detail[k] * gi;
170 }
171 }
172 Ok(x)
173}
174
175pub fn max_level(n: usize, wavelet: Wavelet) -> Result<usize, ErrorsJSL> {
177 let l = wavelet.scaling_filter()?.len();
178 let mut len = n;
179 let mut level = 0;
180 while len >= l && len.is_multiple_of(2) {
181 level += 1;
182 len /= 2;
183 }
184 Ok(level)
185}
186
187#[derive(Clone, Debug, PartialEq)]
189pub struct WaveletDecomposition {
190 pub approximation: Vec<f64>,
192 pub details: Vec<Vec<f64>>,
194}
195
196pub fn wavedec(x: &[f64], wavelet: Wavelet, levels: usize) -> Result<WaveletDecomposition, ErrorsJSL> {
198 if levels == 0 || levels > max_level(x.len(), wavelet)? {
199 return Err(ErrorsJSL::InvalidInputRange("Decomposition level is zero or too deep for this signal length"));
200 }
201 let mut approx = x.to_vec();
202 let mut details = Vec::with_capacity(levels);
203 for _ in 0..levels {
204 let (a, d) = dwt(&approx, wavelet)?;
205 details.push(d);
206 approx = a;
207 }
208 details.reverse();
209 Ok(WaveletDecomposition { approximation: approx, details })
210}
211
212pub fn waverec(decomposition: &WaveletDecomposition, wavelet: Wavelet) -> Result<Vec<f64>, ErrorsJSL> {
214 let mut approx = decomposition.approximation.clone();
215 for d in &decomposition.details {
216 approx = idwt(&approx, d, wavelet)?;
217 }
218 Ok(approx)
219}
220
221pub fn wavelet_transform(x: &[f64], wavelet: Wavelet, levels: usize) -> Result<WaveletDecomposition, ErrorsJSL> {
223 wavedec(x, wavelet, levels)
224}
225
226#[derive(Clone, Copy, Debug, PartialEq)]
228pub enum ContinuousWavelet {
229 Morlet { omega0: f64 },
231 Ricker,
233}
234
235impl ContinuousWavelet {
236 pub fn value(&self, t: f64) -> Complex<f64> {
238 match *self {
239 ContinuousWavelet::Morlet { omega0 } => Complex::from_polar(PI.powf(-0.25) * (-0.5 * t * t).exp(), omega0 * t),
240 ContinuousWavelet::Ricker => {
241 let c = 2.0 / (3f64.sqrt() * PI.powf(0.25));
242 Complex::new(c * (1.0 - t * t) * (-0.5 * t * t).exp(), 0.0)
243 }
244 }
245 }
246
247 pub fn scale_for_frequency(&self, frequency: f64) -> f64 {
250 match *self {
251 ContinuousWavelet::Morlet { omega0 } => omega0 / (2.0 * PI * frequency),
252 ContinuousWavelet::Ricker => 2f64.sqrt() / (2.0 * PI * frequency),
253 }
254 }
255}
256
257pub fn continuous_wavelet_transform(x: &[f64], scales: &[f64], wavelet: ContinuousWavelet) -> Result<Array2<Complex<f64>>, ErrorsJSL> {
262 if x.is_empty() || scales.is_empty() {
263 return Err(ErrorsJSL::InvalidInputRange("Need a non-empty signal and at least one scale"));
264 }
265 if scales.iter().any(|a| !(*a > 0.0) || !a.is_finite()) {
266 return Err(ErrorsJSL::InvalidInputRange("Scales must be positive and finite"));
267 }
268 let xc: Vec<Complex<f64>> = x.iter().map(|&v| Complex::new(v, 0.0)).collect();
269 let mut out = Array2::<Complex<f64>>::zeros((scales.len(), x.len()));
270 for (row, &a) in scales.iter().enumerate() {
271 let half = (5.0 * a).ceil() as isize;
272 let kernel: Vec<Complex<f64>> = (-half..=half).map(|j| wavelet.value(j as f64 / a) / a.sqrt()).collect();
273 let w = fft_cross_correlate(&xc, &kernel, CorrelationMode::Same)?;
274 for (n, v) in w.into_iter().enumerate() {
275 out[(row, n)] = v;
276 }
277 }
278 Ok(out)
279}
280
281#[cfg(test)]
282mod tests {
283 use super::*;
284
285 fn lcg(seed: &mut u64) -> f64 {
286 *seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
287 ((*seed >> 33) as f64 / (1u64 << 31) as f64) - 0.5
288 }
289
290 #[test]
291 fn filters_satisfy_the_orthogonality_and_moment_conditions() {
292 for n in 1..=10usize {
293 let h = Wavelet::Daubechies(n).scaling_filter().unwrap();
294 assert_eq!(h.len(), 2 * n);
295 assert!((h.iter().sum::<f64>() - 2f64.sqrt()).abs() < 1e-14, "db{n} sum");
296 assert!((h.iter().map(|v| v * v).sum::<f64>() - 1.0).abs() < 1e-14, "db{n} norm");
297 for m in 1..n {
298 let c: f64 = (0..h.len() - 2 * m).map(|k| h[k] * h[k + 2 * m]).sum();
299 assert!(c.abs() < 1e-14, "db{n} shift {m}: {c}");
300 }
301 for p in 0..n {
303 let mom: f64 = h.iter().enumerate().map(|(k, c)| (if k % 2 == 0 { 1.0 } else { -1.0 }) * (k as f64).powi(p as i32) * c).sum();
304 let scale: f64 = h.iter().enumerate().map(|(k, c)| (k as f64).powi(p as i32) * c.abs()).sum();
305 assert!(mom.abs() < 1e-12 * scale.max(1.0), "db{n} moment {p}: {mom}");
306 }
307 }
308 assert_eq!(Wavelet::Haar.scaling_filter().unwrap(), Wavelet::Daubechies(1).scaling_filter().unwrap());
309 let db2 = Wavelet::Daubechies(2).scaling_filter().unwrap();
310 let s3 = 3f64.sqrt();
311 let want = [(1.0 + s3), (3.0 + s3), (3.0 - s3), (1.0 - s3)].map(|v| v / (4.0 * 2f64.sqrt()));
312 assert!(db2.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-15), "db2 has a closed form");
313 assert!(Wavelet::Daubechies(0).scaling_filter().is_err() && Wavelet::Daubechies(11).scaling_filter().is_err());
314 }
315
316 #[test]
317 fn haar_matches_hand_computation() {
318 let s = std::f64::consts::FRAC_1_SQRT_2;
319 let (a, d) = dwt(&[1.0, 2.0, 3.0, 4.0], Wavelet::Haar).unwrap();
320 assert!((a[0] - 3.0 * s).abs() < 1e-14 && (a[1] - 7.0 * s).abs() < 1e-14);
321 assert!((d[0] + s).abs() < 1e-14 && (d[1] + s).abs() < 1e-14);
322 let x = idwt(&a, &d, Wavelet::Haar).unwrap();
323 assert!(x.iter().zip([1.0, 2.0, 3.0, 4.0]).all(|(p, q)| (p - q).abs() < 1e-14));
324 }
325
326 #[test]
327 fn perfect_reconstruction_and_energy_preservation() {
328 let mut seed = 3;
329 for n in 1..=10usize {
330 let w = Wavelet::Daubechies(n);
331 let x: Vec<f64> = (0..256).map(|_| lcg(&mut seed)).collect();
332 let max = max_level(256, w).unwrap();
333 for levels in 1..=max.min(6) {
334 let dec = wavedec(&x, w, levels).unwrap();
335 let back = waverec(&dec, w).unwrap();
336 assert!(x.iter().zip(&back).all(|(p, q)| (p - q).abs() < 1e-11), "db{n} level {levels}");
337 let energy: f64 = dec.approximation.iter().chain(dec.details.iter().flatten()).map(|v| v * v).sum();
338 let original: f64 = x.iter().map(|v| v * v).sum();
339 assert!((energy / original - 1.0).abs() < 1e-12, "db{n} Parseval");
340 }
341 }
342 }
343
344 #[test]
345 fn vanishing_moments_annihilate_polynomials() {
346 let n = 64;
348 let ramp: Vec<f64> = (0..n).map(|i| 3.0 + 0.5 * i as f64).collect();
349 let (_, d) = dwt(&ramp, Wavelet::Daubechies(2)).unwrap();
350 assert!(d[..n / 2 - 2].iter().all(|v| v.abs() < 1e-12), "{d:?}");
351 let quad: Vec<f64> = (0..n).map(|i| (i as f64).powi(2)).collect();
352 let (_, d3) = dwt(&quad, Wavelet::Daubechies(3)).unwrap();
353 assert!(d3[..n / 2 - 3].iter().all(|v| v.abs() < 1e-8), "{d3:?}");
354 let (_, haar_d) = dwt(&ramp, Wavelet::Haar).unwrap();
355 assert!(haar_d[0].abs() > 0.1, "Haar has only one vanishing moment");
356 }
357
358 #[test]
359 fn smooth_signals_concentrate_in_the_approximation() {
360 let x: Vec<f64> = (0..256).map(|i| (std::f64::consts::TAU * i as f64 / 256.0).sin()).collect();
361 let dec = wavedec(&x, Wavelet::Daubechies(4), 3).unwrap();
362 let approx_energy: f64 = dec.approximation.iter().map(|v| v * v).sum();
363 let total: f64 = x.iter().map(|v| v * v).sum();
364 assert!(approx_energy / total > 0.9999, "{}", approx_energy / total);
365 assert_eq!(dec.details.iter().map(|d| d.len()).collect::<Vec<_>>(), vec![32, 64, 128]);
366 assert_eq!(dec.approximation.len(), 32);
367 }
368
369 #[test]
370 fn wavelet_transform_is_the_multilevel_dwt() {
371 let x: Vec<f64> = (0..64).map(|i| (i as f64 * 0.37).cos()).collect();
372 assert_eq!(wavelet_transform(&x, Wavelet::Haar, 3).unwrap(), wavedec(&x, Wavelet::Haar, 3).unwrap());
373 }
374
375 #[test]
376 fn dwt_argument_checks() {
377 assert!(dwt(&[1.0, 2.0, 3.0], Wavelet::Haar).is_err(), "odd length");
378 assert!(dwt(&[1.0, 2.0], Wavelet::Daubechies(2)).is_err(), "shorter than the filter");
379 assert!(idwt(&[1.0], &[1.0, 2.0], Wavelet::Haar).is_err());
380 assert!(wavedec(&[1.0; 16], Wavelet::Haar, 0).is_err());
381 assert!(wavedec(&[1.0; 16], Wavelet::Haar, 5).is_err());
382 assert_eq!(max_level(16, Wavelet::Haar).unwrap(), 4);
383 assert_eq!(max_level(256, Wavelet::Daubechies(4)).unwrap(), 6);
384 }
385
386 #[test]
387 fn morlet_cwt_ridge_sits_at_the_signal_frequency() {
388 let f = 0.05; let x: Vec<f64> = (0..512).map(|n| (std::f64::consts::TAU * f * n as f64).sin()).collect();
390 let wavelet = ContinuousWavelet::Morlet { omega0: 6.0 };
391 let target = wavelet.scale_for_frequency(f);
392 let scales: Vec<f64> = (0..40).map(|i| 4.0 * 1.06f64.powi(i)).collect();
393 let w = continuous_wavelet_transform(&x, &scales, wavelet).unwrap();
394 assert_eq!(w.dim(), (40, 512));
395 let mags: Vec<f64> = (0..40).map(|r| w[(r, 256)].norm()).collect();
397 let best = mags.iter().enumerate().max_by(|a, b| a.1.partial_cmp(b.1).unwrap()).unwrap().0;
398 assert!((scales[best] / target - 1.0).abs() < 0.07, "peak scale {} vs target {target}", scales[best]);
399 }
400
401 #[test]
402 fn ricker_cwt_localises_an_impulse_in_time() {
403 let mut x = vec![0.0; 300];
404 x[120] = 1.0;
405 let w = continuous_wavelet_transform(&x, &[2.0, 4.0, 8.0], ContinuousWavelet::Ricker).unwrap();
406 for r in 0..3 {
407 let peak = (0..300).max_by(|&a, &b| w[(r, a)].norm().partial_cmp(&w[(r, b)].norm()).unwrap()).unwrap();
408 assert_eq!(peak, 120, "scale row {r}");
409 assert!(w[(r, 120)].im.abs() < 1e-12, "the Ricker wavelet is real");
410 }
411 let psi0 = ContinuousWavelet::Ricker.value(0.0).re;
413 assert!((w[(1, 120)].re - psi0 / 2.0).abs() < 1e-9);
414 assert!((ContinuousWavelet::Ricker.scale_for_frequency(0.1) - 2f64.sqrt() / (2.0 * PI * 0.1)).abs() < 1e-12);
415 }
416
417 #[test]
418 fn cwt_argument_checks() {
419 assert!(continuous_wavelet_transform(&[], &[1.0], ContinuousWavelet::Ricker).is_err());
420 assert!(continuous_wavelet_transform(&[1.0], &[], ContinuousWavelet::Ricker).is_err());
421 assert!(continuous_wavelet_transform(&[1.0, 2.0], &[0.0], ContinuousWavelet::Ricker).is_err());
422 assert!(continuous_wavelet_transform(&[1.0, 2.0], &[-1.0], ContinuousWavelet::Ricker).is_err());
423 }
424}