fft.py 69.2 KB
Newer Older
Z
zhiboniu 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

15
from typing import Sequence
16

17
import numpy as np
18

19
import paddle
20

姜永久 已提交
21
from . import _C_ops
22 23
from .fluid.data_feeder import check_variable_and_dtype
from .fluid.layer_helper import LayerHelper
24
from .framework import in_dynamic_mode
25 26
from .tensor.attribute import is_floating_point, is_integer
from .tensor.creation import _complex_to_real_dtype, _real_to_complex_dtype
27 28

__all__ = [
Z
zhiboniu 已提交
29 30 31 32 33 34
    'fft',
    'ifft',
    'rfft',
    'irfft',
    'hfft',
    'ihfft',
35 36 37 38 39
    'fft2',
    'ifft2',
    'rfft2',
    'irfft2',
    'hfft2',
Z
zhiboniu 已提交
40
    'ihfft2',
41 42 43 44 45
    'fftn',
    'ifftn',
    'rfftn',
    'irfftn',
    'hfftn',
Z
zhiboniu 已提交
46 47 48 49
    'ihfftn',
    'fftfreq',
    'rfftfreq',
    'fftshift',
50
    'ifftshift',
Z
zhiboniu 已提交
51
]
52 53 54 55 56


def _check_normalization(norm):
    if norm not in ['forward', 'backward', 'ortho']:
        raise ValueError(
57 58 59 60
            "Unexpected norm: {}. Norm should be forward, backward or ortho".format(
                norm
            )
        )
61 62 63 64 65


def _check_fft_n(n):
    if not isinstance(n, int):
        raise ValueError(
66
            f"Invalid FFT argument n({n}), it shoule be an integer."
67
        )
68
    if n <= 0:
69
        raise ValueError(f"Invalid FFT argument n({n}), it should be positive.")
70 71 72 73 74 75


def _check_fft_shape(x, s):
    ndim = x.ndim
    if not isinstance(s, Sequence):
        raise ValueError(
76 77
            "Invaid FFT argument s({}), it should be a sequence of integers."
        )
78 79 80 81

    if len(s) > ndim:
        raise ValueError(
            "Length of FFT argument s should not be larger than the rank of input. "
82 83
            "Received s: {}, rank of x: {}".format(s, ndim)
        )
84 85
    for size in s:
        if not isinstance(size, int) or size <= 0:
86
            raise ValueError(f"FFT sizes {s} contains invalid value ({size})")
87 88 89 90 91


def _check_fft_axis(x, axis):
    ndim = x.ndim
    if not isinstance(axis, int):
92
        raise ValueError(f"Invalid FFT axis ({axis}), it shoule be an integer.")
93 94 95
    if axis < -ndim or axis >= ndim:
        raise ValueError(
            "Invalid FFT axis ({}), it should be in range [-{}, {})".format(
96 97 98
                axis, ndim, ndim
            )
        )
99 100 101 102 103 104


def _check_fft_axes(x, axes):
    ndim = x.ndim
    if not isinstance(axes, Sequence):
        raise ValueError(
105 106 107 108
            "Invalid FFT axes ({}), it should be a sequence of integers.".format(
                axes
            )
        )
109 110 111
    if len(axes) > ndim:
        raise ValueError(
            "Length of fft axes should not be larger than the rank of input. "
112 113
            "Received, len of axes: {}, rank of x: {}".format(len(axes), ndim)
        )
114 115 116
    for axis in axes:
        if not isinstance(axis, int) or axis < -ndim or axis >= ndim:
            raise ValueError(
117 118 119 120
                "FFT axes {} contains invalid value ({}), it should be in range [-{}, {})".format(
                    axes, axis, ndim, ndim
                )
            )
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141


def _resize_fft_input(x, s, axes):
    if len(s) != len(axes):
        raise ValueError("length of `s` should equals length of `axes`.")
    shape = x.shape
    ndim = x.ndim

    axes_to_pad = []
    paddings = []
    axes_to_slice = []
    slices = []
    for i, axis in enumerate(axes):
        if shape[axis] < s[i]:
            axes_to_pad.append(axis)
            paddings.append(s[i] - shape[axis])
        elif shape[axis] > s[i]:
            axes_to_slice.append(axis)
            slices.append((0, s[i]))

    if axes_to_slice:
142 143 144 145 146 147
        x = paddle.slice(
            x,
            axes_to_slice,
            starts=[item[0] for item in slices],
            ends=[item[1] for item in slices],
        )
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
    if axes_to_pad:
        padding_widths = [0] * (2 * ndim)
        for axis, pad in zip(axes_to_pad, paddings):
            padding_widths[2 * axis + 1] = pad
        x = paddle.nn.functional.pad(x, padding_widths)
    return x


def _normalize_axes(x, axes):
    ndim = x.ndim
    return [item if item >= 0 else (item + ndim) for item in axes]


def _check_at_least_ndim(x, rank):
    if x.ndim < rank:
163
        raise ValueError(f"The rank of the input ({x.ndim}) should >= {rank}")
164 165 166 167 168 169 170


# public APIs 1d
def fft(x, n=None, axis=-1, norm="backward", name=None):
    """
    Calculate one-dimensional discrete Fourier transform.

171
    This function uses the efficient fast Fourier transform (FFT) algorithm [1] to
172 173 174 175
    calculate the 1-D * n * point discrete Fourier transform (DFT).

    Args:
        x (Tensor): The input data. It's a Tensor type. It's a complex.
176 177 178
        n (int, optional): The length of the output transform axis. If `n` is less than
            the length input, the input will be cropped. If larger, the input is filled
            with zeros. If `n` is not given, the input length along the axis specified
179
            by `axis` is used.
180 181
        axis (int, optional): Axis used to calculate FFT. If not specified, the last axis
            is used by default.
182
        norm (str, optional): Indicates which direction to scale the `forward` or `backward` transform
183
            pair and what normalization factor to use. The parameter value must be one
184
            of "forward" or "backward" or "ortho". Default is "backward", meaning no normalization on
185 186
            the forward transforms and scaling by ``1/n`` on the `ifft`. "forward" instead applies
            the ``1/n`` factor on the forward tranform. For ``norm="ortho"``, both directions are
187
            scaled by ``1/sqrt(n)``.
188
        name (str, optional): The default value is None.  Normally there is no need for user to set
189 190 191
            this property. For more information, please refer to :ref:`api_guide_Name`.

    Returns:
192
        complex tensor. The truncated or zero-padded input, transformed along the axis indicated
193
        by `axis`, or the last one if `axis` is not specified.
194

195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
    Examples:

        .. code-block:: python

            import numpy as np
            import paddle

            x = np.exp(3j * np.pi * np.arange(7) / 7)
            xp = paddle.to_tensor(x)
            fft_xp = paddle.fft.fft(xp).numpy()
            print(fft_xp)
            #  [1.+1.25396034e+00j 1.+4.38128627e+00j 1.-4.38128627e+00j
            #   1.-1.25396034e+00j 1.-4.81574619e-01j 1.+8.88178420e-16j
            #   1.+4.81574619e-01j]


    """
212
    if is_integer(x) or is_floating_point(x):
213 214 215
        return fft_r2c(
            x, n, axis, norm, forward=True, onesided=False, name=name
        )
216 217 218 219 220 221 222 223
    else:
        return fft_c2c(x, n, axis, norm, forward=True, name=name)


def ifft(x, n=None, axis=-1, norm="backward", name=None):
    """
    Compute the 1-D inverse discrete Fourier Transform.

224
    This function computes the inverse of the 1-D *n*-point discrete Fourier transform
225 226 227 228 229 230 231 232 233 234 235 236
    computed by `fft`.  In other words, ``ifft(fft(x)) == x`` to within numerical accuracy.

    The input should be ordered in the same way as is returned by `fft`,
    i.e.,

    * ``x[0]`` should contain the zero frequency term,
    * ``x[1:n//2]`` should contain the positive-frequency terms,
    * ``x[n//2 + 1:]`` should contain the negative-frequency terms, in
      increasing order starting from the most negative frequency.

    For an even number of input points, ``x[n//2]`` represents the sum of
    the values at the positive and negative Nyquist frequencies, as the two
237
    are aliased together.
238 239 240

    Args:
        x (Tensor): The input data. It's a Tensor type. It's a complex.
241 242 243
        n (int, optional): The length of the output transform axis. If `n` is less than
            the length input, the input will be cropped. If larger, the input is filled
            with zeros. If `n` is not given, the input length along the axis specified
244
            by `axis` is used.
245 246
        axis (int, optional): Axis used to calculate FFT. If not specified, the last axis
            is used by default.
247
        norm (str, optional): Indicates which direction to scale the `forward` or `backward` transform
248
            pair and what normalization factor to use. The parameter value must be one
249
            of "forward" or "backward" or "ortho". Default is "backward", meaning no normalization on
250 251
            the forward transforms and scaling by ``1/n`` on the `ifft`. "forward" instead applies
            the ``1/n`` factor on the forward tranform. For ``norm="ortho"``, both directions are
252
            scaled by ``1/sqrt(n)``.
253
        name (str, optional): The default value is None.  Normally there is no need for user to set
254
            this property. For more information, please refer to :ref:`api_guide_Name`.
255

256
    Returns:
257
        complex tensor. The truncated or zero-padded input, transformed along the axis indicated
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
        by `axis`, or the last one if `axis` is not specified.

    Examples:

        .. code-block:: python

            import numpy as np
            import paddle

            x = np.exp(3j * np.pi * np.arange(7) / 7)
            xp = paddle.to_tensor(x)
            ifft_xp = paddle.fft.ifft(xp).numpy()
            print(ifft_xp)
            #  [0.14285714+1.79137191e-01j 0.14285714+6.87963741e-02j
            #   0.14285714+1.26882631e-16j 0.14285714-6.87963741e-02j
            #   0.14285714-1.79137191e-01j 0.14285714-6.25898038e-01j
            #   0.14285714+6.25898038e-01j]

    """
