Real and multidimensional FFTs
| Problem | Compute the DFT of real data, returning only the non-redundant half of the spectrum; compute DFTs of two-, three- and -dimensional arrays |
| Devised by | The two-for-one and half-length tricks: James Cooley, Peter Lewis and Peter Welch (1970); real-data FFTs: Henrik Sorensen, Douglas Jones, Michael Heideman and C. Sidney Burrus (1987); multidimensional transforms by separability: classical |
| Accuracy | , as the underlying complex FFT |
| Cost | Real FFT: one complex FFT of length plus work. -dimensional: for points in all |
| Read first | The fast Fourier transform |
| API | RealFft, rfft, irfft, fft2, ifft2, fft3, fftn, fft_axis, fftshift, fftfreq, rfftfreq, next_fast_len, rfftn, irfftn, dctn, dstn |
Overview
Most measured signals are real, and the DFT of a real signal is conjugate symmetric: . Half the spectrum is redundant, and a complex FFT of real data wastes half its work on zero imaginary parts. A real FFT packs the real samples into complex numbers, transforms those, and untangles the result: about half the arithmetic, returning the independent bins.
Images, volumes and fields are multidimensional, and the multidimensional DFT is separable: it is the composition of one-dimensional DFTs along each axis. A two-dimensional transform of an image is a transform of every row followed by a transform of every column.
Where it is used
Most real data are real-valued and many are arrays, not vectors.
- Images. Two-dimensional FFTs underlie image filtering, deblurring, registration of photographs and phase correlation to align frames.
- Volumes and fields. 3-D FFTs are used in MRI, in seismic processing and in turbulence and weather simulations, where spectral methods solve PDEs on periodic boxes.
- Real signals. The real FFT halves memory and time for audio, sensor and measurement data, which is the common case.
History
James Cooley, Peter Lewis and Peter Welch (1970) described the standard ways to exploit real data: transforming two real signals with one complex FFT, and transforming one real signal of length with a complex FFT of length . Henrik Sorensen, Douglas Jones, Michael Heideman and C. Sidney Burrus (1987) developed dedicated real-valued FFT algorithms. Multidimensional FFTs by rows and columns are as old as the FFT itself; the row-column method’s poor use of cache for large arrays later motivated transposition and vector-radix algorithms.
The idea
The real FFT by half-length packing
Half the spectrum is redundant. If the samples are real, taking the complex conjugate of the DFT sum only changes the sign of the exponent, which is the same as replacing by . So : the upper half of the spectrum is the mirror image of the lower half, conjugated. Only the bins carry information, and a transform that takes real numbers in and gives complex numbers out should be able to do about half the work.
The packing trick. For even , one way to achieve this is to let a complex FFT of half the length carry two real sequences at once, one in its real part and one in its imaginary part. Pack the even- and odd-indexed samples as
and compute the complex DFT of length . Let and be the DFTs of the even and odd samples separately. The DFT is linear, so . That is one complex equation for two complex unknowns, but a second comes from the symmetry just described. and are DFTs of real sequences, so and , and therefore
Adding and subtracting the two equations separates the transforms:
Finally and are exactly the two half-length transforms of the radix-2 FFT, so one more butterfly step combines them into the spectrum of the original signal:
The inverse transform reverses these steps. Odd lengths cannot be packed this way and use a complex transform of the full length.
What it buys in practice. The arithmetic is about halved, but the packing and untangling are extra passes over memory, which the fast vectorised FFT does not hide. On this machine:
Table 8.3. Time of the real FFT against a complex FFT of real data.
| length | complex Fft of real data | RealFft | ratio |
|---|---|---|---|
| 256 | 0.3 µs | 0.4 µs | 1.27 |
| 1024 | 1.3 µs | 1.4 µs | 1.11 |
| 4096 | 8.7 µs | 6.0 µs | 0.69 |
| 65536 | 197.6 µs | 146.6 µs | 0.74 |
| 1048576 | 7.52 ms | 4.94 ms | 0.66 |
RealFft takes 14% to 32% less time than a complex FFT of the real data from about four thousand points up, with the saving growing
with length. For short signals it is about one and a half times slower: the transform itself is so cheap there that the packing
and untangling passes dominate. The untangling loop must be written with care: taking two integer remainders per bin to handle the
wrap-around at and makes RealFft 1.6 to 2.1 times slower than the complex FFT it is meant to replace. The library
handles those two bins separately and computes the bins and together.
Multidimensional transforms
The DFT of a -dimensional array, such as an image () or a volume (), has one frequency index per axis:
The exponential of a sum is a product of exponentials, one per axis. In two dimensions, for example,
The inner sum is a one-dimensional DFT of row ; the outer sum is then a one-dimensional DFT down each column of the result. So no new algorithm is needed: transform every line parallel to axis 1, then every line parallel to axis 2, and so on. The cost is for points.
Each output is the amplitude of a plane wave, a sinusoid with cycles along the first axis
and along the second. A real plane wave in the data transforms to a pair of peaks, at
and its mirror image. fftshift moves the zero frequency from the corner of the
array to its centre for display, as is conventional for images.
Helpers: frequencies, fast lengths and N-D transforms
A few small functions, following scipy.fft, make spectra easier to use.
- Frequencies of the bins. Bin of an -point DFT of samples spaced apart is the frequency . Bins above are
the negative frequencies .
fftfreq(n, d)lists them in the order the FFT returns them, , andrfftfreqlists the non-negative ones of a real FFT.ifftshiftundoesfftshift; the two differ for odd lengths. - Fast lengths. The FFT is fastest when has only small prime factors. Bluestein’s algorithm handles any length, at about three
times the cost. Padding a signal to
next_fast_len(n)is usually much cheaper: the next length whose factors are 2, 3 and 5 (for real data, matching SciPy) or also 7 and 11 (for complex data). It is found by a depth-first search over the products of prime powers. For example, 1021 is prime, andnext_fast_len(1021)is . - N-dimensional real transforms.
rfftnapplies a real FFT along the last axis, keeping bins, and complex FFTs along the others. It returns the non-redundant half offftn.irfftninverts it, given the output shape, since a last axis of length or gives the same number of bins when is even. - N-dimensional DCTs and DSTs. The cosine and sine transforms are separable too, so
dctnanddstnapply the one-dimensional transforms of the DCT entry along every axis in turn. The 2-D DCT-II is the transform of JPEG blocks.
Algorithm
RealFft::forward, for a real input of even length .
- Pack. Form the complex sequence for .
- Transform with a complex FFT of length .
- The two unpaired bins. and are the real and imaginary parts of , so and , both real.
- Untangle the rest in pairs. For each from 1 to , compute and from and , and set . The same two values and also give bin , so both are produced in one pass of the loop.
The output is the bins . The inverse runs the steps backwards. An odd length is transformed by a complex FFT of the full length, of which the first bins are returned.
fftn, for an array with axes. For each axis in turn:
- plan a one-dimensional
Fftfor the length of that axis; - for every line of the array parallel to the axis, copy the line into a buffer, transform it, and copy it back.
A line along the last axis is contiguous in memory; a line along another axis is read with a stride, which is why it is copied to a buffer first.
Implementation
/// The bins `X_0 ..= X_{n/2}` of the unscaled DFT `X_k = Σ x_m e^{-2πi km/n}`.
pub fn forward(&mut self, x: &[f64]) -> Result<Vec<C64>, ErrorsJSL> {
if x.len() != self.n {
return Err(ErrorsJSL::IncompatibleArraySizes((x.len(), self.n)));
}
if !self.n.is_multiple_of(2) {
let full = self.forward.execute(&x.iter().map(|&v| C64::new(v, 0.0)).collect::<Vec<_>>())?;
return Ok(full[..self.spectrum_len()].to_vec());
}
let m = self.n / 2;
let packed: Vec<C64> = (0..m).map(|j| C64::new(x[2 * j], x[2 * j + 1])).collect();
let z = self.forward.execute(&packed)?;
// X_k = ½[(Z_k + conj Z_{m−k}) − i w_k (Z_k − conj Z_{m−k})], w_k = e^{−2πik/n}. The bins k and
// m − k use the same two values of Z and are computed together; only k = 0 and k = m wrap
// around (Z_m = Z_0). (An earlier version took two integer moduli per bin to handle the
// wrap-around, which cost more than the half-length FFT itself.)
let mut out = vec![C64::new(0.0, 0.0); m + 1];
out[0] = C64::new(z[0].re + z[0].im, 0.0);
out[m] = C64::new(z[0].re - z[0].im, 0.0);
for k in 1..=m / 2 {
let (a, b) = (z[k], z[m - k]);
let (sum, difference) = (a + b.conj(), a - b.conj());
let wd = self.twiddles[k] * difference;
out[k] = C64::new(0.5 * (sum.re + wd.im), 0.5 * (sum.im - wd.re));
let (sum, difference) = (b + a.conj(), b - a.conj());
let wd = self.twiddles[m - k] * difference;
out[m - k] = C64::new(0.5 * (sum.re + wd.im), 0.5 * (sum.im - wd.re));
}
Ok(out)
}
/// Transforms every 1D lane of `data` along `axis` in place. Inverse transforms are scaled by
/// `1 / len`, so a forward and inverse pass along the same axis is the identity.
pub fn fft_axis(data: &mut ArrayD<C64>, axis: usize, direction: FftDirection) -> Result<(), ErrorsJSL> {
if axis >= data.ndim() {
return Err(ErrorsJSL::InvalidInputRange("The axis is out of range."));
}
let len = data.len_of(Axis(axis));
if len == 0 {
return Ok(());
}
let scale = match direction {
FftDirection::Forward => FftScaleFactor::None,
FftDirection::Inverse => FftScaleFactor::N,
};
let mut fft = Fft::with_plan(len, scale, direction, FftOrdering::Standard)?;
for mut lane in data.lanes_mut(Axis(axis)) {
let out = fft.execute(&lane.to_vec())?;
lane.iter_mut().zip(out).for_each(|(v, o)| *v = o);
}
Ok(())
}
/// The smallest length `≥ target` whose prime factors are all small, which FFTs handle fastest
/// (SciPy's `next_fast_len`): 2, 3 and 5 for real transforms (`real = true`), and also 7 and 11
/// for complex ones. Found by enumerating the products of powers of the allowed primes.
pub fn next_fast_len(target: usize, real: bool) -> usize {
if target <= 1 {
return target.max(1);
}
let primes: &[usize] = if real { &[2, 3, 5] } else { &[2, 3, 5, 7, 11] };
let mut best = usize::MAX;
// Depth-first over exponents: each partial product that reaches the target is a candidate.
fn search(product: usize, primes: &[usize], target: usize, best: &mut usize) {
if product >= target {
*best = (*best).min(product);
return;
}
let Some((&p, rest)) = primes.split_first() else { return };
let mut q = product;
loop {
search(q, rest, target, best);
if q >= target || q > usize::MAX / p {
break;
}
q *= p;
}
}
search(1, primes, target, &mut best);
best
}
/// The N-dimensional DFT of real data (SciPy's `rfftn`): a real FFT along the last axis, keeping
/// the `⌊n/2⌋ + 1` non-negative frequencies, then complex FFTs along the other axes. The result
/// has the input's shape with the last axis shortened.
pub fn rfftn(data: &ArrayD<f64>) -> Result<ArrayD<C64>, ErrorsJSL> {
let nd = data.ndim();
if nd == 0 {
return Err(ErrorsJSL::InvalidInputRange("The array must have at least one axis."));
}
let last = data.len_of(Axis(nd - 1));
if last == 0 {
return Err(ErrorsJSL::InvalidInputRange("The last axis must not be empty."));
}
let mut shape = data.shape().to_vec();
shape[nd - 1] = last / 2 + 1;
let mut out = ArrayD::<C64>::zeros(IxDyn(&shape));
for (lane, mut target) in data.lanes(Axis(nd - 1)).into_iter().zip(out.lanes_mut(Axis(nd - 1))) {
let spectrum = rfft(&lane.to_vec())?;
target.iter_mut().zip(spectrum).for_each(|(t, s)| *t = s);
}
for axis in 0..nd - 1 {
fft_axis(&mut out, axis, FftDirection::Forward)?;
}
Ok(out)
}
RealFft::forwardis unscaled;RealFft::inversedivides by , so the pair round-trips exactly.- The multidimensional transforms work on
ndarrayarrays of complex numbers and accept any lengths along each axis.
In practice
//! Real-input and two-dimensional FFTs.
//!
//! Run with `cargo run -p lib_jsl_ffts --example fft_real_and_2d`.
use lib_jsl_ffts::{fft2, ifft2, irfft, rfft};
use ndarray::Array2;
use num_complex::Complex;
fn main() {
// A real signal: only the n/2 + 1 non-negative frequencies are returned.
let x: Vec<f64> = (0..16).map(|k| (k as f64 * 0.8).sin() + 0.2).collect();
let spectrum = rfft(&x).unwrap();
println!("{} bins for {} samples; DC = {:.4} (16 × mean)", spectrum.len(), x.len(), spectrum[0].re);
let back = irfft(&spectrum, x.len()).unwrap();
println!("round trip error {:.1e}", back.iter().zip(&x).map(|(a, b)| (a - b).abs()).fold(0.0, f64::max));
// A 2D transform: a plane wave cos(2π(3i/8 + 2j/16)) has two spectral peaks.
let image = Array2::from_shape_fn((8, 16), |(i, j)| Complex::new((2.0 * std::f64::consts::PI * (3.0 * i as f64 / 8.0 + 2.0 * j as f64 / 16.0)).cos(), 0.0));
let f = fft2(&image).unwrap();
let peaks: Vec<(usize, usize)> = f.indexed_iter().filter(|(_, v)| v.norm() > 1.0).map(|(ij, _)| ij).collect();
println!("2D peaks at {peaks:?} with magnitude {:.1}", f[[3, 2]].norm());
let restored = ifft2(&f).unwrap();
println!("2D round trip error {:.1e}", (&restored - &image).iter().map(|v| v.norm()).fold(0.0, f64::max));
}
The helpers are compared with SciPy 1.17.1 (references from book/generator/data/make_utilities_refs.py):
Table 8.4. The FFT helpers against SciPy.
| computation (SciPy reference) | largest difference (relative) |
|---|---|
fftfreq and rfftfreq, n = 7 | 0 |
fftfreq and rfftfreq, n = 8 | 0 |
next_fast_len (real) of 7, 13, 97, …, 999983: 8, 15, 100, 1000, 1024, 4320, 65610, 1000000 | 0 |
next_fast_len (complex) of 7, 13, 97, …, 999983: 7, 14, 98, 1000, 1024, 4116, 65610, 1000000 | 0 |
rfftn, 4 × 5 × 6 (round trip through irfftn: 1e-15) | 5e-16 |
rfftn, 3 × 4 × 7 (round trip through irfftn: 2e-15) | 5e-16 |
dctn, types I–IV, both normalisations, 5 × 6 | 5e-16 |
dstn, types I–IV, both normalisations, 5 × 6 | 7e-16 |
Strengths
- Real transforms return only the non-redundant half spectrum and save time for long signals.
- Any number of dimensions and any lengths, through one-dimensional engines.
Weaknesses
- The real FFT’s passes limit its gain to between about a seventh and a third of the time at the lengths measured, and turn it into a loss for short signals; a dedicated real-data algorithm would do better.
- The row-column method copies every line; transposition-based or vector-radix algorithms make better use of cache for large arrays.
Exercises
- Prove that the DFT of a real sequence is conjugate symmetric.
- Derive and from and verify the untangling formula for .
- Use one complex FFT to transform two real signals at once, and separate the results.
- Show that the two-dimensional DFT of a separable array is the outer product of the one-dimensional DFTs.
- Compute the 2D power spectrum of an image with a periodic stripe pattern and locate the stripe frequency.
- Why is
next_fast_len(97, real = false)equal to 98 butnext_fast_len(97, real = true)equal to 100?
Hints and answers
- For real , .
- With and , and are the transforms of the even and odd samples, and . For () check each directly.
- Form and transform; then and .
- .
- A stripe pattern is a sinusoid along one direction, so its power spectrum has two symmetric peaks at the stripe frequency; read the position of the peak off the bin indices and convert with the image size.
- is allowed when 7 is a permitted factor (complex transforms); with factors 2, 3 and 5 only, the next candidates are (no), (no) and .
Further reading
- J. W. Cooley, P. A. W. Lewis and P. D. Welch, “The fast Fourier transform algorithm: programming considerations in the calculation of sine, cosine and Laplace transforms”, Journal of Sound and Vibration 12 (1970) 315–337.
- H. V. Sorensen, D. L. Jones, M. T. Heideman and C. S. Burrus, “Real-valued fast Fourier transform algorithms”, IEEE Transactions on Acoustics, Speech, and Signal Processing 35 (1987) 849–863.
- W. H. Press et al., Numerical Recipes, 3rd ed., Cambridge University Press, 2007, §12.3–12.5.