ruxla-core 0.1.0

Internal crate of ruxla (use the `ruxla` crate): the frontend of ruxla (backend-generic values, native and tracing backends)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
//! Discrete Fourier transforms following `jax.numpy.fft`.
//!
//! The transforms compute what JAX's compute, with the same primitives: the
//! operand is sliced or padded with zeros to the lengths `s`, the axes are
//! moved last, and up to three axes are transformed at a time (`lax.fft`).
//! As elsewhere in ruxla, types are not promoted: `fft` takes complex
//! numbers, `rfft` takes `f32` or `f64`.
//!
//! # Examples
//!
//! ```
//! use ruxla_core::{Array, Native, c64, jnp};
//!
//! let x = Array::<Native, f32>::from_vec(vec![1.0, 2.0, 3.0, 4.0], [4]);
//! let y = jnp::fft::rfft(&x, None, -1, None);
//! assert_eq!(y.to_vec()[0], c64::new(10.0, 0.0));
//! let back = jnp::fft::irfft(&y, Some(4), -1, None);
//! for (a, b) in back.to_vec().iter().zip([1.0, 2.0, 3.0, 4.0]) {
//!     assert!((a - b).abs() < 1e-6);
//! }
//! ```

use ruxla_ir::{FftType, Shape};
use ruxla_kernels::{Element, cast};

use crate::backend::Backend;
use crate::jnp::normalize_axis;
use crate::lax;
use crate::value::{Array, ArrayLike, ComplexFloat, Float, Inexact, RealFloat, Scalar};

/// The normalization of a transform (`norm` of `jax.numpy.fft`). `None`
/// stands for [`Norm::Backward`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
pub enum Norm {
    /// The forward transform is not scaled; the inverse divides by `n`.
    #[default]
    Backward,
    /// Both directions divide by `sqrt(n)`.
    Ortho,
    /// The forward transform divides by `n`; the inverse is not scaled.
    Forward,
}

/// `jnp.moveaxis`: moves the axes `src` to the positions `dst`.
fn moveaxis<B: Backend, T: Element>(x: &Array<B, T>, src: &[usize], dst: &[usize]) -> Array<B, T> {
    let ndim = x.ndim();
    let mut order: Vec<usize> = (0..ndim).filter(|i| !src.contains(i)).collect();
    let mut pairs: Vec<(usize, usize)> = dst.iter().copied().zip(src.iter().copied()).collect();
    pairs.sort_unstable();
    for (d, s) in pairs {
        order.insert(d, s);
    }
    if order.iter().enumerate().all(|(i, &o)| i == o) {
        return x.clone();
    }
    x.transpose(&order)
}

/// `lax.fft` from `T` to `U` (the primitive checks the types).
fn raw_fft<B: Backend, T: Element, U: Element>(
    x: &Array<B, T>,
    fft_type: FftType,
    lengths: &[usize],
) -> Array<B, U> {
    Array(B::fft::<T, U>(&x.0, fft_type, lengths))
}

/// JAX's `_fft_core_nd`: transforms of more than three axes are split into
/// transforms of up to three axes.
fn core_nd<B: Backend, T: Element, U: Element>(
    arr: &Array<B, T>,
    fft_type: FftType,
    s: &[usize],
) -> Array<B, U> {
    if s.len() <= 3 {
        return raw_fft(arr, fft_type, s);
    }
    let ndim = arr.ndim();
    let n = if s.len() == 4 { 2 } else { 3 };
    let src: Vec<usize> = (ndim - s.len()..ndim - n).collect();
    let dst: Vec<usize> = (ndim - s.len() + n..ndim).collect();
    let (outer, inner) = s.split_at(s.len() - n);
    if matches!(fft_type, FftType::Rfft | FftType::Fft) {
        let a: Array<B, U> = raw_fft(arr, fft_type, inner);
        let a = moveaxis(&a, &src, &dst);
        let a: Array<B, U> = core_nd(&a, FftType::Fft, outer);
        moveaxis(&a, &dst, &src)
    } else {
        let a = moveaxis(arr, &src, &dst);
        let a: Array<B, T> = core_nd(&a, FftType::Ifft, outer);
        let a = moveaxis(&a, &dst, &src);
        raw_fft(&a, fft_type, inner)
    }
}