277
    if is_integer(x) or is_floating_point(x):
278 279 280
        return fft_r2c(
            x, n, axis, norm, forward=False, onesided=False, name=name
        )
281 282 283 284 285 286 287 288 289 290 291 292 293
    else:
        return fft_c2c(x, n, axis, norm, forward=False, name=name)


def rfft(x, n=None, axis=-1, norm="backward", name=None):
    """
    The one dimensional FFT for real input.

    This function computes the one dimensional *n*-point discrete Fourier
    Transform (DFT) of a real-valued tensor by means of an efficient algorithm
    called the Fast Fourier Transform (FFT).

    When the DFT is computed for purely real input, the output is
294 295
    Hermitian-symmetric. This function does not compute the negative frequency
    terms, and the length of the transformed axis of the output is therefore
296 297 298
    ``n//2 + 1``.

    Args:
299 300 301 302 303
        x(Tensor) : Real-valued input tensor
        n(int, optional): Number of points along transformation axis in the
            input to use. If `n` is smaller than the length of the input, the
            input is cropped. If it is larger, the input is padded with zeros.
            If `n` is not given, the length of the input along the axis
304
            specified by `axis` is used.
305
        axis(int, optional): Axis over which to compute the FFT. Default value
306
            is last axis.
307 308 309
        norm(str, optional) : Normalization mode, indicates which direction of
            the forward/backward  pair of transforms is scaled and with what
            normalization factor. Include {"backward", "ortho", "forward"},
310
            default value is "backward".
311

312 313 314
                - "backward": The factor of forward direction and backward direction are ``1`` and ``1/n`` respectively;
                - "forward": The factor of forward direction and backward direction are ``1/n`` and ``1`` respectively;
                - "ortho": The factor of forward direction and backword direction are both ``1/sqrt(n)``.
315

316
            Where ``n`` is the multiplication of each element in  ``s`` .
317 318 319
        name(str, optional): The default value is None.  Normally there is no
            need for user to set this property. For more information, please
            refer to :ref:`api_guide_Name` .
320 321 322 323 324

    Returns:
        out(Tensor) : complex tensor

    Examples:
325

326
    .. code-block:: python
327

328 329 330 331 332 333 334 335 336 337 338 339 340 341
        import paddle

        x = paddle.to_tensor([0.0, 1.0, 0.0, 0.0])
        print(paddle.fft.rfft(x))
        # Tensor(shape=[3], dtype=complex64, place=CUDAPlace(0), stop_gradient=True,
        #        [ (1+0j), -1j    , (-1+0j)])
    """
    return fft_r2c(x, n, axis, norm, forward=True, onesided=True, name=name)


def irfft(x, n=None, axis=-1, norm="backward", name=None):
    """
    Computes the inverse of `rfft`.

342 343
    This function calculates the inverse of the one-dimensional *n* point discrete
    Fourier transform of the actual input calculated by "rfft". In other words,
344 345
    ``irfft(rfft(a),len(a)) == a`` is within the numerical accuracy range.

346 347 348 349
    The input shall be in the form of "rfft", i.e. the actual zero frequency term,
    followed by the complex positive frequency term, in the order of increasing frequency.
    Because the discrete Fourier transform of the actual input is Hermite symmetric,
    the negative frequency term is regarded as the complex conjugate term of the corresponding
350 351 352 353 354
    positive frequency term.

    Args:
        x (Tensor): The input data. It's a Tensor type. It's a complex.
        n (int, optional): The length of the output transform axis. For `n` output
355 356 357
            points, ``n//2 + 1``input points are necessary. If the length of the input tensor is greater
            than `n`, it will be cropped, if it is shorter than this, fill in zero. If `n` is not given,
            it is considered to be ``2 * (k-1)``, where ``k`` is the length of the input axis specified
358
            along the ` axis'.
359 360
        axis (int, optional): Axis used to calculate FFT. If not specified, the last axis
            is used by default.
361
        norm (str, optional): Indicates which direction to scale the `forward` or `backward` transform
362
            pair and what normalization factor to use. The parameter value must be one
363
            of "forward" or "backward" or "ortho". Default is "backward".
364 365
        name (str, optional): The default value is None.  Normally there is no need for user to set
            this property. For more information, please refer to :ref:`api_guide_Name` .
366 367

    Returns:
368 369 370
        Real tensor. Truncated or zero fill input for the transformation along the axis indicated by
        `axis`, or the last input if `axis` is not specified. The length of the conversion axis
        is `n`, or ``2 * k-2``, if `k` is None, where `k` is the length of the input conversion axis.
371 372
        If the output is an odd number, you need to specify the value of 'n', such as ``2 * k-1``
        in some cases.
373

374 375 376 377 378 379
    Examples:

        .. code-block:: python

            import paddle

380 381 382 383 384
            x = paddle.to_tensor([1, -1j, -1])
            irfft_x = paddle.fft.irfft(x)
            print(irfft_x)
            # Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
            #        [0., 1., 0., 0.])
385 386 387 388 389 390 391 392 393 394 395 396
    """
    return fft_c2r(x, n, axis, norm, forward=False, name=name)


def hfft(x, n=None, axis=-1, norm="backward", name=None):
    """
    Compute the FFT of a signal that has Hermitian symmetry, a real
    spectrum.

    Args:
        x (Tensor): The input data. It's a Tensor type. It's a complex.
        n (int, optional): The length of the output transform axis. For `n` output
397 398 399
            points, ``n//2 + 1`` input points are necessary. If the length of the input tensor is greater
            than `n`, it will be cropped, if it is shorter than this, fill in zero. If `n` is not given,
            it is considered to be ``2 * (k-1)``, where ``k`` is the length of the input axis specified
400
            along the ` axis'.
401 402
        axis (int,optional): Axis used to calculate FFT. If not specified, the last axis
            is used by default.
403
        norm (str, optional): Indicates which direction to scale the `forward` or `backward` transform
404
            pair and what normalization factor to use. The parameter value must be one
405
            of "forward" or "backward" or "ortho". Default is "backward".
406 407
        name (str, optional): The default value is None.  Normally there is no need for user to set
            this property. For more information, please refer to :ref:`api_guide_Name` .
408 409

    Returns:
410 411 412 413
        Real tensor. Truncated or zero fill input for the transformation along the axis indicated by
        `axis`, or the last input if `axis` is not specified. The length of the conversion axis
        is `n`, or ``2 * k-2``, if `k` is None, where `k` is the length of the input conversion axis.
        If the output is an odd number, you need to specify the value of 'n', such as ``2 * k-1`` in
414
        some cases.
415

416 417 418 419 420 421
    Examples:

        .. code-block:: python

            import paddle

422 423 424 425 426
            x = paddle.to_tensor([1, -1j, -1])
            hfft_x = paddle.fft.hfft(x)
            print(hfft_x)
            # Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
            #        [0., 0., 0., 4.])
427 428 429 430 431 432 433 434 435
    """

    return fft_c2r(x, n, axis, norm, forward=True, name=name)


def ihfft(x, n=None, axis=-1, norm="backward", name=None):
    """
    The inverse FFT of a signal that has Hermitian symmetry.

436 437
    This function computes the one dimensional *n*-point inverse FFT of a signal
    that has Hermitian symmetry by means of an efficient algorithm called
438 439 440
    the Fast Fourier Transform (FFT).

    When the DFT is computed for purely real input, the output is
441 442
    Hermitian-symmetric. This function does not compute the negative frequency
    terms, and the length of the transformed axis of the output is therefore
443 444 445 446
    ``n//2 + 1``.

    Args:
        x(Tensor): Input tensor.
447 448 449 450
        n(int, optional): The number of points along transformation axis in the
            input to use.  If `n` is smaller than the length of the input, the
            input is cropped.  If it is larger, the input is padded with zeros.
            If `n` is not given, the length of the input along the axis
451 452 453
            specified by `axis` is used.
        axis(int, optional) : Axis over which to compute the inverse FFT. If not
            given, the last axis is used.
454 455 456
        norm(str, optional) : Normalization mode, indicates which direction of
            the forward/backward pair of transforms is scaled and with what
            normalization factor. Include {"backward", "ortho", "forward"},
457
            default value is "backward".
458 459 460
        name(str, optional): The default value is None.  Normally there is no
            need for user to set this property. For more information, please
            refer to :ref:`api_guide_Name` .
461 462 463 464 465

    Returns:
        out(Tensor) : complex tensor.

    Examples:
466

467
    .. code-block:: python
468 469

        import paddle
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487

        spectrum = paddle.to_tensor([10.0, -5.0, 0.0, -1.0, 0.0, -5.0])
        print(paddle.fft.ifft(spectrum))
        # Tensor(shape=[6], dtype=complex64, place=CUDAPlace(0), stop_gradient=True,
        #       [(-0.1666666716337204+0j),  (1-1.9868215517249155e-08j), (2.3333334922790527-1.9868215517249155e-08j),  (3.5+0j), (2.3333334922790527+1.9868215517249155e-08j),  (1+1.9868215517249155e-08j)])
        print(paddle.fft.ihfft(spectrum))
        #  Tensor(shape = [4], dtype = complex64, place = CUDAPlace(0), stop_gradient = True,
        #         [(-0.1666666716337204+0j),  (1-1.9868215517249155e-08j), (2.3333334922790527-1.9868215517249155e-08j),  (3.5+0j)])

    """
    return fft_r2c(x, n, axis, norm, forward=False, onesided=True, name=name)


