评价此页

torch.fft.fftshift#

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

重新排序由 fftn() 提供的 n 维 FFT 数据,使负频率项在前。

这会执行 n 维数据的周期性移位,将原点 (0, ..., 0) 移动到张量的中心。具体来说,是在每个选定的维度上移动到 input.shape[dim] // 2 的位置。

注意

按照惯例,FFT 返回正频率项在前,然后是反向排列的负频率项,因此在 Python 中 f[-i] 对于所有 0<in/20 < i \leq n/2 都表示负频率项。 fftshift() 将所有频率重新排列为从负到正的升序,零频率项位于中心。

注意

对于偶数长度,奈奎斯特频率 f[n/2] 可以被视为负频率或正频率。 fftshift() 始终将奈奎斯特项放在 0 索引处。这与 fftfreq() 使用的约定相同。

参数
  • input (Tensor) – FFT 顺序的张量

  • dim (int, Tuple[int], optional) – 要重新排列的维度。只有在这里指定的维度才会被重新排列,其他维度将保持其原始顺序。默认值:input 的所有维度。

示例

>>> f = torch.fft.fftfreq(4)
>>> f
tensor([ 0.0000,  0.2500, -0.5000, -0.2500])
>>> torch.fft.fftshift(f)
tensor([-0.5000, -0.2500,  0.0000,  0.2500])

同时注意,位于 f[2] 的奈奎斯特频率项已移至张量开头。

这同样适用于多维变换。

>>> x = torch.fft.fftfreq(5, d=1/5) + 0.1 * torch.fft.fftfreq(5, d=1/5).unsqueeze(1)
>>> x
tensor([[ 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() 对于空间数据也很有用。如果我们的数据定义在中心网格上([-(N//2), (N-1)//2]),那么我们可以使用定义在非中心网格([0, N))上的标准 FFT,通过先应用 ifftshift() 来实现。

>>> x_centered = torch.arange(-5, 5)
>>> x_uncentered = torch.fft.ifftshift(x_centered)
>>> fft_uncentered = torch.fft.fft(x_uncentered)

类似地,我们可以通过应用 fftshift() 将频域分量转换为中心约定。

>>> fft_centered = torch.fft.fftshift(fft_uncentered)

逆变换,从中心傅里叶空间回到中心空间数据,可以通过按相反的顺序应用逆移位来执行。

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