/// JAX's `_fft_core`.
#[track_caller]
fn core<B: Backend, T: Element, U: Inexact>(
    fft_type: FftType,
    a: &Array<B, T>,
    s: Option<&[usize]>,
    axes: Option<&[i64]>,
    norm: Option<Norm>,
) -> Array<B, U> {
    let ndim = a.ndim();
    if let Some(s) = s {
        assert!(s.iter().all(|&x| x > 0), "Shape should be positive.");
        if let Some(axes) = axes {
            assert_eq!(
                s.len(),
                axes.len(),
                "Shape and axes have different lengths."
            );
        }
    }
    let orig_axes: Option<Vec<usize>> =
        axes.map(|a| a.iter().map(|&x| normalize_axis(x, ndim)).collect());
    let mut axes: Vec<usize> = match (&orig_axes, s) {
        (Some(a), _) => a.clone(),
        (None, None) => (0..ndim).collect(),
        (None, Some(s)) => (ndim - s.len()..ndim).collect(),
    };
    for (i, ax) in axes.iter().enumerate() {
        assert!(
            !axes[..i].contains(ax),
            "the transforms do not support repeated axes, got {axes:?}"
        );
    }
    assert!(!axes.is_empty(), "the transforms need at least one axis");
    let mut arr = a.clone();
    if let Some(orig) = &orig_axes {
        axes = (ndim - orig.len()..ndim).collect();
        arr = moveaxis(&arr, orig, &axes);
    }
    let shape = arr.shape();
    let s: Vec<usize> = match s {
        Some(s) => {
            let mut in_s: Vec<usize> = shape.dims().to_vec();
            for (&axis, &x) in axes.iter().zip(s) {
                in_s[axis] = x;
            }
            if fft_type == FftType::Irfft {
                in_s[ndim - 1] = in_s[ndim - 1] / 2 + 1;
            }
            // Slice to the lengths, then pad with zeros.
            let limit: Vec<usize> = in_s
                .iter()
                .zip(shape.iter())
                .map(|(&a, &b)| a.min(b))
                .collect();
            if limit != shape.dims() {
                arr = lax::slice(&arr, &vec![0; ndim], &limit, None);
            }
            if in_s != limit {
                let config: Vec<(i64, i64, usize)> = in_s
                    .iter()
                    .zip(&limit)
                    .map(|(&a, &b)| (0, (a - b) as i64, 0))
                    .collect();
                arr = lax::pad(&arr, T::default(), &config);
            }
            s.to_vec()
        }
        None => {
            if fft_type == FftType::Irfft {
                let mut s: Vec<usize> = axes[..axes.len() - 1].iter().map(|&a| shape[a]).collect();
                s.push((2 * shape[axes[axes.len() - 1]]).saturating_sub(2));
                s
            } else {
                axes.iter().map(|&a| shape[a]).collect()
            }
        }
    };
    let mut out: Array<B, U> = core_nd(&arr, fft_type, &s);
    let inverse = matches!(fft_type, FftType::Ifft | FftType::Irfft);
    let factor = match norm.unwrap_or_default() {
        Norm::Backward => None,
        Norm::Ortho => {
            let r = (s.iter().product::<usize>() as f64).sqrt();
            Some(if inverse { r } else { 1.0 / r })
        }
        Norm::Forward => {
            let n = s.iter().product::<usize>() as f64;
            Some(if inverse { n } else { 1.0 / n })
        }
    };
    if let Some(f) = factor {
        out = out * Scalar::<B, U>::new(cast::<f64, U>(f));
    }
    if let Some(orig) = &orig_axes {
        out = moveaxis(&out, &axes, orig);
    }
    out
}

/// The one-dimensional discrete Fourier transform along `axis`, of length
/// `n` (the operand is sliced or padded with zeros; its length by default).
#[track_caller]
pub fn fft<B: Backend, C: ComplexFloat>(
    a: impl ArrayLike<B, C>,
    n: Option<usize>,
    axis: i64,
    norm: Option<Norm>,
) -> Array<B, C> {
    let s = n.map(|n| [n]);
    a.with_array(|a| {
        core(
            FftType::Fft,
            a,
            s.as_ref().map(|s| &s[..]),
            Some(&[axis]),
            norm,
        )
    })
}