# public APIs nd
def fftn(x, s=None, axes=None, norm="backward", name=None):
    """
    Compute the N-D discrete Fourier Transform.

488
    This function calculates the n-D discrete Fourier transform on any number of axes
489 490 491 492 493 494 495 496 497 498 499 500
    in the M-D array by fast Fourier transform (FFT).

    Args:
        x (Tensor): The input data. It's a Tensor type. It's a complex.
        s (sequence of ints, optional): Shape (length of each transformed axis) of the output
            (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).
            This corresponds to ``n`` for ``fft(x, n)``.
            Along any axis, if the given shape is smaller than that of the input,
            the input is cropped. If it is larger, the input is padded with zeros.
            if `s` is not given, the shape of the input along the axes specified
            by `axes` is used.
        axes (sequence of ints, optional): Axes used to calculate FFT. If not given, the last ``len(s)``
501
            axes are used, or all axes if `s` is also not specified.
502
        norm (str, optional): Indicates which direction to scale the `forward` or `backward` transform
503
            pair and what normalization factor to use. The parameter value must be one
504
            of "forward" or "backward" or "ortho". Default is "backward", meaning no normalization on
505 506
            the forward transforms and scaling by ``1/n`` on the `ifft`. "forward" instead applies
            the ``1/n`` factor on the forward tranform. For ``norm="ortho"``, both directions are
507
            scaled by ``1/sqrt(n)``.
508
        name (str, optional): The default value is None.  Normally there is no need for user to set
509 510 511
            this property. For more information, please refer to :ref:`api_guide_Name`.

    Returns:
512
        complex tensor. The truncated or zero-padded input, transformed along the axes indicated by
513
        `axes`, or by a combination of `s` and `x`, as explained in the parameters section above.
514

515 516 517 518 519 520
    Examples:

        .. code-block:: python

            import paddle

521 522 523 524
            arr = paddle.arange(4, dtype="float64")
            x = paddle.meshgrid(arr, arr, arr)[1]

            fftn_xp = paddle.fft.fftn(x, axes=(1, 2))
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
            print(fftn_xp)
            # Tensor(shape=[4, 4, 4], dtype=complex128, place=Place(gpu:0), stop_gradient=True,
            #        [[[(24+0j),  0j    ,  0j    ,  -0j   ],
            #          [(-8+8j),  0j    ,  0j    ,  -0j   ],
            #          [(-8+0j),  0j    ,  0j    ,  -0j   ],
            #          [(-8-8j),  0j    ,  0j    ,  -0j   ]],

            #         [[(24+0j),  0j    ,  0j    ,  -0j   ],
            #          [(-8+8j),  0j    ,  0j    ,  -0j   ],
            #          [(-8+0j),  0j    ,  0j    ,  -0j   ],
            #          [(-8-8j),  0j    ,  0j    ,  -0j   ]],

            #         [[(24+0j),  0j    ,  0j    ,  -0j   ],
            #          [(-8+8j),  0j    ,  0j    ,  -0j   ],
            #          [(-8+0j),  0j    ,  0j    ,  -0j   ],
            #          [(-8-8j),  0j    ,  0j    ,  -0j   ]],

            #         [[(24+0j),  0j    ,  0j    ,  -0j   ],
            #          [(-8+8j),  0j    ,  0j    ,  -0j   ],
            #          [(-8+0j),  0j    ,  0j    ,  -0j   ],
            #          [(-8-8j),  0j    ,  0j    ,  -0j   ]]])
546
    """
547
    if is_integer(x) or is_floating_point(x):
548 549 550
        return fftn_r2c(
            x, s, axes, norm, forward=True, onesided=False, name=name
        )
551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580
    else:
        return fftn_c2c(x, s, axes, norm, forward=True, name=name)


def ifftn(x, s=None, axes=None, norm="backward", name=None):
    """
    Compute the N-D inverse discrete Fourier Transform.

    This function computes the inverse of the N-D discrete
    Fourier Transform over any number of axes in an M-D array by
    means of the Fast Fourier Transform (FFT).  In other words,
    ``ifftn(fftn(x)) == x`` to within numerical accuracy.

    The input, analogously to `ifft`, should be ordered in the same way as is
    returned by `fftn`, i.e., it should have the term for zero frequency
    in all axes in the low-order corner, the positive frequency terms in the
    first half of all axes, the term for the Nyquist frequency in the middle
    of all axes and the negative frequency terms in the second half of all
    axes, in order of decreasingly negative frequency.

    Args:
        x (Tensor): The input data. It's a Tensor type. It's a complex.
        s (sequence of ints, optional): Shape (length of each transformed axis) of the output
            (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).
            This corresponds to ``n`` for ``fft(x, n)``.
            Along any axis, if the given shape is smaller than that of the input,
            the input is cropped. If it is larger, the input is padded with zeros.
            if `s` is not given, the shape of the input along the axes specified
            by `axes` is used.
        axes (sequence of ints, optional): Axes used to calculate FFT. If not given, the last ``len(s)``
581
            axes are used, or all axes if `s` is also not specified.
582
        norm (str, optional): Indicates which direction to scale the `forward` or `backward` transform
583
            pair and what normalization factor to use. The parameter value must be one
584
            of "forward" or "backward" or "ortho". Default is "backward", meaning no normalization on
585 586
            the forward transforms and scaling by ``1/n`` on the `ifft`. "forward" instead applies
            the ``1/n`` factor on the forward tranform. For ``norm="ortho"``, both directions are
587
            scaled by ``1/sqrt(n)``.
588
        name (str, optional): The default value is None.  Normally there is no need for user to set
589
            this property. For more information, please refer to :ref:`api_guide_Name`.
590

591
    Returns:
592
        complex tensor. The truncated or zero-padded input, transformed along the axes indicated by
593
        `axes`, or by a combination of `s` and `x`, as explained in the parameters section above.
594

595 596 597 598 599 600
    Examples:

        .. code-block:: python

            import paddle

601 602 603 604 605 606 607 608 609 610 611 612 613
            x = paddle.eye(3)
            ifftn_x = paddle.fft.ifftn(x, axes=(1,))
            print(ifftn_x)
            # Tensor(shape=[3, 3], dtype=complex64, place=Place(cpu), stop_gradient=True,
            #        [[ (0.3333333432674408+0j)                  ,
            #           (0.3333333432674408-0j)                  ,
            #           (0.3333333432674408+0j)                  ],
            #         [ (0.3333333432674408+0j)                  ,
            #          (-0.1666666716337204+0.28867512941360474j),
            #          (-0.1666666716337204-0.28867512941360474j)],
            #         [ (0.3333333432674408+0j)                  ,
            #          (-0.1666666716337204-0.28867512941360474j),
            #          (-0.1666666716337204+0.28867512941360474j)]])
614
    """
615
    if is_integer(x) or is_floating_point(x):
616 617 618
        return fftn_r2c(
            x, s, axes, norm, forward=False, onesided=False, name=name
        )
619 620 621 622 623 624
    else:
        return fftn_c2c(x, s, axes, norm, forward=False, name=name)


