Skip to main content

lib_jsl_ffts/
dct.rs

1//! Discrete cosine and sine transforms of types I-IV, computed through complex FFTs.
2//!
3//! Unnormalized definitions follow the common (SciPy / FFTW REDFT-RODFT) convention, for a
4//! length-`N` input `x`:
5//!
6//! | Type | Cosine transform `y_k` | Sine transform `y_k` |
7//! |------|------------------------|----------------------|
8//! | I    | `x₀ + (−1)ᵏx_{N−1} + 2Σ_{n=1}^{N−2} x_n cos(πkn/(N−1))` | `2Σ x_n sin(π(k+1)(n+1)/(N+1))` |
9//! | II   | `2Σ x_n cos(πk(2n+1)/(2N))` | `2Σ x_n sin(π(k+1)(2n+1)/(2N))` |
10//! | III  | `x₀ + 2Σ_{n≥1} x_n cos(πn(2k+1)/(2N))` | `(−1)ᵏx_{N−1} + 2Σ_{n<N−1} x_n sin(π(n+1)(2k+1)/(2N))` |
11//! | IV   | `2Σ x_n cos(π(2n+1)(2k+1)/(4N))` | `2Σ x_n sin(π(2n+1)(2k+1)/(4N))` |
12//!
13//! Types II and III are mutual inverses up to `2N`, types I and IV are their own inverses up to
14//! `2(N∓1)` and `2N`. [`TrigNormalization::Ortho`] scales each transform to an orthogonal matrix,
15//! so the inverse is the transpose (type II ↔ III, types I and IV self-inverse). Every transform
16//! is an O(N log N) FFT of a symmetric extension or twiddled zero-padding of length about 2N.
17//!
18//! See the book entry [Discrete cosine and sine transforms](https://jwkunz.github.io/lib_jsl/book/fft/dct.html).
19
20use crate::fft::Fft;
21use crate::fft_engine_trait::{FftDirection, FftEngine1D, FftOrdering, FftScaleFactor};
22use lib_jsl_core::ErrorsJSL;
23use num_complex::Complex;
24use std::f64::consts::PI;
25
26type C64 = Complex<f64>;
27
28/// The transform type.
29#[derive(Clone, Copy, Debug, PartialEq, Eq)]
30pub enum TrigTransformType {
31    I,
32    II,
33    III,
34    IV,
35}
36
37/// Scaling of the forward transform.
38#[derive(Clone, Copy, Debug, PartialEq, Eq)]
39pub enum TrigNormalization {
40    /// The unnormalized forward transform; the inverse carries the whole scale factor.
41    Backward,
42    /// Orthonormal scaling: forward and inverse are transposes of each other.
43    Ortho,
44}
45
46use TrigNormalization::*;
47use TrigTransformType::*;
48
49fn unscaled_fft(v: &[C64], direction: FftDirection) -> Result<Vec<C64>, ErrorsJSL> {
50    Fft::with_plan(v.len(), FftScaleFactor::None, direction, FftOrdering::Standard)?.execute(v)
51}
52
53fn real(v: &[f64]) -> Vec<C64> {
54    v.iter().map(|&a| C64::new(a, 0.0)).collect()
55}
56
57fn check(x: &[f64], kind: TrigTransformType, cosine: bool) -> Result<usize, ErrorsJSL> {
58    let n = x.len();
59    if n == 0 {
60        return Err(ErrorsJSL::InvalidInputRange("The input must not be empty."));
61    }
62    if cosine && kind == I && n < 2 {
63        return Err(ErrorsJSL::InvalidInputRange("The type I cosine transform needs at least two samples."));
64    }
65    Ok(n)
66}
67
68/// `V_k = Σ x_n e^{-iπn/(2N)} e^{-2πi nk/(2N)}`, the shared core of the type IV transforms, with
69/// the output twiddle `e^{-iπ(2k+1)/(4N)}` already applied.
70fn type_four_core(x: &[f64]) -> Result<Vec<C64>, ErrorsJSL> {
71    let n = x.len();
72    let mut v = vec![C64::new(0.0, 0.0); 2 * n];
73    for (i, &a) in x.iter().enumerate() {
74        v[i] = C64::from_polar(a, -PI * i as f64 / (2 * n) as f64);
75    }
76    let big = unscaled_fft(&v, FftDirection::Forward)?;
77    Ok((0..n).map(|k| C64::from_polar(2.0, -PI * (2 * k + 1) as f64 / (4 * n) as f64) * big[k]).collect())
78}
79
80// ANCHOR: dct_raw
81fn dct_raw(x: &[f64], kind: TrigTransformType) -> Result<Vec<f64>, ErrorsJSL> {
82    let n = x.len();
83    Ok(match kind {
84        I => {
85            let ext: Vec<f64> = x.iter().copied().chain(x[1..n - 1].iter().rev().copied()).collect();
86            unscaled_fft(&real(&ext), FftDirection::Forward)?[..n].iter().map(|v| v.re).collect()
87        }
88        II => {
89            let ext: Vec<f64> = x.iter().copied().chain(x.iter().rev().copied()).collect();
90            let big = unscaled_fft(&real(&ext), FftDirection::Forward)?;
91            (0..n).map(|k| (C64::from_polar(1.0, -PI * k as f64 / (2 * n) as f64) * big[k]).re).collect()
92        }
93        III => {
94            let mut w = vec![C64::new(0.0, 0.0); 2 * n];
95            for (k, &a) in x.iter().enumerate() {
96                let c = if k == 0 { 0.5 } else { 1.0 };
97                w[k] = C64::from_polar(c * a, PI * k as f64 / (2 * n) as f64);
98            }
99            unscaled_fft(&w, FftDirection::Inverse)?[..n].iter().map(|v| 2.0 * v.re).collect()
100        }
101        IV => type_four_core(x)?.iter().map(|v| v.re).collect(),
102    })
103}
104// ANCHOR_END: dct_raw
105
106fn dst_raw(x: &[f64], kind: TrigTransformType) -> Result<Vec<f64>, ErrorsJSL> {
107    let n = x.len();
108    Ok(match kind {
109        I => {
110            // Odd extension [0, x, 0, −rev x] of length 2(N+1): its DFT is −2i times the sine sum.
111            let mut u = vec![0.0; 2 * (n + 1)];
112            for (i, &a) in x.iter().enumerate() {
113                u[i + 1] = a;
114                u[2 * n + 1 - i] = -a;
115            }
116            let big = unscaled_fft(&real(&u), FftDirection::Forward)?;
117            (0..n).map(|k| -big[k + 1].im).collect()
118        }
119        // DST-II(x)_k = DCT-II((−1)ⁿx)_{N−1−k}.
120        II => {
121            let alt: Vec<f64> = x.iter().enumerate().map(|(i, &a)| if i.is_multiple_of(2) { a } else { -a }).collect();
122            let d = dct_raw(&alt, II)?;
123            (0..n).map(|k| d[n - 1 - k]).collect()
124        }
125        // DST-III(x)_k = (−1)ᵏ DCT-III(rev x)_k.
126        III => {
127            let rev: Vec<f64> = x.iter().rev().copied().collect();
128            dct_raw(&rev, III)?.iter().enumerate().map(|(k, &a)| if k.is_multiple_of(2) { a } else { -a }).collect()
129        }
130        IV => type_four_core(x)?.iter().map(|v| -v.im).collect(),
131    })
132}
133
134/// Orthonormal scaling of a type II/III pair: entry `special` (0 for cosine, N−1 for sine) of the
135/// type II output has norm `√(4N)`, the others `√(2N)`.
136fn pair_scale(n: usize, i: usize, special: usize) -> f64 {
137    if i == special { (4 * n) as f64 } else { (2 * n) as f64 }.sqrt()
138}
139
140fn transform(x: &[f64], kind: TrigTransformType, norm: TrigNormalization, cosine: bool) -> Result<Vec<f64>, ErrorsJSL> {
141    let n = check(x, kind, cosine)?;
142    let raw = |v: &[f64], k| if cosine { dct_raw(v, k) } else { dst_raw(v, k) };
143    if norm == Backward {
144        return raw(x, kind);
145    }
146    let special = if cosine { 0 } else { n - 1 };
147    Ok(match kind {
148        I if cosine => {
149            // Endpoint weights ½ make the raw matrix non-symmetric; rescale them by √2 on both sides.
150            let mut v = x.to_vec();
151            v[0] *= 2f64.sqrt();
152            v[n - 1] *= 2f64.sqrt();
153            let mut y = raw(&v, I)?;
154            y[0] /= 2f64.sqrt();
155            y[n - 1] /= 2f64.sqrt();
156            let s = (2.0 * (n - 1) as f64).sqrt();
157            y.iter().map(|a| a / s).collect()
158        }
159        I => raw(x, I)?.iter().map(|a| a / (2.0 * (n + 1) as f64).sqrt()).collect(),
160        II => raw(x, II)?.iter().enumerate().map(|(i, a)| a / pair_scale(n, i, special)).collect(),
161        // The orthonormal type III is the inverse (= transpose) of the orthonormal type II.
162        III => {
163            let v: Vec<f64> = x.iter().enumerate().map(|(i, a)| a * pair_scale(n, i, special)).collect();
164            raw(&v, III)?.iter().map(|a| a / (2 * n) as f64).collect()
165        }
166        IV => raw(x, IV)?.iter().map(|a| a / (2.0 * n as f64).sqrt()).collect(),
167    })
168}
169
170fn inverse(y: &[f64], kind: TrigTransformType, norm: TrigNormalization, cosine: bool) -> Result<Vec<f64>, ErrorsJSL> {
171    let n = check(y, kind, cosine)?;
172    let partner = match kind {
173        II => III,
174        III => II,
175        k => k,
176    };
177    let out = transform(y, partner, norm, cosine)?;
178    if norm == Ortho {
179        return Ok(out);
180    }
181    let scale = match kind {
182        I if cosine => 2 * (n - 1),
183        I => 2 * (n + 1),
184        _ => 2 * n,
185    } as f64;
186    Ok(out.iter().map(|a| a / scale).collect())
187}
188
189/// The discrete cosine transform of the given type.
190pub fn dct(x: &[f64], kind: TrigTransformType, norm: TrigNormalization) -> Result<Vec<f64>, ErrorsJSL> {
191    transform(x, kind, norm, true)
192}
193
194/// The inverse of [`dct`] with the same type and normalization.
195pub fn idct(y: &[f64], kind: TrigTransformType, norm: TrigNormalization) -> Result<Vec<f64>, ErrorsJSL> {
196    inverse(y, kind, norm, true)
197}
198
199/// The discrete sine transform of the given type.
200pub fn dst(x: &[f64], kind: TrigTransformType, norm: TrigNormalization) -> Result<Vec<f64>, ErrorsJSL> {
201    transform(x, kind, norm, false)
202}
203
204/// The inverse of [`dst`] with the same type and normalization.
205pub fn idst(y: &[f64], kind: TrigTransformType, norm: TrigNormalization) -> Result<Vec<f64>, ErrorsJSL> {
206    inverse(y, kind, norm, false)
207}
208
209#[cfg(test)]
210mod tests {
211    use super::*;
212
213    const KINDS: [TrigTransformType; 4] = [I, II, III, IV];
214
215    fn alt(k: usize) -> f64 {
216        if k.is_multiple_of(2) { 1.0 } else { -1.0 }
217    }
218
219    fn direct(x: &[f64], kind: TrigTransformType, cosine: bool) -> Vec<f64> {
220        let n = x.len();
221        let nf = n as f64;
222        (0..n)
223            .map(|k| {
224                let kf = k as f64;
225                let sum = |f: &dyn Fn(f64) -> f64| x.iter().enumerate().map(|(i, &a)| a * f(i as f64)).sum::<f64>();
226                match (kind, cosine) {
227                    (I, true) => x[0] + alt(k) * x[n - 1] + 2.0 * (1..n - 1).map(|i| x[i] * (PI * kf * i as f64 / (nf - 1.0)).cos()).sum::<f64>(),
228                    (II, true) => 2.0 * sum(&|i| (PI * kf * (2.0 * i + 1.0) / (2.0 * nf)).cos()),
229                    (III, true) => x[0] + 2.0 * (1..n).map(|i| x[i] * (PI * i as f64 * (2.0 * kf + 1.0) / (2.0 * nf)).cos()).sum::<f64>(),
230                    (IV, true) => 2.0 * sum(&|i| (PI * (2.0 * i + 1.0) * (2.0 * kf + 1.0) / (4.0 * nf)).cos()),
231                    (I, false) => 2.0 * sum(&|i| (PI * (kf + 1.0) * (i + 1.0) / (nf + 1.0)).sin()),
232                    (II, false) => 2.0 * sum(&|i| (PI * (kf + 1.0) * (2.0 * i + 1.0) / (2.0 * nf)).sin()),
233                    (III, false) => alt(k) * x[n - 1] + 2.0 * (0..n - 1).map(|i| x[i] * (PI * (i as f64 + 1.0) * (2.0 * kf + 1.0) / (2.0 * nf)).sin()).sum::<f64>(),
234                    (IV, false) => 2.0 * sum(&|i| (PI * (2.0 * i + 1.0) * (2.0 * kf + 1.0) / (4.0 * nf)).sin()),
235                }
236            })
237            .collect()
238    }
239
240    fn signal(n: usize) -> Vec<f64> {
241        (0..n).map(|i| (0.7 * i as f64).sin() + 0.3 * ((i * i) % 7) as f64 - 0.4).collect()
242    }
243
244    fn close(a: &[f64], b: &[f64], tol: f64) -> bool {
245        a.len() == b.len() && a.iter().zip(b).all(|(p, q)| (p - q).abs() < tol)
246    }
247
248    #[test]
249    fn every_type_matches_its_definition_and_inverts() {
250        for cosine in [true, false] {
251            for kind in KINDS {
252                for n in [2, 3, 4, 5, 8, 13, 16, 30] {
253                    let x = signal(n);
254                    let f = if cosine { dct(&x, kind, Backward) } else { dst(&x, kind, Backward) }.unwrap();
255                    assert!(close(&f, &direct(&x, kind, cosine), 1e-9 * n as f64), "{kind:?} cosine={cosine} n={n}");
256                    for norm in [Backward, Ortho] {
257                        let y = if cosine { dct(&x, kind, norm) } else { dst(&x, kind, norm) }.unwrap();
258                        let back = if cosine { idct(&y, kind, norm) } else { idst(&y, kind, norm) }.unwrap();
259                        assert!(close(&back, &x, 1e-11), "inverse {kind:?} {norm:?} cosine={cosine} n={n}");
260                    }
261                }
262            }
263        }
264    }
265
266    #[test]
267    fn orthonormal_scaling_gives_orthogonal_matrices() {
268        let n = 7;
269        for cosine in [true, false] {
270            for kind in KINDS {
271                let cols: Vec<Vec<f64>> = (0..n)
272                    .map(|j| {
273                        let e: Vec<f64> = (0..n).map(|i| if i == j { 1.0 } else { 0.0 }).collect();
274                        if cosine { dct(&e, kind, Ortho) } else { dst(&e, kind, Ortho) }.unwrap()
275                    })
276                    .collect();
277                for a in 0..n {
278                    for b in 0..n {
279                        let dot: f64 = cols[a].iter().zip(&cols[b]).map(|(p, q)| p * q).sum();
280                        assert!((dot - if a == b { 1.0 } else { 0.0 }).abs() < 1e-12, "{kind:?} cosine={cosine}");
281                    }
282                }
283            }
284        }
285    }
286
287    #[test]
288    fn energy_compaction_and_validation() {
289        // A smooth ramp has almost all of its DCT-II energy in the first few coefficients.
290        let x: Vec<f64> = (0..64).map(|i| i as f64 / 63.0).collect();
291        let y = dct(&x, II, Ortho).unwrap();
292        let total: f64 = y.iter().map(|v| v * v).sum();
293        let head: f64 = y[..4].iter().map(|v| v * v).sum();
294        assert!(head / total > 0.999);
295        assert!((total - x.iter().map(|v| v * v).sum::<f64>()).abs() < 1e-10); // Parseval
296        assert!(dct(&[], II, Backward).is_err() && dct(&[1.0], I, Backward).is_err());
297        assert_eq!(dct(&[3.0], II, Backward).unwrap(), vec![6.0]);
298        assert!(dst(&[2.0], I, Backward).is_ok());
299    }
300}