/// The one-dimensional inverse transform (see [`fft`]).
#[track_caller]
pub fn ifft<B: Backend, C: ComplexFloat>(
    a: impl ArrayLike<B, C>,
    n: Option<usize>,
    axis: i64,
    norm: Option<Norm>,
) -> Array<B, C> {
    let s = n.map(|n| [n]);
    a.with_array(|a| {
        core(
            FftType::Ifft,
            a,
            s.as_ref().map(|s| &s[..]),
            Some(&[axis]),
            norm,
        )
    })
}

/// The one-dimensional transform of real numbers: the `n / 2 + 1`
/// nonnegative frequencies.
#[track_caller]
pub fn rfft<B: Backend, R: RealFloat>(
    a: impl ArrayLike<B, R>,
    n: Option<usize>,
    axis: i64,
    norm: Option<Norm>,
) -> Array<B, R::Complex> {
    let s = n.map(|n| [n]);
    a.with_array(|a| {
        core(
            FftType::Rfft,
            a,
            s.as_ref().map(|s| &s[..]),
            Some(&[axis]),
            norm,
        )
    })
}

/// The inverse of [`rfft`]: `n` real numbers (`2 (m - 1)` by default, for
/// `m` coefficients).
#[track_caller]
pub fn irfft<B: Backend, C: ComplexFloat>(
    a: impl ArrayLike<B, C>,
    n: Option<usize>,
    axis: i64,
    norm: Option<Norm>,
) -> Array<B, C::Real> {
    let s = n.map(|n| [n]);
    a.with_array(|a| {
        core(
            FftType::Irfft,
            a,
            s.as_ref().map(|s| &s[..]),
            Some(&[axis]),
            norm,
        )
    })
}

/// The two-dimensional transform of `axes` (`[-2, -1]` in JAX), of lengths
/// `s`.
#[track_caller]
pub fn fft2<B: Backend, C: ComplexFloat>(
    a: impl ArrayLike<B, C>,
    s: Option<&[usize]>,
    axes: &[i64],
    norm: Option<Norm>,
) -> Array<B, C> {
    assert_eq!(axes.len(), 2, "fft2 only supports 2 axes, got {axes:?}");
    a.with_array(|a| core(FftType::Fft, a, s, Some(axes), norm))
}

/// The two-dimensional inverse transform (see [`fft2`]).
#[track_caller]
pub fn ifft2<B: Backend, C: ComplexFloat>(
    a: impl ArrayLike<B, C>,
    s: Option<&[usize]>,
    axes: &[i64],
    norm: Option<Norm>,
) -> Array<B, C> {
    assert_eq!(axes.len(), 2, "ifft2 only supports 2 axes, got {axes:?}");
    a.with_array(|a| core(FftType::Ifft, a, s, Some(axes), norm))
}

/// The two-dimensional transform of real numbers (see [`rfftn`]).
#[track_caller]
pub fn rfft2<B: Backend, R: RealFloat>(
    a: impl ArrayLike<B, R>,
    s: Option<&[usize]>,
    axes: &[i64],
    norm: Option<Norm>,
) -> Array<B, R::Complex> {
    assert_eq!(axes.len(), 2, "rfft2 only supports 2 axes, got {axes:?}");
    a.with_array(|a| core(FftType::Rfft, a, s, Some(axes), norm))
}

/// The two-dimensional inverse of [`rfft2`].
#[track_caller]
pub fn irfft2<B: Backend, C: ComplexFloat>(
    a: impl ArrayLike<B, C>,
    s: Option<&[usize]>,
    axes: &[i64],
    norm: Option<Norm>,
) -> Array<B, C::Real> {
    assert_eq!(axes.len(), 2, "irfft2 only supports 2 axes, got {axes:?}");
    a.with_array(|a| core(FftType::Irfft, a, s, Some(axes), norm))
}

/// The transform of `axes` (every axis by default, or the last `s.len()`),
/// of lengths `s` (those of the operand by default).
#[track_caller]
pub fn fftn<B: Backend, C: ComplexFloat>(
    a: impl ArrayLike<B, C>,
    s: Option<&[usize]>,
    axes: Option<&[i64]>,
    norm: Option<Norm>,
) -> Array<B, C> {
    a.with_array(|a| core(FftType::Fft, a, s, axes, norm))
}