def rfftn(x, s=None, axes=None, norm="backward", name=None):
    """
U
ustiniankw 已提交
625

626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
    The N dimensional FFT for real input.

    This function computes the N-dimensional discrete Fourier Transform over
    any number of axes in an M-dimensional real array by means of the Fast
    Fourier Transform (FFT).  By default, all axes are transformed, with the
    real transform performed over the last axis, while the remaining
    transforms are complex.

    The transform for real input is performed over the last transformation
    axis, as by `rfft`, then the transform over the remaining axes is
    performed as by `fftn`.  The order of the output is as for `rfft` for the
    final transformation axis, and as for `fftn` for the remaining
    transformation axes.

    Args:
        x(Tensor) : Input tensor, taken to be real.
642 643 644 645 646 647
        s(Sequence[int], optional) : Shape to use from the exec fft. The final element of
            `s` corresponds to `n` for ``rfft(x, n)``, while for the remaining
            axes, it corresponds to `n` for ``fft(x, n)``. Along any axis, if
            the given shape is smaller than that of the input, the input is
            cropped.  If it is larger, the input is padded with zeros. if `s` is
            not given, the shape of the input along the axes specified by `axes`
648
            is used.
649 650
        axes(Sequence[int], optional) : Axes over which to compute the FFT.  If not given,
            the last ``len(s)`` axes are used, or all axes if `s` is also not
651
            specified.
652 653 654 655
        norm(str, optional) : Normalization mode, indicates which direction of
            the forward/backward pair of transforms is scaled and with what
            normalization factor. Include {"backward", "ortho", "forward"},
            default value is "backward". The details of
656
            three operations are shown below:
657 658

                - "backward": The factor of forward direction and backward direction are ``1``
U
ustiniankw 已提交
659
                  and ``1/n`` respectively;
660
                - "forward": The factor of forward direction and backward direction are ``1/n``
U
ustiniankw 已提交
661
                  and ``1`` respectively;
662
                - "ortho": The factor of forward direction and backword direction are both ``1/sqrt(n)``.
663

664
            Where ``n`` is the multiplication of each element in  ``s`` .
665 666 667
        name(str, optional): The default value is None.  Normally there is no
            need for user to set this property. For more information, please
            refer to :ref:`api_guide_Name` .
668 669

    Returns:
U
ustiniankw 已提交
670
        out(Tensor), complex tensor
671 672

    Examples:
U
ustiniankw 已提交
673
        .. code-block:: python
674

U
ustiniankw 已提交
675
            import paddle
676

U
ustiniankw 已提交
677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698
            # default, all axis will be used to exec fft
            x = paddle.ones((2, 3, 4))
            print(paddle.fft.rfftn(x))
            # Tensor(shape=[2, 3, 3], dtype=complex64, place=CUDAPlace(0), stop_gradient=True,
            #        [[[(24+0j), 0j     , 0j     ],
            #          [0j     , 0j     , 0j     ],
            #          [0j     , 0j     , 0j     ]],
            #
            #         [[0j     , 0j     , 0j     ],
            #          [0j     , 0j     , 0j     ],
            #          [0j     , 0j     , 0j     ]]])

            # use axes(2, 0)
            print(paddle.fft.rfftn(x, axes=(2, 0)))
            # Tensor(shape=[2, 3, 3], dtype=complex64, place=CUDAPlace(0), stop_gradient=True,
            #        [[[(8+0j), 0j     , 0j     ],
            #          [(8+0j), 0j     , 0j     ],
            #          [(8+0j), 0j     , 0j     ]],
            #
            #         [[0j     , 0j     , 0j     ],
            #          [0j     , 0j     , 0j     ],
            #          [0j     , 0j     , 0j     ]]])
699 700 701 702 703 704 705 706 707 708 709 710 711

    """
    return fftn_r2c(x, s, axes, norm, forward=True, onesided=True, name=name)


def irfftn(x, s=None, axes=None, norm="backward", name=None):
    """
    Computes the inverse of `rfftn`.

    This function computes the inverse of the N-D discrete
    Fourier Transform for real input over any number of axes in an
    M-D array by means of the Fast Fourier Transform (FFT). In
    other words, ``irfftn(rfftn(x), x.shape) == x`` to within numerical
712
    accuracy. (The ``x.shape`` is necessary like ``len(x)`` is for `irfft`,
713 714 715 716 717 718 719 720
    and for the same reason.)

    The input should be ordered in the same way as is returned by `rfftn`,
    i.e., as for `irfft` for the final transformation axis, and as for `ifftn`
    along all the other axes.

    Args:
        x (Tensor): The input data. It's a Tensor type.
721 722 723 724 725 726 727
        s (sequence of ints, optional): The length of the output transform axis.
            (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).

            - `s` is also the number of input points used along this axis, except for the last axis, where ``s[-1]//2+1`` points of the input are used.
            - Along any axis, if the shape indicated by `s` is smaller than that of the input, the input is cropped. If it is larger, the input is padded with zeros.
            - If `s` is not given, the shape of the input along the axes specified by axes is used. Except for the last axis which is taken to be ``2*(k-1)``

728
            where ``k`` is the length of the input along that axis.
729

730
        axes (sequence of ints, optional): Axes over which to compute the inverse FFT. If not given, the last
731
            `len(s)` axes are used, or all axes if `s` is also not specified.
732
        norm (str): Indicates which direction to scale the `forward` or `backward` transform
733 734
            pair and what normalization factor to use. The parameter value must be one
            of "forward" or "backward" or "ortho". Default is "backward". The details of
735
            three operations are shown below:
736

737 738 739
                - "backward": The factor of forward direction and backward direction are ``1`` and ``1/n`` respectively;
                - "forward": The factor of forward direction and backward direction are ``1/n`` and ``1`` respectively;
                - "ortho": The factor of forward direction and backword direction are both ``1/sqrt(n)``.
740

741
            Where ``n`` is the multiplication of each element in  ``s`` .
742 743 744
        name (str, optional): The default value is None.  Normally there is no need for user to set
            this property. For more information, please refer to :ref:`api_guide_Name`.

745
    Returns:
746 747
        Real tensor. The truncated or zero-padded input, transformed along the axes indicated by `axes`,
        or by a combination of `s` or `x`, as explained in the parameters section above. The length of
748 749
        each transformed axis is as given by the corresponding element of `s`, or the length of the input
        in every axis except for the last one if `s` is not given. In the final transformed axis the length
750 751
        of the output when `s` is not given is ``2*(m-1)``, where ``m`` is the length of the final
        transformed axis of the input. To get an odd number of output points in the final axis,
752 753 754 755 756 757 758 759
        `s` must be specified.

    Examples:

        .. code-block:: python

            import paddle

760 761 762 763
            x = paddle.to_tensor([2.+2.j, 2.+2.j, 3.+3.j]).astype(paddle.complex128)
            print(x)
            irfftn_x = paddle.fft.irfftn(x)
            print(irfftn_x)
764

765 766 767 768
            # Tensor(shape=[3], dtype=complex128, place=Place(cpu), stop_gradient=True,
            #        [(2+2j), (2+2j), (3+3j)])
            # Tensor(shape=[4], dtype=float64, place=Place(cpu), stop_gradient=True,
            #        [ 2.25000000, -1.25000000,  0.25000000,  0.75000000])
769

770 771 772 773 774 775 776 777 778
    """
    return fftn_c2r(x, s, axes, norm, forward=False, name=name)


def hfftn(x, s=None, axes=None, norm="backward", name=None):
    """
    Compute the N-D FFT of Hermitian symmetric complex input, i.e., a
    signal with a real spectrum.

779 780
    This function calculates the n-D discrete Fourier transform of Hermite symmetric
    complex input on any axis in M-D array by fast Fourier transform (FFT).
781
    In other words, ``ihfftn(hfftn(x, s)) == x`` is within the numerical accuracy range.
782
    (``s`` here are ``x.shape`` and ``s[-1] = x.shape[- 1] * 2 - 1``. This is necessary
783
    for the same reason that ``irfft`` requires ``x.shape``.)
784 785 786

    Args:
        x (Tensor): The input data. It's a Tensor type.
787
        s (sequence of ints, optional): The length of the output transform axis.
788 789
            (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.). `s` is also the
            number of input points used along this axis, except for the last axis,
790 791 792 793 794
            where ``s[-1]//2+1`` points of the input are used. Along any axis, if
            the shape indicated by `s` is smaller than that of the input, the input
            is cropped. If it is larger, the input is padded with zeros.
            If `s` is not given, the shape of the input along the axes specified by axes
            is used. Except for the last axis which is taken to be ``2*(k-1)`` where
795 796
            ``k`` is the length of the input along that axis.
        axes (sequence of ints, optional): Axes over which to compute the inverse FFT. If not given, the last
797
            `len(s)` axes are used, or all axes if `s` is also not specified.
798
        norm (str, optional): Indicates which direction to scale the `forward` or `backward` transform
799
            pair and what normalization factor to use. The parameter value must be one
800
            of "forward" or "backward" or "ortho". Default is "backward".
801 802 803
        name (str, optional): The default value is None.  Normally there is no need for user to set
            this property. For more information, please refer to :ref:`api_guide_Name`.

804
    Returns:
805
        Real tensor. Truncate or zero fill input, transforming along the axis indicated by axis or
806
        a combination of `s` or `X`.
807

808 809 810 811 812 813
    Examples:

        .. code-block:: python

            import paddle

814 815 816 817 818
            x = paddle.to_tensor([(2+2j), (2+2j), (3+3j)])
            hfftn_x = paddle.fft.hfftn(x)
            print(hfftn_x)
            # Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
            #        [ 9.,  3.,  1., -5.])
819 820 821 822 823 824 825 826
    """
    return fftn_c2r(x, s, axes, norm, forward=True, name=name)


