Skip to main content

lib_jsl_ffts/
helpers.rs

1//! Frequency grids, fast transform lengths, N-dimensional real FFTs and N-dimensional DCTs and DSTs,
2//! following `scipy.fft`: `fftfreq`, `rfftfreq`, `next_fast_len`, `ifftshift`, `rfftn`/`irfftn`
3//! and `dctn`/`idctn`/`dstn`/`idstn`.
4//!
5//! See the book entry [Real and multidimensional FFTs](https://jwkunz.github.io/lib_jsl/book/fft/real-multidimensional.html#helpers-frequencies-fast-lengths-and-n-d-transforms).
6
7use crate::dct::{TrigNormalization, TrigTransformType, dct, dst, idct, idst};
8use crate::fft_engine_trait::FftDirection;
9use crate::multidimensional_fft::fft_axis;
10use crate::real_fft::{irfft, rfft};
11use lib_jsl_core::ErrorsJSL;
12use ndarray::{ArrayD, Axis, IxDyn};
13use num_complex::Complex;
14
15type C64 = Complex<f64>;
16
17// ANCHOR: fftfreq
18/// The sample frequencies of an `n`-point DFT with sample spacing `d` (NumPy's `fftfreq`):
19/// `[0, 1, …, ⌈n/2⌉−1, −⌊n/2⌋, …, −1] / (n d)`, in the order the FFT returns its bins.
20pub fn fftfreq(n: usize, d: f64) -> Vec<f64> {
21    let scale = 1.0 / (n as f64 * d);
22    (0..n).map(|k| if k < n.div_ceil(2) { k as f64 } else { k as f64 - n as f64 } * scale).collect()
23}
24
25/// The non-negative sample frequencies of an `n`-point real FFT, `[0, 1, …, ⌊n/2⌋] / (n d)`
26/// (NumPy's `rfftfreq`).
27pub fn rfftfreq(n: usize, d: f64) -> Vec<f64> {
28    let scale = 1.0 / (n as f64 * d);
29    (0..=n / 2).map(|k| k as f64 * scale).collect()
30}
31// ANCHOR_END: fftfreq
32
33// ANCHOR: next_fast_len
34/// The smallest length `≥ target` whose prime factors are all small, which FFTs handle fastest
35/// (SciPy's `next_fast_len`): 2, 3 and 5 for real transforms (`real = true`), and also 7 and 11
36/// for complex ones. Found by enumerating the products of powers of the allowed primes.
37pub fn next_fast_len(target: usize, real: bool) -> usize {
38    if target <= 1 {
39        return target.max(1);
40    }
41    let primes: &[usize] = if real { &[2, 3, 5] } else { &[2, 3, 5, 7, 11] };
42    let mut best = usize::MAX;
43    // Depth-first over exponents: each partial product that reaches the target is a candidate.
44    fn search(product: usize, primes: &[usize], target: usize, best: &mut usize) {
45        if product >= target {
46            *best = (*best).min(product);
47            return;
48        }
49        let Some((&p, rest)) = primes.split_first() else { return };
50        let mut q = product;
51        loop {
52            search(q, rest, target, best);
53            if q >= target || q > usize::MAX / p {
54                break;
55            }
56            q *= p;
57        }
58    }
59    search(1, primes, target, &mut best);
60    best
61}
62// ANCHOR_END: next_fast_len
63
64/// The inverse of [`fftshift`](crate::fftshift): moves the zero-frequency bin from the centre
65/// back to index 0 along every axis (they differ for odd lengths).
66pub fn ifftshift(data: &ArrayD<C64>) -> ArrayD<C64> {
67    let shape = data.shape().to_vec();
68    ArrayD::from_shape_fn(data.raw_dim(), |idx| {
69        let src: Vec<usize> = (0..shape.len()).map(|d| (idx[d] + shape[d] / 2) % shape[d]).collect();
70        data[IxDyn(&src)]
71    })
72}
73
74/// One-dimensional `fftshift` for a slice of any element type.
75pub fn fftshift_1d<T: Clone>(x: &[T]) -> Vec<T> {
76    let n = x.len();
77    (0..n).map(|k| x[(k + n - n / 2) % n].clone()).collect()
78}
79
80/// One-dimensional `ifftshift` for a slice of any element type.
81pub fn ifftshift_1d<T: Clone>(x: &[T]) -> Vec<T> {
82    let n = x.len();
83    (0..n).map(|k| x[(k + n / 2) % n].clone()).collect()
84}
85
86// ANCHOR: rfftn
87/// The N-dimensional DFT of real data (SciPy's `rfftn`): a real FFT along the last axis, keeping
88/// the `⌊n/2⌋ + 1` non-negative frequencies, then complex FFTs along the other axes. The result
89/// has the input's shape with the last axis shortened.
90pub fn rfftn(data: &ArrayD<f64>) -> Result<ArrayD<C64>, ErrorsJSL> {
91    let nd = data.ndim();
92    if nd == 0 {
93        return Err(ErrorsJSL::InvalidInputRange("The array must have at least one axis."));
94    }
95    let last = data.len_of(Axis(nd - 1));
96    if last == 0 {
97        return Err(ErrorsJSL::InvalidInputRange("The last axis must not be empty."));
98    }
99    let mut shape = data.shape().to_vec();
100    shape[nd - 1] = last / 2 + 1;
101    let mut out = ArrayD::<C64>::zeros(IxDyn(&shape));
102    for (lane, mut target) in data.lanes(Axis(nd - 1)).into_iter().zip(out.lanes_mut(Axis(nd - 1))) {
103        let spectrum = rfft(&lane.to_vec())?;
104        target.iter_mut().zip(spectrum).for_each(|(t, s)| *t = s);
105    }
106    for axis in 0..nd - 1 {
107        fft_axis(&mut out, axis, FftDirection::Forward)?;
108    }
109    Ok(out)
110}
111// ANCHOR_END: rfftn
112
113/// The inverse of [`rfftn`] (SciPy's `irfftn`): `shape` is the shape of the real output, needed
114/// because the last axis of length `n` and `n + 1` have the same half spectrum when `n` is even.
115/// Scaled so that `irfftn(rfftn(x), x.shape()) = x`.
116pub fn irfftn(spectrum: &ArrayD<C64>, shape: &[usize]) -> Result<ArrayD<f64>, ErrorsJSL> {
117    let nd = spectrum.ndim();
118    if shape.len() != nd || nd == 0 {
119        return Err(ErrorsJSL::InvalidInputRange("The output shape must have one entry per axis."));
120    }
121    let n = shape[nd - 1];
122    if spectrum.shape()[..nd - 1] != shape[..nd - 1] || spectrum.len_of(Axis(nd - 1)) != n / 2 + 1 {
123        return Err(ErrorsJSL::InvalidInputRange("The spectrum does not match the output shape."));
124    }
125    let mut work = spectrum.clone();
126    for axis in 0..nd - 1 {
127        fft_axis(&mut work, axis, FftDirection::Inverse)?;
128    }
129    let mut out = ArrayD::<f64>::zeros(IxDyn(shape));
130    for (lane, mut target) in work.lanes(Axis(nd - 1)).into_iter().zip(out.lanes_mut(Axis(nd - 1))) {
131        let x = irfft(&lane.to_vec(), n)?;
132        target.iter_mut().zip(x).for_each(|(t, s)| *t = s);
133    }
134    Ok(out)
135}
136
137fn along_every_axis(data: &ArrayD<f64>, f: impl Fn(&[f64]) -> Result<Vec<f64>, ErrorsJSL>) -> Result<ArrayD<f64>, ErrorsJSL> {
138    let mut out = data.clone();
139    for axis in 0..out.ndim() {
140        for mut lane in out.lanes_mut(Axis(axis)) {
141            let y = f(&lane.to_vec())?;
142            lane.iter_mut().zip(y).for_each(|(t, s)| *t = s);
143        }
144    }
145    Ok(out)
146}
147
148// ANCHOR: dctn
149/// The N-dimensional DCT (SciPy's `dctn`): the 1-D [`dct`] along every axis in turn, which is
150/// valid because the transform is separable.
151pub fn dctn(data: &ArrayD<f64>, kind: TrigTransformType, norm: TrigNormalization) -> Result<ArrayD<f64>, ErrorsJSL> {
152    along_every_axis(data, |x| dct(x, kind, norm))
153}
154// ANCHOR_END: dctn
155
156/// The inverse of [`dctn`] with the same type and normalization.
157pub fn idctn(data: &ArrayD<f64>, kind: TrigTransformType, norm: TrigNormalization) -> Result<ArrayD<f64>, ErrorsJSL> {
158    along_every_axis(data, |x| idct(x, kind, norm))
159}
160
161/// The N-dimensional DST (SciPy's `dstn`).
162pub fn dstn(data: &ArrayD<f64>, kind: TrigTransformType, norm: TrigNormalization) -> Result<ArrayD<f64>, ErrorsJSL> {
163    along_every_axis(data, |x| dst(x, kind, norm))
164}
165
166/// The inverse of [`dstn`] with the same type and normalization.
167pub fn idstn(data: &ArrayD<f64>, kind: TrigTransformType, norm: TrigNormalization) -> Result<ArrayD<f64>, ErrorsJSL> {
168    along_every_axis(data, |x| idst(x, kind, norm))
169}
170
171#[cfg(test)]
172mod tests {
173    use super::*;
174    use crate::multidimensional_fft::{fftn, fftshift};
175
176    #[test]
177    fn frequency_grids_match_numpy() {
178        assert_eq!(fftfreq(5, 0.1), vec![0.0, 2.0, 4.0, -4.0, -2.0]);
179        assert_eq!(fftfreq(4, 1.0), vec![0.0, 0.25, -0.5, -0.25]);
180        assert_eq!(rfftfreq(5, 0.1), vec![0.0, 2.0, 4.0]);
181        assert_eq!(rfftfreq(4, 1.0), vec![0.0, 0.25, 0.5]);
182    }
183
184    #[test]
185    fn fast_lengths() {
186        assert_eq!(next_fast_len(1021, true), 1024);
187        assert_eq!(next_fast_len(1021, false), 1024);
188        assert_eq!(next_fast_len(97, true), 100);
189        assert_eq!(next_fast_len(97, false), 98);
190        assert_eq!(next_fast_len(13, false), 14);
191        assert_eq!(next_fast_len(1, true), 1);
192        for t in 2..500 {
193            let n = next_fast_len(t, false);
194            assert!(n >= t);
195            let mut m = n;
196            for p in [2, 3, 5, 7, 11] {
197                while m.is_multiple_of(p) {
198                    m /= p;
199                }
200            }
201            assert_eq!(m, 1);
202        }
203    }
204
205    #[test]
206    fn shifts_invert_each_other() {
207        let x: Vec<i32> = (0..7).collect();
208        assert_eq!(fftshift_1d(&x), vec![4, 5, 6, 0, 1, 2, 3]);
209        assert_eq!(ifftshift_1d(&fftshift_1d(&x)), x);
210        let a = ArrayD::from_shape_fn(IxDyn(&[3, 4]), |i| C64::new((i[0] * 4 + i[1]) as f64, 0.0));
211        assert_eq!(ifftshift(&fftshift(&a)), a);
212    }
213
214    #[test]
215    fn rfftn_is_the_half_spectrum_of_fftn() {
216        let x = ArrayD::from_shape_fn(IxDyn(&[3, 4, 5]), |i| ((i[0] * 7 + i[1] * 3 + i[2]) as f64).sin());
217        let half = rfftn(&x).unwrap();
218        assert_eq!(half.shape(), &[3, 4, 3]);
219        let full = fftn(&x.mapv(|v| C64::new(v, 0.0)), FftDirection::Forward).unwrap();
220        for (idx, v) in half.indexed_iter() {
221            assert!((v - full[idx.clone()]).norm() < 1e-12);
222        }
223        let back = irfftn(&half, &[3, 4, 5]).unwrap();
224        assert!(back.iter().zip(x.iter()).all(|(a, b)| (a - b).abs() < 1e-13));
225    }
226
227    #[test]
228    fn dctn_inverts() {
229        let x = ArrayD::from_shape_fn(IxDyn(&[4, 6]), |i| (i[0] as f64 - 1.3) * (i[1] as f64 + 0.2).cos());
230        for kind in [TrigTransformType::I, TrigTransformType::II, TrigTransformType::III, TrigTransformType::IV] {
231            for norm in [TrigNormalization::Backward, TrigNormalization::Ortho] {
232                let y = dctn(&x, kind, norm).unwrap();
233                let back = idctn(&y, kind, norm).unwrap();
234                assert!(back.iter().zip(x.iter()).all(|(a, b)| (a - b).abs() < 1e-12));
235                let y = dstn(&x, kind, norm).unwrap();
236                let back = idstn(&y, kind, norm).unwrap();
237                assert!(back.iter().zip(x.iter()).all(|(a, b)| (a - b).abs() < 1e-12));
238            }
239        }
240    }
241}