use crate::error::Error;
use itertools::Itertools;
use ndarray::{Array, Array1, ArrayD, AsArray, Axis, Dimension, RemoveAxis, concatenate, s};
use ndrustfft::{FftHandler, Normalization, ndfft_par, ndifft_par};
use num::Complex;
use num::traits::FloatConst;
use std::ops::MulAssign;
pub fn fft<'a, A, D>(array: A) -> Result<Array<Complex<f64>, D>, Error>
where
A: AsArray<'a, f64, D>,
D: Dimension,
{
let mut input = array.into().mapv(|i| Complex::new(i, 0.0));
let shape = input.shape().to_vec();
let mut tmp = ArrayD::zeros(shape.clone()).into_dimensionality()?;
for (i, s) in shape.iter().enumerate() {
let handler = FftHandler::new(*s).normalization(Normalization::None);
ndfft_par(&input.view(), &mut tmp.view_mut(), &handler, i);
std::mem::swap(&mut input, &mut tmp);
}
Ok(input)
}
pub fn ifft<'a, A, D>(array: A) -> Result<Array<Complex<f64>, D>, Error>
where
A: AsArray<'a, Complex<f64>, D>,
D: Dimension,
{
let mut input = array.into().to_owned();
let shape = input.shape().to_vec();
let mut tmp = ArrayD::zeros(shape.clone()).into_dimensionality()?;
for (i, s) in shape.iter().enumerate() {
let handler = FftHandler::new(*s).normalization(Normalization::None);
ndifft_par(&input.view(), &mut tmp.view_mut(), &handler, i);
std::mem::swap(&mut input, &mut tmp);
}
Ok(input / Complex::from(shape.iter().product::<usize>() as f64))
}
pub fn fft_freq(size: usize) -> Array1<f64> {
let val = 1.0 / size as f64;
let mut results = Array1::zeros(size);
let n = (size - 1) / 2 + 1;
let p1 = Array1::range(0.0, n as f64, 1.0);
results.slice_mut(s![..n]).assign(&p1);
let p2 = Array1::range(-((size / 2) as f64), 0.0, 1.0);
results.slice_mut(s![n..]).assign(&p2);
results * val
}
pub fn fft_shift<'a, A, T, D>(x: A) -> Array<T, D>
where
A: AsArray<'a, T, D>,
T: 'a + Clone,
D: Dimension + RemoveAxis,
{
let mut x = x.into().to_owned();
let shift = x.shape().iter().map(|i| i / 2).collect::<Vec<_>>();
for (i, s) in shift.iter().enumerate() {
let (a, b) = x.view().split_at(Axis(i), *s);
x = concatenate(Axis(i), &[b, a]).unwrap();
}
x
}
pub fn gaussian(x: &[f64], mu: f64, sigma: f64) -> Vec<f64> {
let a = 2.0 * sigma.powi(2);
let b = (a * f64::PI()).sqrt();
x.iter()
.map(|i| (-(i - mu).powi(2) / a).exp() / b)
.collect()
}
pub fn gaussian_kernel<D>(shape: &[usize], sigma: &[f64]) -> Result<Array<Complex<f64>, D>, Error>
where
D: Dimension,
{
let mut g = Array::ones(shape).into_dimensionality()?;
for (i, (s, t)) in shape.iter().zip_eq(sigma.iter()).enumerate() {
let a = 0.5 / t.powi(2);
let f = (-(f64::PI() * fft_freq(*s)).powi(2) / a)
.exp()
.mapv(Complex::from);
for mut lane in g.lanes_mut(Axis(i)) {
lane.mul_assign(&f);
}
}
Ok(g)
}
pub fn gaussian_smooth<'a, A, D>(array: A, sigma: &[f64]) -> Result<Array<f64, D>, Error>
where
A: AsArray<'a, f64, D>,
D: Dimension,
{
let array = array.into().to_owned();
let shape = array.shape();
let kernel = gaussian_kernel::<D>(shape, sigma)?;
Ok(ifft((kernel * fft(array.view())?).view())?.mapv(|i| i.re))
}