Rate this Page

torch.fft.fftshift#

torch.fft.fftshift(input,dim=None)Tensor#

Reorders n-dimensional FFT data, as provided byfftn(), 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]//2 in each selected dimension.

Note

By convention, the FFT returns positive frequency terms first, followed bythe negative frequencies in reverse order, so thatf[-i] for all0<in/20 < i \leq n/2 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 atf[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
  • input (Tensor) – the tensor in FFT order

  • dim (int,Tuple[int],optional) – The dimensions to rearrange.Only dimensions specified here will be rearranged, any other dimensionswill be left in their original order.Default: All dimensions ofinput.

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 atf[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 applyingfftshift().

>>>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)