def ihfftn(x, s=None, axes=None, norm="backward", name=None):
    """
    The n dimensional inverse FFT of a signal that has Hermitian symmetry.

827 828
    This function computes the n dimensional inverse FFT over any number of axes
    in an M-dimensional of a signal that has Hermitian symmetry by means of an
829 830 831 832
    efficient algorithm called the Fast Fourier Transform (FFT).

    Args:
        x(Tensor): Input tensor.
833 834 835 836 837
        s(Sequence[int], optional) : Shape (length along each transformed axis)
            to use from the input. (``s[0]`` refers to axis 0, ``s[1]`` to axis
            1, etc.). Along any axis, if the given shape is smaller than that
            of the input, the input is cropped. If it is larger, the input is
            padded with zeros. if `s` is not given, the shape of the input
838
            along the axes specified by `axes` is used.
839
        axes(Sequence[int], optional) : Axis over which to compute the inverse FFT. If not
840
            given, the last axis is used.
841 842 843
        norm(str, optional) : Normalization mode, indicates which direction of
            the forward/backward pair of transforms is scaled and with what
            normalization factor. Include {"backward", "ortho", "forward"},
844
            default value is "backward".
845 846 847
        name(str, optional): The default value is None.  Normally there is no
            need for user to set this property. For more information, please
            refer to :ref:`api_guide_Name` .
848 849 850 851 852

    Returns:
        out(Tensor) : complex tensor.

    Examples:
853

854
    .. code-block:: python
855 856

        import paddle
857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880

        spectrum = paddle.to_tensor([10.0, -5.0, 0.0, -1.0, 0.0, -5.0])
        print(paddle.fft.ifft(spectrum))
        # Tensor(shape=[6], dtype=complex64, place=CUDAPlace(0), stop_gradient=True,
        #       [(-0.1666666716337204+0j),  (1-1.9868215517249155e-08j), (2.3333334922790527-1.9868215517249155e-08j),  (3.5+0j), (2.3333334922790527+1.9868215517249155e-08j),  (1+1.9868215517249155e-08j)])
        print(paddle.fft.ihfft(spectrum))
        #  Tensor(shape = [4], dtype = complex64, place = CUDAPlace(0), stop_gradient = True,
        #         [(-0.1666666716337204+0j),  (1-1.9868215517249155e-08j), (2.3333334922790527-1.9868215517249155e-08j),  (3.5+0j)])
    """
    return fftn_r2c(x, s, axes, norm, forward=False, onesided=True, name=name)


# public APIs 2d
def fft2(x, s=None, axes=(-2, -1), norm="backward", name=None):
    """
    Compute the 2-D discrete Fourier Transform

    This function computes the N-D discrete Fourier Transform
    over any axes in an M-D array by means of the
    Fast Fourier Transform (FFT). By default, the transform is computed over
    the last two axes of the input array, i.e., a 2-dimensional FFT.

    Args:
        x (Tensor): The input data. It's a Tensor type.
881 882
        s (sequence of ints, optional): Shape (length of each transformed axis) of the output.
            It should be a sequence of 2 integers. This corresponds to ``n`` for ``fft(x, n)``.
883 884 885 886
            Along each axis, if the given shape is smaller than that of the input,
            the input is cropped. If it is larger, the input is padded with zeros.
            if `s` is not given, the shape of the input along the axes specified
            by `axes` is used. Default is None.
887 888
        axes (sequence of ints, optional):  Axes over which to compute the FFT. It should be a
            sequence of 2 integers. If not specified, the last two axes are used by default.
889
        norm (str, optional): Indicates which direction to scale the `forward` or `backward` transform
890
            pair and what normalization factor to use. The parameter value must be one
891
            of "forward" or "backward" or "ortho". Default is "backward".
892 893 894
        name (str, optional): The default value is None.  Normally there is no need for user to set
            this property. For more information, please refer to :ref:`api_guide_Name`.

895
    Returns:
896
        Complex tensor. The truncated or zero-padded input, transformed along the axes indicated by `axes`,
897 898 899 900 901 902 903 904
        or the last two axes if `axes` is not given.

    Examples:

        .. code-block:: python

            import paddle

905 906 907 908
            arr = paddle.arange(2, dtype="float64")
            x = paddle.meshgrid(arr, arr)[0]

            fft2_xp = paddle.fft.fft2(x)
909
            print(fft2_xp)
910 911 912
            # Tensor(shape=[2, 2], dtype=complex128, place=Place(gpu:0), stop_gradient=True,
            #        [[ (2+0j),  0j    ],
            #         [(-2+0j),  0j    ]])
913 914 915 916 917 918

    """
    _check_at_least_ndim(x, 2)
    if s is not None:
        if not isinstance(s, Sequence) or len(s) != 2:
            raise ValueError(
919 920 921 922
                "Invalid FFT argument s ({}), it should be a sequence of 2 integers.".format(
                    s
                )
            )
923 924 925
    if axes is not None:
        if not isinstance(axes, Sequence) or len(axes) != 2:
            raise ValueError(
926 927 928 929
                "Invalid FFT argument axes ({}), it should be a sequence of 2 integers.".format(
                    axes
                )
            )
930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951
    return fftn(x, s, axes, norm, name)


def ifft2(x, s=None, axes=(-2, -1), norm="backward", name=None):
    """
    Compute the 2-D inverse discrete Fourier Transform.

    This function computes the inverse of the 2-D discrete Fourier
    Transform over any number of axes in an M-D array by means of
    the Fast Fourier Transform (FFT). In other words, ``ifft2(fft2(x)) == x``
    to within numerical accuracy. By default, the inverse transform is
    computed over the last two axes of the input array.

    The input, analogously to `ifft`, should be ordered in the same way as is
    returned by `fft2`, i.e., it should have the term for zero frequency
    in the low-order corner of the two axes, the positive frequency terms in
    the first half of these axes, the term for the Nyquist frequency in the
    middle of the axes and the negative frequency terms in the second half of
    both axes, in order of decreasingly negative frequency.

    Args:
        x (Tensor): The input data. It's a Tensor type.
952 953
        s (sequence of ints, optional): Shape (length of each transformed axis) of the output.
            It should be a sequence of 2 integers. This corresponds to ``n`` for ``fft(x, n)``.
954 955 956 957
            Along each axis, if the given shape is smaller than that of the input,
            the input is cropped. If it is larger, the input is padded with zeros.
            if `s` is not given, the shape of the input along the axes specified
            by `axes` is used. Default is None.
958 959
        axes (sequence of ints, optional):  Axes over which to compute the FFT. It should be a
            sequence of 2 integers. If not specified, the last two axes are used by default.
960
        norm (str, optional): Indicates which direction to scale the `forward` or `backward` transform
961
            pair and what normalization factor to use. The parameter value must be one
962
            of "forward" or "backward" or "ortho". Default is "backward".
963
        name (str, optional): The default value is None.  Normally there is no need for user to set
964
            this property. For more information, please refer to :ref:`api_guide_Name`.
965

966
    Returns:
967
        Complex tensor. The truncated or zero-padded input, transformed along the axes indicated by `axes`,
968 969 970 971 972 973 974 975
        or the last two axes if `axes` is not given.

    Examples:

        .. code-block:: python

            import paddle

976 977 978 979
            arr = paddle.arange(2, dtype="float64")
            x = paddle.meshgrid(arr, arr)[0]

            ifft2_xp = paddle.fft.ifft2(x)
980
            print(ifft2_xp)
981 982 983
            # Tensor(shape=[2, 2], dtype=complex128, place=Place(gpu:0), stop_gradient=True,
            #        [[ (0.5+0j),  0j      ],
            #         [(-0.5+0j),  0j      ]])
984 985 986 987 988
    """
    _check_at_least_ndim(x, 2)
    if s is not None:
        if not isinstance(s, Sequence) or len(s) != 2:
            raise ValueError(
989 990 991 992
                "Invalid FFT argument s ({}), it should be a sequence of 2 integers.".format(
                    s
                )
            )
993 994 995
    if axes is not None:
        if not isinstance(axes, Sequence) or len(axes) != 2:
            raise ValueError(
996 997 998 999
                "Invalid FFT argument axes ({}), it should be a sequence of 2 integers.".format(
                    axes
                )
            )
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
    return ifftn(x, s, axes, norm, name)


def rfft2(x, s=None, axes=(-2, -1), norm="backward", name=None):
    """
    The two dimensional FFT with real tensor input.

    This is really just `rfftn` with different default behavior.
    For more details see `rfftn`.

    Args:
        x(Tensor): Input tensor, taken to be real.
1012
        s(Sequence[int], optional) : Shape of the FFT.
1013
        axes(Sequence[int], optional): Axes over which to compute the FFT.
1014 1015 1016 1017
        norm(str, optional) : {"backward", "ortho", "forward"},
            default is "backward". Indicates which direction of the
            forward/backward pair of transforms is scaled and with what
            normalization factor. The details of
1018
            three operations are shown below:
1019

1020 1021 1022
                - "backward": The factor of forward direction and backward direction are ``1`` and ``1/n`` respectively;
                - "forward": The factor of forward direction and backward direction are ``1/n`` and ``1`` respectively;
                - "ortho": The factor of forward direction and backword direction are both ``1/sqrt(n)``.
1023

1024
            Where ``n`` is the multiplication of each element in  ``s`` .
1025 1026 1027
        name(str, optional): The default value is None.  Normally there is no
            need for user to set this property. For more information, please
            refer to :ref:`api_guide_Name` .
1028

1029
    Returns:
1030 1031 1032 1033 1034
        out(Tensor): The result of the real 2-D FFT.

    Examples:

    .. code-block:: python
1035

1036
        import paddle
1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047

        arr = paddle.arange(5, dtype="float64")
        x = paddle.meshgrid(arr, arr)[0]

        result = paddle.fft.rfft2(x)
        print(result.numpy())
        # [[ 50.  +0.j           0.  +0.j           0.  +0.j        ]
        #  [-12.5+17.20477401j   0.  +0.j           0.  +0.j        ]
        #  [-12.5 +4.0614962j    0.  +0.j           0.  +0.j        ]
        #  [-12.5 -4.0614962j    0.  +0.j           0.  +0.j        ]
        #  [-12.5-17.20477401j   0.  +0.j           0.  +0.j        ]]
1048 1049 1050 1051 1052
    """
    _check_at_least_ndim(x, 2)
    if s is not None:
        if not isinstance(s, Sequence) or len(s) != 2:
            raise ValueError(
1053 1054 1055 1056
                "Invalid FFT argument s ({}), it should be a sequence of 2 integers.".format(
                    s
                )
            )