/// The inverse transform of `axes` (see [`fftn`]).
#[track_caller]
pub fn ifftn<B: Backend, C: ComplexFloat>(
    a: impl ArrayLike<B, C>,
    s: Option<&[usize]>,
    axes: Option<&[i64]>,
    norm: Option<Norm>,
) -> Array<B, C> {
    a.with_array(|a| core(FftType::Ifft, a, s, axes, norm))
}

/// The transform of real numbers along `axes` (see [`fftn`]): the last axis
/// has `s[-1] / 2 + 1` coefficients.
#[track_caller]
pub fn rfftn<B: Backend, R: RealFloat>(
    a: impl ArrayLike<B, R>,
    s: Option<&[usize]>,
    axes: Option<&[i64]>,
    norm: Option<Norm>,
) -> Array<B, R::Complex> {
    a.with_array(|a| core(FftType::Rfft, a, s, axes, norm))
}

/// The inverse of [`rfftn`]: real numbers of lengths `s` (by default, those
/// of the operand, and `2 (m - 1)` along the last axis).
#[track_caller]
pub fn irfftn<B: Backend, C: ComplexFloat>(
    a: impl ArrayLike<B, C>,
    s: Option<&[usize]>,
    axes: Option<&[i64]>,
    norm: Option<Norm>,
) -> Array<B, C::Real> {
    a.with_array(|a| core(FftType::Irfft, a, s, axes, norm))
}

/// The frequencies of the coefficients of [`fft`] of length `n` with sample
/// spacing `d`: `[0, 1, ..., n / 2 - 1, -n / 2, ..., -1] / (d n)` (for even
/// `n`).
pub fn fftfreq<B: Backend, T: Float>(n: usize, d: f64) -> Array<B, T> {
    let c = |v: f64| Scalar::<B, T>::new(cast::<f64, T>(v));
    let i: Array<B, T> = lax::iota([n], 0);
    let half = (n / 2) as f64;
    let k = (i + c(half)) % c(n as f64) - c(half);
    k / c(d * n as f64)
}

/// The frequencies of the coefficients of [`rfft`] of length `n` with
/// sample spacing `d`: `[0, 1, ..., n / 2] / (d n)`.
pub fn rfftfreq<B: Backend, T: Float>(n: usize, d: f64) -> Array<B, T> {
    let k: Array<B, T> = lax::iota([n / 2 + 1], 0);
    k / Scalar::<B, T>::new(cast::<f64, T>(d * n as f64))
}

/// `jnp.roll` with static shifts of some axes.
fn roll<B: Backend, T: Element>(x: &Array<B, T>, shifts: &[i64], axes: &[usize]) -> Array<B, T> {
    let mut x = x.clone();
    for (&shift, &axis) in shifts.iter().zip(axes) {
        let n = x.shape()[axis];
        if n == 0 {
            continue;
        }
        let shift = shift.rem_euclid(n as i64) as usize;
        if shift == 0 {
            continue;
        }
        let tail = lax::slice_in_dim(&x, n - shift, n, 1, axis);
        let head = lax::slice_in_dim(&x, 0, n - shift, 1, axis);
        x = lax::concatenate(&[tail, head], axis);
    }
    x
}

fn shift_axes(shape: &Shape, axes: Option<&[i64]>) -> Vec<usize> {
    match axes {
        None => (0..shape.rank()).collect(),
        Some(a) => a.iter().map(|&x| normalize_axis(x, shape.rank())).collect(),
    }
}

/// Moves the zero frequency to the center of `axes` (every axis by
/// default): a roll by half of each length.
#[track_caller]
pub fn fftshift<B: Backend, T: Element>(
    x: impl ArrayLike<B, T>,
    axes: Option<&[i64]>,
) -> Array<B, T> {
    x.with_array(|x| {
        let shape = x.shape();
        let axes = shift_axes(&shape, axes);
        let shifts: Vec<i64> = axes.iter().map(|&a| (shape[a] / 2) as i64).collect();
        roll(x, &shifts, &axes)
    })
}

/// The inverse of [`fftshift`].
#[track_caller]
pub fn ifftshift<B: Backend, T: Element>(
    x: impl ArrayLike<B, T>,
    axes: Option<&[i64]>,
) -> Array<B, T> {
    x.with_array(|x| {
        let shape = x.shape();
        let axes = shift_axes(&shape, axes);
        let shifts: Vec<i64> = axes.iter().map(|&a| -((shape[a] / 2) as i64)).collect();
        roll(x, &shifts, &axes)
    })
}