torch.fft.fftshift#
- torch.fft.fftshift(input,dim=None)→Tensor#
Reorders n-dimensional FFT data, as provided by
fftn(), to havenegative frequency terms first.This performs a periodic shift of n-dimensional data such that the origin
(0,...,0)is moved to the center of the tensor. Specifically, toinput.shape[dim]//2in each selected dimension.Note
By convention, the FFT returns positive frequency terms first, followed bythe negative frequencies in reverse order, so that
f[-i]for all in Python gives the negative frequency terms.fftshift()rearranges all frequencies into ascending orderfrom negative to positive with the zero-frequency term in the center.Note
For even lengths, the Nyquist frequency at
f[n/2]can be thought of aseither negative or positive.fftshift()always puts theNyquist term at the 0-index. This is the same convention used byfftfreq().- Parameters
Example
>>>f=torch.fft.fftfreq(4)>>>ftensor([ 0.0000, 0.2500, -0.5000, -0.2500])
>>>torch.fft.fftshift(f)tensor([-0.5000, -0.2500, 0.0000, 0.2500])
Also notice that the Nyquist frequency term at
f[2]was moved to thebeginning of the tensor.This also works for multi-dimensional transforms:
>>>x=torch.fft.fftfreq(5,d=1/5)+0.1*torch.fft.fftfreq(5,d=1/5).unsqueeze(1)>>>xtensor([[ 0.0000, 1.0000, 2.0000, -2.0000, -1.0000], [ 0.1000, 1.1000, 2.1000, -1.9000, -0.9000], [ 0.2000, 1.2000, 2.2000, -1.8000, -0.8000], [-0.2000, 0.8000, 1.8000, -2.2000, -1.2000], [-0.1000, 0.9000, 1.9000, -2.1000, -1.1000]])
>>>torch.fft.fftshift(x)tensor([[-2.2000, -1.2000, -0.2000, 0.8000, 1.8000], [-2.1000, -1.1000, -0.1000, 0.9000, 1.9000], [-2.0000, -1.0000, 0.0000, 1.0000, 2.0000], [-1.9000, -0.9000, 0.1000, 1.1000, 2.1000], [-1.8000, -0.8000, 0.2000, 1.2000, 2.2000]])
fftshift()can also be useful for spatial data. If ourdata is defined on a centered grid ([-(N//2),(N-1)//2]) then we canuse the standard FFT defined on an uncentered grid ([0,N)) by firstapplying anifftshift().>>>x_centered=torch.arange(-5,5)>>>x_uncentered=torch.fft.ifftshift(x_centered)>>>fft_uncentered=torch.fft.fft(x_uncentered)
Similarly, we can convert the frequency domain components to centeredconvention by applying
fftshift().>>>fft_centered=torch.fft.fftshift(fft_uncentered)
The inverse transform, from centered Fourier space back to centered spatialdata, can be performed by applying the inverse shifts in reverse order:
>>>x_centered_2=torch.fft.fftshift(torch.fft.ifft(torch.fft.ifftshift(fft_centered)))>>>torch.testing.assert_close(x_centered.to(torch.complex64),x_centered_2,check_stride=False)