1057 1058 1059
    if axes is not None:
        if not isinstance(axes, Sequence) or len(axes) != 2:
            raise ValueError(
1060 1061 1062 1063
                "Invalid FFT argument axes ({}), it should be a sequence of 2 integers.".format(
                    axes
                )
            )
1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
    return rfftn(x, s, axes, norm, name)


def irfft2(x, s=None, axes=(-2, -1), norm="backward", name=None):
    """
    Computes the inverse of `rfft2`.

    Args:
        x (Tensor): The input data. It's a Tensor type.
        s (sequence of ints, optional): Shape of the real output to the inverse FFT. Default is None.
1074 1075
        axes (sequence of ints, optional): The axes over which to compute the inverse FFT. Axes
            must be two-dimensional. If not specified, the last two axes are used by default.
1076
        norm (str, optional): Indicates which direction to scale the `forward` or `backward` transform
1077 1078
            pair and what normalization factor to use. The parameter value must be one
            of "forward" or "backward" or "ortho". Default is "backward". The details of
1079
            three operations are shown below:
1080

1081 1082 1083
                - "backward": The factor of forward direction and backward direction are ``1`` and ``1/n`` respectively;
                - "forward": The factor of forward direction and backward direction are ``1/n`` and ``1`` respectively;
                - "ortho": The factor of forward direction and backword direction are both ``1/sqrt(n)``.
1084

1085
            Where ``n`` is the multiplication of each element in  ``s`` .
1086 1087 1088
        name (str, optional): The default value is None.  Normally there is no need for user to set
            this property. For more information, please refer to :ref:`api_guide_Name` .

1089 1090
    Returns:
        Real tensor. The result of the inverse real 2-D FFT.
1091

1092 1093 1094 1095 1096 1097
    Examples:

        .. code-block:: python

            import paddle

1098 1099 1100 1101 1102 1103
            x = paddle.to_tensor([[3.+3.j, 2.+2.j, 3.+3.j], [2.+2.j, 2.+2.j, 3.+3.j]])
            irfft2_x = paddle.fft.irfft2(x)
            print(irfft2_x)
            # Tensor(shape=[2, 4], dtype=float32, place=Place(cpu), stop_gradient=True,
            #        [[ 2.37500000, -1.12500000,  0.37500000,  0.87500000],
            #         [ 0.12500000,  0.12500000,  0.12500000,  0.12500000]])
1104 1105 1106 1107 1108
    """
    _check_at_least_ndim(x, 2)
    if s is not None:
        if not isinstance(s, Sequence) or len(s) != 2:
            raise ValueError(
1109 1110 1111 1112
                "Invalid FFT argument s ({}), it should be a sequence of 2 integers.".format(
                    s
                )
            )
1113 1114 1115
    if axes is not None:
        if not isinstance(axes, Sequence) or len(axes) != 2:
            raise ValueError(
1116 1117 1118 1119
                "Invalid FFT argument axes ({}), it should be a sequence of 2 integers.".format(
                    axes
                )
            )
1120 1121 1122 1123 1124 1125 1126 1127 1128 1129
    return irfftn(x, s, axes, norm, name)


def hfft2(x, s=None, axes=(-2, -1), norm="backward", name=None):
    """
    Compute the 2-D FFT of a Hermitian complex array.

    Args:
        x (Tensor): The input data. It's a Tensor type.
        s (sequence of ints, optional): Shape of the real output. Default is None.
1130 1131
        axes (sequence of ints, optional):  Axes over which to compute the FFT. Axes must be
            two-dimensional. If not specified, the last two axes are used by default.
1132
        norm (str): Indicates which direction to scale the `forward` or `backward` transform
1133
            pair and what normalization factor to use. The parameter value must be one
1134
            of "forward" or "backward" or "ortho". Default is "backward".
1135 1136 1137
        name (str, optional): The default value is None.  Normally there is no need for user to set
            this property. For more information, please refer to :ref:`api_guide_Name`.

1138 1139
    Returns:
        Real tensor. The real result of the 2-D Hermitian complex real FFT.
1140

1141 1142 1143 1144 1145 1146
    Examples:

        .. code-block:: python

            import paddle

1147 1148 1149 1150 1151 1152
            x = paddle.to_tensor([[3.+3.j, 2.+2.j, 3.+3.j], [2.+2.j, 2.+2.j, 3.+3.j]])
            hfft2_x = paddle.fft.hfft2(x)
            print(hfft2_x)
            # Tensor(shape=[2, 4], dtype=float32, place=Place(cpu), stop_gradient=True,
            #        [[19.,  7.,  3., -9.],
            #         [ 1.,  1.,  1.,  1.]])
1153 1154 1155 1156 1157
    """
    _check_at_least_ndim(x, 2)
    if s is not None:
        if not isinstance(s, Sequence) or len(s) != 2:
            raise ValueError(
1158 1159 1160 1161
                "Invalid FFT argument s ({}), it should be a sequence of 2 integers.".format(
                    s
                )
            )
1162 1163 1164
    if axes is not None:
        if not isinstance(axes, Sequence) or len(axes) != 2:
            raise ValueError(
1165 1166 1167 1168
                "Invalid FFT argument axes ({}), it should be a sequence of 2 integers.".format(
                    axes
                )
            )
1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
    return hfftn(x, s, axes, norm, name)


def ihfft2(x, s=None, axes=(-2, -1), norm="backward", name=None):
    """
    Compute the two dimensional inverse FFT of a real spectrum.

    This is really `ihfftn` with different defaults.
    For more details see `ihfftn`.

    Args:
1180
        x(Tensor): Input tensor.
1181
        s(Sequence[int], optional): Shape of the real input to the inverse FFT.
1182
        axes(Sequance[int], optional): The axes over which to compute the
1183
            inverse fft. Default is the last two axes.
1184
        norm(str, optional): {"backward", "ortho", "forward"}. Default is
1185
            "backward".
1186 1187 1188
        name(str, optional): The default value is None.  Normally there is no
            need for user to set this property. For more information, please
            refer to :ref:`api_guide_Name` .
1189 1190 1191 1192 1193 1194 1195 1196 1197 1198

    Returns:
        out(Tensor) : The result of the inverse hermitian 2-D FFT.

    Examples:

        .. code-block:: python

            import paddle

1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210
            arr = paddle.arange(5, dtype="float64")
            x = paddle.meshgrid(arr, arr)[0]
            print(x)
            # Tensor(shape=[5, 5], dtype=float64, place=Place(gpu:0), stop_gradient=True,
            #        [[0., 0., 0., 0., 0.],
            #         [1., 1., 1., 1., 1.],
            #         [2., 2., 2., 2., 2.],
            #         [3., 3., 3., 3., 3.],
            #         [4., 4., 4., 4., 4.]])

            ihfft2_xp = paddle.fft.ihfft2(x)
            print(ihfft2_xp.numpy())
1211 1212 1213 1214 1215 1216 1217 1218 1219 1220
            # [[ 2. +0.j          0. +0.j          0. +0.j        ]
            #  [-0.5-0.68819096j  0. +0.j          0. +0.j        ]
            #  [-0.5-0.16245985j  0. +0.j          0. +0.j        ]
            #  [-0.5+0.16245985j  0. +0.j          0. +0.j        ]
            #  [-0.5+0.68819096j  0. +0.j          0. +0.j        ]]
    """
    _check_at_least_ndim(x, 2)
    if s is not None:
        if not isinstance(s, Sequence) or len(s) != 2:
            raise ValueError(
1221 1222 1223 1224
                "Invalid FFT argument s ({}), it should be a sequence of 2 integers.".format(
                    s
                )
            )
1225 1226 1227
    if axes is not None:
        if not isinstance(axes, Sequence) or len(axes) != 2:
            raise ValueError(
1228 1229 1230 1231
                "Invalid FFT argument axes ({}), it should be a sequence of 2 integers.".format(
                    axes
                )
            )
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251
    return ihfftn(x, s, axes, norm, name)


