Skip to main content

ruxla_core/jnp/
fft.rs

1//! Discrete Fourier transforms following `jax.numpy.fft`.
2//!
3//! The transforms compute what JAX's compute, with the same primitives: the
4//! operand is sliced or padded with zeros to the lengths `s`, the axes are
5//! moved last, and up to three axes are transformed at a time (`lax.fft`).
6//! As elsewhere in ruxla, types are not promoted: `fft` takes complex
7//! numbers, `rfft` takes `f32` or `f64`.
8//!
9//! # Examples
10//!
11//! ```
12//! use ruxla_core::{Array, Native, c64, jnp};
13//!
14//! let x = Array::<Native, f32>::from_vec(vec![1.0, 2.0, 3.0, 4.0], [4]);
15//! let y = jnp::fft::rfft(&x, None, -1, None);
16//! assert_eq!(y.to_vec()[0], c64::new(10.0, 0.0));
17//! let back = jnp::fft::irfft(&y, Some(4), -1, None);
18//! for (a, b) in back.to_vec().iter().zip([1.0, 2.0, 3.0, 4.0]) {
19//!     assert!((a - b).abs() < 1e-6);
20//! }
21//! ```
22
23use ruxla_ir::{FftType, Shape};
24use ruxla_kernels::{Element, cast};
25
26use crate::backend::Backend;
27use crate::jnp::normalize_axis;
28use crate::lax;
29use crate::value::{Array, ArrayLike, ComplexFloat, Float, Inexact, RealFloat, Scalar};
30
31/// The normalization of a transform (`norm` of `jax.numpy.fft`). `None`
32/// stands for [`Norm::Backward`].
33#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
34pub enum Norm {
35    /// The forward transform is not scaled; the inverse divides by `n`.
36    #[default]
37    Backward,
38    /// Both directions divide by `sqrt(n)`.
39    Ortho,
40    /// The forward transform divides by `n`; the inverse is not scaled.
41    Forward,
42}
43
44/// `jnp.moveaxis`: moves the axes `src` to the positions `dst`.
45fn moveaxis<B: Backend, T: Element>(x: &Array<B, T>, src: &[usize], dst: &[usize]) -> Array<B, T> {
46    let ndim = x.ndim();
47    let mut order: Vec<usize> = (0..ndim).filter(|i| !src.contains(i)).collect();
48    let mut pairs: Vec<(usize, usize)> = dst.iter().copied().zip(src.iter().copied()).collect();
49    pairs.sort_unstable();
50    for (d, s) in pairs {
51        order.insert(d, s);
52    }
53    if order.iter().enumerate().all(|(i, &o)| i == o) {
54        return x.clone();
55    }
56    x.transpose(&order)
57}
58
59/// `lax.fft` from `T` to `U` (the primitive checks the types).
60fn raw_fft<B: Backend, T: Element, U: Element>(
61    x: &Array<B, T>,
62    fft_type: FftType,
63    lengths: &[usize],
64) -> Array<B, U> {
65    Array(B::fft::<T, U>(&x.0, fft_type, lengths))
66}
67
68/// JAX's `_fft_core_nd`: transforms of more than three axes are split into
69/// transforms of up to three axes.
70fn core_nd<B: Backend, T: Element, U: Element>(
71    arr: &Array<B, T>,
72    fft_type: FftType,
73    s: &[usize],
74) -> Array<B, U> {
75    if s.len() <= 3 {
76        return raw_fft(arr, fft_type, s);
77    }
78    let ndim = arr.ndim();
79    let n = if s.len() == 4 { 2 } else { 3 };
80    let src: Vec<usize> = (ndim - s.len()..ndim - n).collect();
81    let dst: Vec<usize> = (ndim - s.len() + n..ndim).collect();
82    let (outer, inner) = s.split_at(s.len() - n);
83    if matches!(fft_type, FftType::Rfft | FftType::Fft) {
84        let a: Array<B, U> = raw_fft(arr, fft_type, inner);
85        let a = moveaxis(&a, &src, &dst);
86        let a: Array<B, U> = core_nd(&a, FftType::Fft, outer);
87        moveaxis(&a, &dst, &src)
88    } else {
89        let a = moveaxis(arr, &src, &dst);
90        let a: Array<B, T> = core_nd(&a, FftType::Ifft, outer);
91        let a = moveaxis(&a, &dst, &src);
92        raw_fft(&a, fft_type, inner)
93    }
94}
95
96/// JAX's `_fft_core`.
97#[track_caller]
98fn core<B: Backend, T: Element, U: Inexact>(
99    fft_type: FftType,
100    a: &Array<B, T>,
101    s: Option<&[usize]>,
102    axes: Option<&[i64]>,
103    norm: Option<Norm>,
104) -> Array<B, U> {
105    let ndim = a.ndim();
106    if let Some(s) = s {
107        assert!(s.iter().all(|&x| x > 0), "Shape should be positive.");
108        if let Some(axes) = axes {
109            assert_eq!(
110                s.len(),
111                axes.len(),
112                "Shape and axes have different lengths."
113            );
114        }
115    }
116    let orig_axes: Option<Vec<usize>> =
117        axes.map(|a| a.iter().map(|&x| normalize_axis(x, ndim)).collect());
118    let mut axes: Vec<usize> = match (&orig_axes, s) {
119        (Some(a), _) => a.clone(),
120        (None, None) => (0..ndim).collect(),
121        (None, Some(s)) => (ndim - s.len()..ndim).collect(),
122    };
123    for (i, ax) in axes.iter().enumerate() {
124        assert!(
125            !axes[..i].contains(ax),
126            "the transforms do not support repeated axes, got {axes:?}"
127        );
128    }
129    assert!(!axes.is_empty(), "the transforms need at least one axis");
130    let mut arr = a.clone();
131    if let Some(orig) = &orig_axes {
132        axes = (ndim - orig.len()..ndim).collect();
133        arr = moveaxis(&arr, orig, &axes);
134    }
135    let shape = arr.shape();
136    let s: Vec<usize> = match s {
137        Some(s) => {
138            let mut in_s: Vec<usize> = shape.dims().to_vec();
139            for (&axis, &x) in axes.iter().zip(s) {
140                in_s[axis] = x;
141            }
142            if fft_type == FftType::Irfft {
143                in_s[ndim - 1] = in_s[ndim - 1] / 2 + 1;
144            }
145            // Slice to the lengths, then pad with zeros.
146            let limit: Vec<usize> = in_s
147                .iter()
148                .zip(shape.iter())
149                .map(|(&a, &b)| a.min(b))
150                .collect();
151            if limit != shape.dims() {
152                arr = lax::slice(&arr, &vec![0; ndim], &limit, None);
153            }
154            if in_s != limit {
155                let config: Vec<(i64, i64, usize)> = in_s
156                    .iter()
157                    .zip(&limit)
158                    .map(|(&a, &b)| (0, (a - b) as i64, 0))
159                    .collect();
160                arr = lax::pad(&arr, T::default(), &config);
161            }
162            s.to_vec()
163        }
164        None => {
165            if fft_type == FftType::Irfft {
166                let mut s: Vec<usize> = axes[..axes.len() - 1].iter().map(|&a| shape[a]).collect();
167                s.push((2 * shape[axes[axes.len() - 1]]).saturating_sub(2));
168                s
169            } else {
170                axes.iter().map(|&a| shape[a]).collect()
171            }
172        }
173    };
174    let mut out: Array<B, U> = core_nd(&arr, fft_type, &s);
175    let inverse = matches!(fft_type, FftType::Ifft | FftType::Irfft);
176    let factor = match norm.unwrap_or_default() {
177        Norm::Backward => None,
178        Norm::Ortho => {
179            let r = (s.iter().product::<usize>() as f64).sqrt();
180            Some(if inverse { r } else { 1.0 / r })
181        }
182        Norm::Forward => {
183            let n = s.iter().product::<usize>() as f64;
184            Some(if inverse { n } else { 1.0 / n })
185        }
186    };
187    if let Some(f) = factor {
188        out = out * Scalar::<B, U>::new(cast::<f64, U>(f));
189    }
190    if let Some(orig) = &orig_axes {
191        out = moveaxis(&out, &axes, orig);
192    }
193    out
194}
195
196/// The one-dimensional discrete Fourier transform along `axis`, of length
197/// `n` (the operand is sliced or padded with zeros; its length by default).
198#[track_caller]
199pub fn fft<B: Backend, C: ComplexFloat>(
200    a: impl ArrayLike<B, C>,
201    n: Option<usize>,
202    axis: i64,
203    norm: Option<Norm>,
204) -> Array<B, C> {
205    let s = n.map(|n| [n]);
206    a.with_array(|a| {
207        core(
208            FftType::Fft,
209            a,
210            s.as_ref().map(|s| &s[..]),
211            Some(&[axis]),
212            norm,
213        )
214    })
215}
216
217/// The one-dimensional inverse transform (see [`fft`]).
218#[track_caller]
219pub fn ifft<B: Backend, C: ComplexFloat>(
220    a: impl ArrayLike<B, C>,
221    n: Option<usize>,
222    axis: i64,
223    norm: Option<Norm>,
224) -> Array<B, C> {
225    let s = n.map(|n| [n]);
226    a.with_array(|a| {
227        core(
228            FftType::Ifft,
229            a,
230            s.as_ref().map(|s| &s[..]),
231            Some(&[axis]),
232            norm,
233        )
234    })
235}
236
237/// The one-dimensional transform of real numbers: the `n / 2 + 1`
238/// nonnegative frequencies.
239#[track_caller]
240pub fn rfft<B: Backend, R: RealFloat>(
241    a: impl ArrayLike<B, R>,
242    n: Option<usize>,
243    axis: i64,
244    norm: Option<Norm>,
245) -> Array<B, R::Complex> {
246    let s = n.map(|n| [n]);
247    a.with_array(|a| {
248        core(
249            FftType::Rfft,
250            a,
251            s.as_ref().map(|s| &s[..]),
252            Some(&[axis]),
253            norm,
254        )
255    })
256}
257
258/// The inverse of [`rfft`]: `n` real numbers (`2 (m - 1)` by default, for
259/// `m` coefficients).
260#[track_caller]
261pub fn irfft<B: Backend, C: ComplexFloat>(
262    a: impl ArrayLike<B, C>,
263    n: Option<usize>,
264    axis: i64,
265    norm: Option<Norm>,
266) -> Array<B, C::Real> {
267    let s = n.map(|n| [n]);
268    a.with_array(|a| {
269        core(
270            FftType::Irfft,
271            a,
272            s.as_ref().map(|s| &s[..]),
273            Some(&[axis]),
274            norm,
275        )
276    })
277}
278
279/// The two-dimensional transform of `axes` (`[-2, -1]` in JAX), of lengths
280/// `s`.
281#[track_caller]
282pub fn fft2<B: Backend, C: ComplexFloat>(
283    a: impl ArrayLike<B, C>,
284    s: Option<&[usize]>,
285    axes: &[i64],
286    norm: Option<Norm>,
287) -> Array<B, C> {
288    assert_eq!(axes.len(), 2, "fft2 only supports 2 axes, got {axes:?}");
289    a.with_array(|a| core(FftType::Fft, a, s, Some(axes), norm))
290}
291
292/// The two-dimensional inverse transform (see [`fft2`]).
293#[track_caller]
294pub fn ifft2<B: Backend, C: ComplexFloat>(
295    a: impl ArrayLike<B, C>,
296    s: Option<&[usize]>,
297    axes: &[i64],
298    norm: Option<Norm>,
299) -> Array<B, C> {
300    assert_eq!(axes.len(), 2, "ifft2 only supports 2 axes, got {axes:?}");
301    a.with_array(|a| core(FftType::Ifft, a, s, Some(axes), norm))
302}
303
304/// The two-dimensional transform of real numbers (see [`rfftn`]).
305#[track_caller]
306pub fn rfft2<B: Backend, R: RealFloat>(
307    a: impl ArrayLike<B, R>,
308    s: Option<&[usize]>,
309    axes: &[i64],
310    norm: Option<Norm>,
311) -> Array<B, R::Complex> {
312    assert_eq!(axes.len(), 2, "rfft2 only supports 2 axes, got {axes:?}");
313    a.with_array(|a| core(FftType::Rfft, a, s, Some(axes), norm))
314}
315
316/// The two-dimensional inverse of [`rfft2`].
317#[track_caller]
318pub fn irfft2<B: Backend, C: ComplexFloat>(
319    a: impl ArrayLike<B, C>,
320    s: Option<&[usize]>,
321    axes: &[i64],
322    norm: Option<Norm>,
323) -> Array<B, C::Real> {
324    assert_eq!(axes.len(), 2, "irfft2 only supports 2 axes, got {axes:?}");
325    a.with_array(|a| core(FftType::Irfft, a, s, Some(axes), norm))
326}
327
328/// The transform of `axes` (every axis by default, or the last `s.len()`),
329/// of lengths `s` (those of the operand by default).
330#[track_caller]
331pub fn fftn<B: Backend, C: ComplexFloat>(
332    a: impl ArrayLike<B, C>,
333    s: Option<&[usize]>,
334    axes: Option<&[i64]>,
335    norm: Option<Norm>,
336) -> Array<B, C> {
337    a.with_array(|a| core(FftType::Fft, a, s, axes, norm))
338}
339
340/// The inverse transform of `axes` (see [`fftn`]).
341#[track_caller]
342pub fn ifftn<B: Backend, C: ComplexFloat>(
343    a: impl ArrayLike<B, C>,
344    s: Option<&[usize]>,
345    axes: Option<&[i64]>,
346    norm: Option<Norm>,
347) -> Array<B, C> {
348    a.with_array(|a| core(FftType::Ifft, a, s, axes, norm))
349}
350
351/// The transform of real numbers along `axes` (see [`fftn`]): the last axis
352/// has `s[-1] / 2 + 1` coefficients.
353#[track_caller]
354pub fn rfftn<B: Backend, R: RealFloat>(
355    a: impl ArrayLike<B, R>,
356    s: Option<&[usize]>,
357    axes: Option<&[i64]>,
358    norm: Option<Norm>,
359) -> Array<B, R::Complex> {
360    a.with_array(|a| core(FftType::Rfft, a, s, axes, norm))
361}
362
363/// The inverse of [`rfftn`]: real numbers of lengths `s` (by default, those
364/// of the operand, and `2 (m - 1)` along the last axis).
365#[track_caller]
366pub fn irfftn<B: Backend, C: ComplexFloat>(
367    a: impl ArrayLike<B, C>,
368    s: Option<&[usize]>,
369    axes: Option<&[i64]>,
370    norm: Option<Norm>,
371) -> Array<B, C::Real> {
372    a.with_array(|a| core(FftType::Irfft, a, s, axes, norm))
373}
374
375/// The frequencies of the coefficients of [`fft`] of length `n` with sample
376/// spacing `d`: `[0, 1, ..., n / 2 - 1, -n / 2, ..., -1] / (d n)` (for even
377/// `n`).
378pub fn fftfreq<B: Backend, T: Float>(n: usize, d: f64) -> Array<B, T> {
379    let c = |v: f64| Scalar::<B, T>::new(cast::<f64, T>(v));
380    let i: Array<B, T> = lax::iota([n], 0);
381    let half = (n / 2) as f64;
382    let k = (i + c(half)) % c(n as f64) - c(half);
383    k / c(d * n as f64)
384}
385
386/// The frequencies of the coefficients of [`rfft`] of length `n` with
387/// sample spacing `d`: `[0, 1, ..., n / 2] / (d n)`.
388pub fn rfftfreq<B: Backend, T: Float>(n: usize, d: f64) -> Array<B, T> {
389    let k: Array<B, T> = lax::iota([n / 2 + 1], 0);
390    k / Scalar::<B, T>::new(cast::<f64, T>(d * n as f64))
391}
392
393/// `jnp.roll` with static shifts of some axes.
394fn roll<B: Backend, T: Element>(x: &Array<B, T>, shifts: &[i64], axes: &[usize]) -> Array<B, T> {
395    let mut x = x.clone();
396    for (&shift, &axis) in shifts.iter().zip(axes) {
397        let n = x.shape()[axis];
398        if n == 0 {
399            continue;
400        }
401        let shift = shift.rem_euclid(n as i64) as usize;
402        if shift == 0 {
403            continue;
404        }
405        let tail = lax::slice_in_dim(&x, n - shift, n, 1, axis);
406        let head = lax::slice_in_dim(&x, 0, n - shift, 1, axis);
407        x = lax::concatenate(&[tail, head], axis);
408    }
409    x
410}
411
412fn shift_axes(shape: &Shape, axes: Option<&[i64]>) -> Vec<usize> {
413    match axes {
414        None => (0..shape.rank()).collect(),
415        Some(a) => a.iter().map(|&x| normalize_axis(x, shape.rank())).collect(),
416    }
417}
418
419/// Moves the zero frequency to the center of `axes` (every axis by
420/// default): a roll by half of each length.
421#[track_caller]
422pub fn fftshift<B: Backend, T: Element>(
423    x: impl ArrayLike<B, T>,
424    axes: Option<&[i64]>,
425) -> Array<B, T> {
426    x.with_array(|x| {
427        let shape = x.shape();
428        let axes = shift_axes(&shape, axes);
429        let shifts: Vec<i64> = axes.iter().map(|&a| (shape[a] / 2) as i64).collect();
430        roll(x, &shifts, &axes)
431    })
432}
433
434/// The inverse of [`fftshift`].
435#[track_caller]
436pub fn ifftshift<B: Backend, T: Element>(
437    x: impl ArrayLike<B, T>,
438    axes: Option<&[i64]>,
439) -> Array<B, T> {
440    x.with_array(|x| {
441        let shape = x.shape();
442        let axes = shift_axes(&shape, axes);
443        let shifts: Vec<i64> = axes.iter().map(|&a| -((shape[a] / 2) as i64)).collect();
444        roll(x, &shifts, &axes)
445    })
446}