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};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
pub enum Norm {
#[default]
Backward,
Ortho,
Forward,
}
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)
}
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))
}
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)
}
}
#[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;
}
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
}
#[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,
)
})
}
#[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,
)
})
}
#[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,
)
})
}
#[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,
)
})
}
#[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))
}
#[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))
}
#[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))
}
#[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))
}
#[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))
}
#[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))
}
#[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))
}
#[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))
}
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)
}
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))
}
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(),
}
}
#[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)
})
}
#[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)
})
}