# public APIs utilities
def fftfreq(n, d=1.0, dtype=None, name=None):
    """
    Return the Discrete Fourier Transform sample frequencies.

    The returned float array `f` contains the frequency bin centers in cycles
    per unit of the sample spacing (with zero at the start).  For instance, if
    the sample spacing is in seconds, then the frequency unit is cycles/second.

    Given input length `n` and a sample spacing `d`::

      f = [0, 1, ...,   n/2-1,     -n/2, ..., -1] / (d*n)   if n is even
      f = [0, 1, ..., (n-1)/2, -(n-1)/2, ..., -1] / (d*n)   if n is odd

    Args:
        n (int): Dimension inputed.
        d (scalar, optional): Sample spacing (inverse of the sampling rate). Defaults is 1.
1252
        name (str, optional): The default value is None.  Normally there is no need for user to set
1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264
            this property. For more information, please refer to :ref:`api_guide_Name`.

    Returns:
        Tensor. A tensor of length 'n' containing the sampling frequency.

    Examples:

        .. code-block:: python

            import paddle

            scalar_temp = 0.5
1265
            fftfreq_xp = paddle.fft.fftfreq(5, d=scalar_temp)
1266 1267 1268 1269
            print(fftfreq_xp)
            #  Tensor(shape=[5], dtype=float32, place=CUDAPlace(0), stop_gradient=True,
            #           [ 0.        ,  0.40000001,  0.80000001, -0.80000001, -0.40000001])
    """
1270 1271
    if d * n == 0:
        raise ValueError("d or n should not be 0.")
1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285

    dtype = paddle.framework.get_default_dtype()
    val = 1.0 / (n * d)
    pos_max = (n + 1) // 2
    neg_max = n // 2
    indices = paddle.arange(-neg_max, pos_max, dtype=dtype, name=name)
    indices = paddle.roll(indices, -neg_max, name=name)
    return indices * val


def rfftfreq(n, d=1.0, dtype=None, name=None):
    """
    Return the Discrete Fourier Transform sample frequencies.

1286 1287
    The returned floating-point array "F" contains the center of the frequency unit,
    and the unit is the number of cycles of the sampling interval (the starting point is zero).
1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298

    Given input length `n` and a sample spacing `d`::

      f = [0, 1, ...,     n/2-1,     n/2] / (d*n)   if n is even
      f = [0, 1, ..., (n-1)/2-1, (n-1)/2] / (d*n)   if n is odd

    the Nyquist frequency component is considered to be positive.

    Args:
        n (int): Dimension inputed.
        d (scalar, optional): Sample spacing (inverse of the sampling rate). Defaults is 1.
1299
        dtype (str, optional): The data type of returns. Defaults is the data type of returns
1300
            of ``paddle.get_default_dtype()``.
1301
        name (str, optional): The default value is None.  Normally there is no need for user to set
1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313
            this property. For more information, please refer to :ref:`api_guide_Name`.

    Returns:
        Tensor. A tensor of length ``n//2 + 1`` containing the sample frequencies.

    Examples:

        .. code-block:: python

            import paddle

            scalar_temp = 0.3
1314
            rfftfreq_xp = paddle.fft.rfftfreq(5, d=scalar_temp)
1315 1316 1317 1318 1319 1320
            print(rfftfreq_xp)

            #  Tensor(shape=[3], dtype=float32, place=CUDAPlace(0), stop_gradient=True,
            #           [0.        , 0.66666669, 1.33333337])

    """
1321 1322
    if d * n == 0:
        raise ValueError("d or n should not be 0.")
1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341

    dtype = paddle.framework.get_default_dtype()
    val = 1.0 / (n * d)
    pos_max = 1 + n // 2
    indices = paddle.arange(0, pos_max, dtype=dtype, name=name)
    return indices * val


def fftshift(x, axes=None, name=None):
    """
    Shift the zero-frequency component to the center of the spectrum.

    This function swaps half spaces for all the axes listed (all by default).
    Note that ``y[0]`` is the Nyquist component only if ``len(x)`` is even.

    Args:
        n (int): Dimension inputed.
        axes (int|tuple, optional): The axis on which to move. The default is none, which moves all axes.
            Default is None.
1342
        name (str, optional): The default value is None.  Normally there is no need for user to set
1343 1344 1345 1346
            this property. For more information, please refer to :ref:`api_guide_Name`.

    Returns:
        Tensor. The shifted tensor.
1347

1348 1349 1350 1351 1352 1353
    Examples:

        .. code-block:: python

            import paddle

1354 1355 1356 1357 1358 1359
            fftfreq_xp = paddle.fft.fftfreq(5, d=0.3)
            print(fftfreq_xp)
            # Tensor(shape=[5], dtype=float32, place=Place(gpu:0), stop_gradient=True,
            #        [ 0.        ,  0.66666669,  1.33333337, -1.33333337, -0.66666669])

            res = paddle.fft.fftshift(fftfreq_xp)
1360
            print(res)
1361 1362
            # Tensor(shape=[5], dtype=float32, place=Place(gpu:0), stop_gradient=True,
            #        [-1.33333337, -0.66666669,  0.        ,  0.66666669,  1.33333337])
1363 1364 1365 1366 1367

    """
    shape = paddle.shape(x)
    if axes is None:
        # shift all axes
1368 1369 1370
        rank = len(x.shape)
        axes = list(range(0, rank))
        shifts = shape // 2
1371 1372 1373
    elif isinstance(axes, int):
        shifts = shape[axes] // 2
    else:
1374
        shifts = paddle.concat([shape[ax : ax + 1] // 2 for ax in axes])
1375 1376 1377 1378 1379
    return paddle.roll(x, shifts, axes, name=name)


def ifftshift(x, axes=None, name=None):
    """
1380
    The inverse of `fftshift`. Although the even length 'x' is the same, the function of the
1381 1382 1383 1384 1385 1386
    odd length 'x' is different. An example.

    Args:
        n (int): Dimension inputed.
        axes (int|tuple, optional): The axis on which to move. The default is none, which moves all axes.
            Default is None.
1387
        name (str, optional): The default value is None.  Normally there is no need for user to set
1388 1389 1390 1391
            this property. For more information, please refer to :ref:`api_guide_Name`.

    Returns:
        Tensor. The shifted tensor.
1392

1393 1394 1395 1396 1397 1398
    Examples:

        .. code-block:: python

            import paddle

1399 1400 1401 1402 1403 1404
            fftfreq_xp = paddle.fft.fftfreq(5, d=0.3)
            print(fftfreq_xp)
            # Tensor(shape=[5], dtype=float32, place=Place(gpu:0), stop_gradient=True,
            #        [ 0.        ,  0.66666669,  1.33333337, -1.33333337, -0.66666669])

            res = paddle.fft.ifftshift(fftfreq_xp)
1405
            print(res)
1406 1407
            # Tensor(shape=[5], dtype=float32, place=Place(gpu:0), stop_gradient=True,
            #        [ 1.33333337, -1.33333337, -0.66666669,  0.        ,  0.66666669])
1408 1409 1410 1411 1412

    """
    shape = paddle.shape(x)
    if axes is None:
        # shift all axes
1413 1414
        rank = len(x.shape)
        axes = list(range(0, rank))
1415
        shifts = -shape // 2
1416 1417 1418
    elif isinstance(axes, int):
        shifts = -shape[axes] // 2
    else:
1419
        shifts = paddle.concat([-shape[ax : ax + 1] // 2 for ax in axes])
1420 1421 1422 1423 1424
    return paddle.roll(x, shifts, axes, name=name)


# internal functions
def fft_c2c(x, n, axis, norm, forward, name):
1425
    if is_integer(x):
1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439
        x = paddle.cast(x, _real_to_complex_dtype(paddle.get_default_dtype()))
    elif is_floating_point(x):
        x = paddle.cast(x, _real_to_complex_dtype(x.dtype))
    _check_normalization(norm)

    axis = axis if axis is not None else -1
    _check_fft_axis(x, axis)
    axes = [axis]
    axes = _normalize_axes(x, axes)
    if n is not None:
        _check_fft_n(n)
        s = [n]
        x = _resize_fft_input(x, s, axes)

1440
    if in_dynamic_mode():
1441
        out = _C_ops.fft_c2c(x, axes, norm, forward)
1442
    else:
1443 1444
        op_type = 'fft_c2c'
        check_variable_and_dtype(x, 'x', ['complex64', 'complex128'], op_type)
1445 1446 1447
        inputs = {
            'X': [x],
        }
1448 1449 1450 1451 1452
        attrs = {'axes': axes, 'normalization': norm, 'forward': forward}
        helper = LayerHelper(op_type, **locals())
        dtype = helper.input_dtype(input_param_name='x')
        out = helper.create_variable_for_type_inference(dtype)
        outputs = {"Out": [out]}
1453 1454 1455
        helper.append_op(
            type=op_type, inputs=inputs, outputs=outputs, attrs=attrs
        )
1456 1457 1458 1459
    return out


def fft_r2c(x, n, axis, norm, forward, onesided, name):
1460
    if is_integer(x):
1461 1462 1463 1464 1465 1466 1467 1468 1469 1470
        x = paddle.cast(x, paddle.get_default_dtype())
    _check_normalization(norm)
    axis = axis if axis is not None else -1
    _check_fft_axis(x, axis)
    axes = [axis]
    axes = _normalize_axes(x, axes)
    if n is not None:
        _check_fft_n(n)
        s = [n]
        x = _resize_fft_input(x, s, axes)
1471
    if in_dynamic_mode():
1472
        out = _C_ops.fft_r2c(x, axes, norm, forward, onesided)
1473
    else:
1474 1475 1476 1477
        op_type = 'fft_r2c'
        check_variable_and_dtype(
            x, 'x', ['float16', 'float32', 'float64'], op_type
        )
1478 1479 1480
        inputs = {
            'X': [x],
        }
1481 1482 1483 1484 1485 1486 1487 1488 1489
        attrs = {
            'axes': axes,
            'normalization': norm,
            'forward': forward,
            'onesided': onesided,
        }
        helper = LayerHelper(op_type, **locals())
        dtype = helper.input_dtype(input_param_name='x')
        out = helper.create_variable_for_type_inference(
1490 1491
            _real_to_complex_dtype(dtype)
        )
1492
        outputs = {"Out": [out]}
1493 1494 1495
        helper.append_op(
            type=op_type, inputs=inputs, outputs=outputs, attrs=attrs
        )
1496 1497 1498 1499
    return out


def fft_c2r(x, n, axis, norm, forward, name):
1500
    if is_integer(x):
1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513
        x = paddle.cast(x, _real_to_complex_dtype(paddle.get_default_dtype()))
    elif is_floating_point(x):
        x = paddle.cast(x, _real_to_complex_dtype(x.dtype))
    _check_normalization(norm)
    axis = axis if axis is not None else -1
    _check_fft_axis(x, axis)
    axes = [axis]
    axes = _normalize_axes(x, axes)
    if n is not None:
        _check_fft_n(n)
        s = [n // 2 + 1]
        x = _resize_fft_input(x, s, axes)

1514
    if in_dynamic_mode():
F
Feiyu Chan 已提交
1515
        if n is not None:
1516
            out = _C_ops.fft_c2r(x, axes, norm, forward, n)
F
Feiyu Chan 已提交
1517
        else:
1518
            out = _C_ops.fft_c2r(x, axes, norm, forward, 0)
1519
    else:
1520 1521
        op_type = 'fft_c2r'
        check_variable_and_dtype(x, 'x', ['complex64', 'complex128'], op_type)
1522 1523 1524
        inputs = {
            'X': [x],
        }
1525 1526 1527 1528 1529 1530
        attrs = {'axes': axes, 'normalization': norm, 'forward': forward}
        if n is not None:
            attrs['last_dim_size'] = n
        helper = LayerHelper(op_type, **locals())
        dtype = helper.input_dtype(input_param_name='x')
        out = helper.create_variable_for_type_inference(
1531 1532
            _complex_to_real_dtype(dtype)
        )
1533
        outputs = {"Out": [out]}
1534 1535 1536
        helper.append_op(
            type=op_type, inputs=inputs, outputs=outputs, attrs=attrs
        )
1537 1538 1539 1540
    return out


def fftn_c2c(x, s, axes, norm, forward, name):
1541
    if is_integer(x):
1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563
        x = paddle.cast(x, _real_to_complex_dtype(paddle.get_default_dtype()))
    elif is_floating_point(x):
        x = paddle.cast(x, _real_to_complex_dtype(x.dtype))
    _check_normalization(norm)
    if s is not None:
        _check_fft_shape(x, s)

    rank = x.ndim
    if axes is None:
        if s is None:
            axes = list(range(rank))
        else:
            fft_ndims = len(s)
            axes = list(range(rank - fft_ndims, rank))
    else:
        _check_fft_axes(x, axes)
        axes = _normalize_axes(x, axes)
        axes_argsoft = np.argsort(axes).tolist()
        axes = [axes[i] for i in axes_argsoft]
        if s is not None:
            if len(s) != len(axes):
                raise ValueError(
1564 1565 1566 1567
                    "Length of s ({}) and length of axes ({}) does not match.".format(
                        len(s), len(axes)
                    )
                )
1568 1569 1570 1571 1572
            s = [s[i] for i in axes_argsoft]

    if s is not None:
        x = _resize_fft_input(x, s, axes)

1573
    if in_dynamic_mode():
1574
        out = _C_ops.fft_c2c(x, axes, norm, forward)
1575
    else:
1576 1577
        op_type = 'fft_c2c'
        check_variable_and_dtype(x, 'x', ['complex64', 'complex128'], op_type)
1578 1579 1580
        inputs = {
            'X': [x],
        }
1581 1582 1583 1584 1585
        attrs = {'axes': axes, 'normalization': norm, 'forward': forward}
        helper = LayerHelper(op_type, **locals())
        dtype = helper.input_dtype(input_param_name='x')
        out = helper.create_variable_for_type_inference(dtype)
        outputs = {"Out": [out]}
1586 1587 1588
        helper.append_op(
            type=op_type, inputs=inputs, outputs=outputs, attrs=attrs
        )
1589 1590 1591 1592
    return out


def fftn_r2c(x, s, axes, norm, forward, onesided, name):
1593
    if is_integer(x):
1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613
        x = paddle.cast(x, paddle.get_default_dtype())
    _check_normalization(norm)
    if s is not None:
        _check_fft_shape(x, s)

    rank = x.ndim
    if axes is None:
        if s is None:
            axes = list(range(rank))
        else:
            fft_ndims = len(s)
            axes = list(range(rank - fft_ndims, rank))
    else:
        _check_fft_axes(x, axes)
        axes = _normalize_axes(x, axes)
        axes_argsoft = np.argsort(axes[:-1]).tolist()
        axes = [axes[i] for i in axes_argsoft] + [axes[-1]]
        if s is not None:
            if len(s) != len(axes):
                raise ValueError(
1614 1615 1616 1617
                    "Length of s ({}) and length of axes ({}) does not match.".format(
                        len(s), len(axes)
                    )
                )
1618 1619 1620 1621 1622
            s = [s[i] for i in axes_argsoft] + [s[-1]]

    if s is not None:
        x = _resize_fft_input(x, s, axes)

1623
    if in_dynamic_mode():
1624
        out = _C_ops.fft_r2c(x, axes, norm, forward, onesided)
1625
    else:
1626 1627 1628 1629
        op_type = 'fft_r2c'
        check_variable_and_dtype(
            x, 'x', ['float16', 'float32', 'float64'], op_type
        )
1630 1631 1632
        inputs = {
            'X': [x],
        }
1633 1634 1635 1636 1637 1638 1639 1640 1641
        attrs = {
            'axes': axes,
            'normalization': norm,
            'forward': forward,
            'onesided': onesided,
        }
        helper = LayerHelper(op_type, **locals())
        dtype = helper.input_dtype(input_param_name='x')
        out = helper.create_variable_for_type_inference(
1642 1643
            _real_to_complex_dtype(dtype)
        )
1644
        outputs = {"Out": [out]}
1645 1646 1647
        helper.append_op(
            type=op_type, inputs=inputs, outputs=outputs, attrs=attrs
        )
1648 1649 1650 1651 1652

    return out


def fftn_c2r(x, s, axes, norm, forward, name):
1653
    if is_integer(x):
1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675
        x = paddle.cast(x, _real_to_complex_dtype(paddle.get_default_dtype()))
    elif is_floating_point(x):
        x = paddle.cast(x, _real_to_complex_dtype(x.dtype))
    _check_normalization(norm)
    if s is not None:
        _check_fft_shape(x, s)

    rank = x.ndim
    if axes is None:
        if s is None:
            axes = list(range(rank))
        else:
            fft_ndims = len(s)
            axes = list(range(rank - fft_ndims, rank))
    else:
        _check_fft_axes(x, axes)
        axes = _normalize_axes(x, axes)
        axes_argsoft = np.argsort(axes[:-1]).tolist()
        axes = [axes[i] for i in axes_argsoft] + [axes[-1]]
        if s is not None:
            if len(s) != len(axes):
                raise ValueError(
1676 1677 1678 1679
                    "Length of s ({}) and length of axes ({}) does not match.".format(
                        len(s), len(axes)
                    )
                )
1680 1681 1682 1683 1684 1685 1686
            s = [s[i] for i in axes_argsoft] + [s[-1]]

    if s is not None:
        fft_input_shape = list(s)
        fft_input_shape[-1] = fft_input_shape[-1] // 2 + 1
        x = _resize_fft_input(x, fft_input_shape, axes)

1687
    if in_dynamic_mode():
F
Feiyu Chan 已提交
1688
        if s is not None:
1689
            out = _C_ops.fft_c2r(x, axes, norm, forward, s[-1])
F
Feiyu Chan 已提交
1690
        else:
1691
            out = _C_ops.fft_c2r(x, axes, norm, forward, 0)
1692
    else:
1693 1694
        op_type = 'fft_c2r'
        check_variable_and_dtype(x, 'x', ['complex64', 'complex128'], op_type)
1695 1696 1697
        inputs = {
            'X': [x],
        }
1698 1699 1700 1701 1702 1703
        attrs = {'axes': axes, 'normalization': norm, 'forward': forward}
        if s:
            attrs["last_dim_size"] = s[-1]
        helper = LayerHelper(op_type, **locals())
        dtype = helper.input_dtype(input_param_name='x')
        out = helper.create_variable_for_type_inference(
1704 1705
            _complex_to_real_dtype(dtype)
        )
1706
        outputs = {"Out": [out]}
1707 1708 1709
        helper.append_op(
            type=op_type, inputs=inputs, outputs=outputs, attrs=attrs
        )
1710
    return out