signal.py 21.8 KB
Newer Older
1
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
2
#
3 4 5
# 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
6
#
7
#     http://www.apache.org/licenses/LICENSE-2.0
8
#
9 10 11 12 13 14 15 16
# 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.

import paddle

17
from .tensor.attribute import is_complex
18
from .fft import fft_r2c, fft_c2r, fft_c2c
19
from .fluid.data_feeder import check_variable_and_dtype
J
Jiabin Yang 已提交
20
from .fluid.framework import _non_static_mode
21
from .fluid.layer_helper import LayerHelper
22
from paddle import _C_ops, _legacy_C_ops
C
Charles-hit 已提交
23
from paddle.fluid.framework import in_dygraph_mode, _in_legacy_dygraph
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39

__all__ = [
    'stft',
    'istft',
]


def frame(x, frame_length, hop_length, axis=-1, name=None):
    """
    Slice the N-dimensional (where N >= 1) input into (overlapping) frames.

    Args:
        x (Tensor): The input data which is a N-dimensional (where N >= 1) Tensor
            with shape `[..., seq_length]` or `[seq_length, ...]`.
        frame_length (int): Length of the frame and `0 < frame_length <= x.shape[axis]`.
        hop_length (int): Number of steps to advance between adjacent frames
40
            and `0 < hop_length`.
41 42
        axis (int, optional): Specify the axis to operate on the input Tensors. Its
            value should be 0(the first dimension) or -1(the last dimension). If not
43
            specified, the last axis is used by default.
44 45 46 47

    Returns:
        The output frames tensor with shape `[..., frame_length, num_frames]` if `axis==-1`,
            otherwise `[num_frames, frame_length, ...]` where
48

49 50 51 52 53 54 55
            `num_framse = 1 + (x.shape[axis] - frame_length) // hop_length`

    Examples:

    .. code-block:: python

        import paddle
56
        from paddle.signal import frame
57

58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
        # 1D
        x = paddle.arange(8)
        y0 = frame(x, frame_length=4, hop_length=2, axis=-1)  # [4, 3]
        # [[0, 2, 4],
        #  [1, 3, 5],
        #  [2, 4, 6],
        #  [3, 5, 7]]

        y1 = frame(x, frame_length=4, hop_length=2, axis=0)   # [3, 4]
        # [[0, 1, 2, 3],
        #  [2, 3, 4, 5],
        #  [4, 5, 6, 7]]

        # 2D
        x0 = paddle.arange(16).reshape([2, 8])
        y0 = frame(x0, frame_length=4, hop_length=2, axis=-1)  # [2, 4, 3]
        # [[[0, 2, 4],
        #   [1, 3, 5],
        #   [2, 4, 6],
        #   [3, 5, 7]],
        #
        #  [[8 , 10, 12],
        #   [9 , 11, 13],
        #   [10, 12, 14],
        #   [11, 13, 15]]]

        x1 = paddle.arange(16).reshape([8, 2])
        y1 = frame(x1, frame_length=4, hop_length=2, axis=0)   # [3, 4, 2]
        # [[[0 , 1 ],
        #   [2 , 3 ],
        #   [4 , 5 ],
        #   [6 , 7 ]],
        #
        #   [4 , 5 ],
        #   [6 , 7 ],
        #   [8 , 9 ],
        #   [10, 11]],
        #
        #   [8 , 9 ],
        #   [10, 11],
        #   [12, 13],
        #   [14, 15]]]

        # > 2D
        x0 = paddle.arange(32).reshape([2, 2, 8])
        y0 = frame(x0, frame_length=4, hop_length=2, axis=-1)  # [2, 2, 4, 3]

        x1 = paddle.arange(32).reshape([8, 2, 2])
        y1 = frame(x1, frame_length=4, hop_length=2, axis=0)   # [3, 4, 2, 2]
    """
    if axis not in [0, -1]:
        raise ValueError(f'Unexpected axis: {axis}. It should be 0 or -1.')

    if not isinstance(frame_length, int) or frame_length <= 0:
        raise ValueError(
            f'Unexpected frame_length: {frame_length}. It should be an positive integer.'
        )

    if not isinstance(hop_length, int) or hop_length <= 0:
        raise ValueError(
            f'Unexpected hop_length: {hop_length}. It should be an positive integer.'
        )

J
Jiabin Yang 已提交
121
    if _non_static_mode():
122 123 124
        if frame_length > x.shape[axis]:
            raise ValueError(
                f'Attribute frame_length should be less equal than sequence length, '
125 126
                f'but got ({frame_length}) > ({x.shape[axis]}).'
            )
127 128 129

    op_type = 'frame'

C
Charles-hit 已提交
130
    if in_dygraph_mode():
131
        return _C_ops.frame(x, frame_length, hop_length, axis)
C
Charles-hit 已提交
132 133

    if _in_legacy_dygraph():
134 135 136 137 138 139 140 141
        attrs = (
            'frame_length',
            frame_length,
            'hop_length',
            hop_length,
            'axis',
            axis,
        )
142
        op = getattr(_legacy_C_ops, op_type)
143 144 145
        out = op(x, *attrs)
    else:
        check_variable_and_dtype(
146 147
            x, 'x', ['int32', 'int64', 'float16', 'float32', 'float64'], op_type
        )
148 149 150
        helper = LayerHelper(op_type, **locals())
        dtype = helper.input_dtype(input_param_name='x')
        out = helper.create_variable_for_type_inference(dtype=dtype)
151 152 153 154 155 156 157 158 159 160
        helper.append_op(
            type=op_type,
            inputs={'X': x},
            attrs={
                'frame_length': frame_length,
                'hop_length': hop_length,
                'axis': axis,
            },
            outputs={'Out': out},
        )
161 162 163 164 165 166 167 168 169 170 171 172
    return out


def overlap_add(x, hop_length, axis=-1, name=None):
    """
    Reconstructs a tensor consisted of overlap added sequences from input frames.

    Args:
        x (Tensor): The input data which is a N-dimensional (where N >= 2) Tensor
            with shape `[..., frame_length, num_frames]` or
            `[num_frames, frame_length ...]`.
        hop_length (int): Number of steps to advance between adjacent frames and
173
            `0 < hop_length <= frame_length`.
174 175
        axis (int, optional): Specify the axis to operate on the input Tensors. Its
            value should be 0(the first dimension) or -1(the last dimension). If not
176
            specified, the last axis is used by default.
177 178 179 180 181 182 183 184 185 186 187 188

    Returns:
        The output frames tensor with shape `[..., seq_length]` if `axis==-1`,
            otherwise `[seq_length, ...]` where

            `seq_length = (n_frames - 1) * hop_length + frame_length`

    Examples:

    .. code-block:: python

        import paddle
189
        from paddle.signal import overlap_add
190

191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
        # 2D
        x0 = paddle.arange(16).reshape([8, 2])
        # [[0 , 1 ],
        #  [2 , 3 ],
        #  [4 , 5 ],
        #  [6 , 7 ],
        #  [8 , 9 ],
        #  [10, 11],
        #  [12, 13],
        #  [14, 15]]
        y0 = overlap_add(x0, hop_length=2, axis=-1)  # [10]
        # [0 , 2 , 5 , 9 , 13, 17, 21, 25, 13, 15]

        x1 = paddle.arange(16).reshape([2, 8])
        # [[0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 ],
        #  [8 , 9 , 10, 11, 12, 13, 14, 15]]
        y1 = overlap_add(x1, hop_length=2, axis=0)   # [10]
        # [0 , 1 , 10, 12, 14, 16, 18, 20, 14, 15]

        # > 2D
        x0 = paddle.arange(32).reshape([2, 1, 8, 2])
        y0 = overlap_add(x0, hop_length=2, axis=-1)  # [2, 1, 10]

        x1 = paddle.arange(32).reshape([2, 8, 1, 2])
215
        y1 = overlap_add(x1, hop_length=2, axis=0)   # [10, 1, 2]
216 217 218 219 220 221 222 223 224 225 226
    """
    if axis not in [0, -1]:
        raise ValueError(f'Unexpected axis: {axis}. It should be 0 or -1.')

    if not isinstance(hop_length, int) or hop_length <= 0:
        raise ValueError(
            f'Unexpected hop_length: {hop_length}. It should be an positive integer.'
        )

    op_type = 'overlap_add'

227
    if in_dygraph_mode():
228
        out = _C_ops.overlap_add(x, hop_length, axis)
229
    elif paddle.in_dynamic_mode():
230
        attrs = ('hop_length', hop_length, 'axis', axis)
231
        op = getattr(_legacy_C_ops, op_type)
232 233 234
        out = op(x, *attrs)
    else:
        check_variable_and_dtype(
235 236
            x, 'x', ['int32', 'int64', 'float16', 'float32', 'float64'], op_type
        )
237 238 239
        helper = LayerHelper(op_type, **locals())
        dtype = helper.input_dtype(input_param_name='x')
        out = helper.create_variable_for_type_inference(dtype=dtype)
240 241 242 243 244 245
        helper.append_op(
            type=op_type,
            inputs={'X': x},
            attrs={'hop_length': hop_length, 'axis': axis},
            outputs={'Out': out},
        )
246 247 248
    return out


249 250 251 252 253 254 255 256 257 258 259 260
def stft(
    x,
    n_fft,
    hop_length=None,
    win_length=None,
    window=None,
    center=True,
    pad_mode='reflect',
    normalized=False,
    onesided=True,
    name=None,
):
261
    r"""
U
ustiniankw 已提交
262

263 264 265 266
    Short-time Fourier transform (STFT).

    The STFT computes the discrete Fourier transforms (DFT) of short overlapping
    windows of the input using this formula:
267

268 269 270 271
    .. math::
        X_t[\omega] = \sum_{n = 0}^{N-1}%
                      \text{window}[n]\ x[t \times H + n]\ %
                      e^{-{2 \pi j \omega n}/{N}}
272

273 274
    Where:
    - :math:`t`: The :math:`t`-th input window.
U
ustiniankw 已提交
275

276
    - :math:`\omega`: Frequency :math:`0 \leq \omega < \text{n\_fft}` for `onesided=False`,
U
ustiniankw 已提交
277 278
      or :math:`0 \leq \omega < \lfloor \text{n\_fft} / 2 \rfloor + 1` for `onesided=True`.

279
    - :math:`N`: Value of `n_fft`.
U
ustiniankw 已提交
280

281 282
    - :math:`H`: Value of `hop_length`.

283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
    Args:
        x (Tensor): The input data which is a 1-dimensional or 2-dimensional Tensor with
            shape `[..., seq_length]`. It can be a real-valued or a complex Tensor.
        n_fft (int): The number of input samples to perform Fourier transform.
        hop_length (int, optional): Number of steps to advance between adjacent windows
            and `0 < hop_length`. Default: `None`(treated as equal to `n_fft//4`)
        win_length (int, optional): The size of window. Default: `None`(treated as equal
            to `n_fft`)
        window (Tensor, optional): A 1-dimensional tensor of size `win_length`. It will
            be center padded to length `n_fft` if `win_length < n_fft`. Default: `None`(
            treated as a rectangle window with value equal to 1 of size `win_length`).
        center (bool, optional): Whether to pad `x` to make that the
            :math:`t \times hop\_length` at the center of :math:`t`-th frame. Default: `True`.
        pad_mode (str, optional): Choose padding pattern when `center` is `True`. See
            `paddle.nn.functional.pad` for all padding options. Default: `"reflect"`
        normalized (bool, optional): Control whether to scale the output by `1/sqrt(n_fft)`.
            Default: `False`
        onesided (bool, optional): Control whether to return half of the Fourier transform
            output that satisfies the conjugate symmetry condition when input is a real-valued
            tensor. It can not be `True` if input is a complex tensor. Default: `True`
        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`.
305

306
    Returns:
U
ustiniankw 已提交
307 308 309
        The complex STFT output tensor with shape `[..., n_fft//2 + 1, num_frames]`
        (real-valued input and `onesided` is `True`) or `[..., n_fft, num_frames]`
        (`onesided` is `False`)
310

311
    Examples:
312
        .. code-block:: python
313

314
            import paddle
315
            from paddle.signal import stft
316

317 318 319 320
            # real-valued input
            x = paddle.randn([8, 48000], dtype=paddle.float64)
            y1 = stft(x, n_fft=512)  # [8, 257, 376]
            y2 = stft(x, n_fft=512, onesided=False)  # [8, 512, 376]
321

322 323 324 325
            # complex input
            x = paddle.randn([8, 48000], dtype=paddle.float64) + \
                    paddle.randn([8, 48000], dtype=paddle.float64)*1j  # [8, 48000] complex128
            y1 = stft(x, n_fft=512, center=False, onesided=False)  # [8, 512, 372]
U
ustiniankw 已提交
326

327
    """
328 329 330
    check_variable_and_dtype(
        x, 'x', ['float32', 'float64', 'complex64', 'complex128'], 'stft'
    )
331 332

    x_rank = len(x.shape)
333 334 335 336
    assert x_rank in [
        1,
        2,
    ], f'x should be a 1D or 2D real tensor, but got rank of x is {x_rank}'
337 338 339 340 341 342 343

    if x_rank == 1:  # (batch, seq_length)
        x = x.unsqueeze(0)

    if hop_length is None:
        hop_length = int(n_fft // 4)

344
    assert hop_length > 0, f'hop_length should be > 0, but got {hop_length}.'
345 346 347 348

    if win_length is None:
        win_length = n_fft

J
Jiabin Yang 已提交
349
    if _non_static_mode():
350 351 352
        assert (
            0 < n_fft <= x.shape[-1]
        ), f'n_fft should be in (0, seq_length({x.shape[-1]})], but got {n_fft}.'
353

354 355 356
    assert (
        0 < win_length <= n_fft
    ), f'win_length should be in (0, n_fft({n_fft})], but got {win_length}.'
357 358

    if window is not None:
359 360 361
        assert (
            len(window.shape) == 1 and len(window) == win_length
        ), f'expected a 1D window tensor of size equal to win_length({win_length}), but got window with shape {window.shape}.'
362
    else:
363
        window = paddle.ones(shape=(win_length,), dtype=x.dtype)
364 365 366 367

    if win_length < n_fft:
        pad_left = (n_fft - win_length) // 2
        pad_right = n_fft - win_length - pad_left
368 369 370
        window = paddle.nn.functional.pad(
            window, pad=[pad_left, pad_right], mode='constant'
        )
371 372

    if center:
373 374 375 376 377 378
        assert pad_mode in [
            'constant',
            'reflect',
        ], 'pad_mode should be "reflect" or "constant", but got "{}".'.format(
            pad_mode
        )
379 380 381

        pad_length = n_fft // 2
        # FIXME: Input `x` can be a complex tensor but pad does not supprt complex input.
382 383 384 385 386 387
        x = paddle.nn.functional.pad(
            x.unsqueeze(-1),
            pad=[pad_length, pad_length],
            mode=pad_mode,
            data_format="NLC",
        ).squeeze(-1)
388 389 390

    x_frames = frame(x=x, frame_length=n_fft, hop_length=hop_length, axis=-1)
    x_frames = x_frames.transpose(
391 392
        perm=[0, 2, 1]
    )  # switch n_fft to last dim, egs: (batch, num_frames, n_fft)
393
    x_frames = paddle.multiply(x_frames, window)
394 395 396

    norm = 'ortho' if normalized else 'backward'
    if is_complex(x_frames):
397 398 399
        assert (
            not onesided
        ), 'onesided should be False when input or window is a complex Tensor.'
400 401

    if not is_complex(x):
402 403 404 405 406 407 408 409 410
        out = fft_r2c(
            x=x_frames,
            n=None,
            axis=-1,
            norm=norm,
            forward=True,
            onesided=onesided,
            name=name,
        )
411
    else:
412 413 414
        out = fft_c2c(
            x=x_frames, n=None, axis=-1, norm=norm, forward=True, name=name
        )
415 416 417 418 419 420 421 422 423

    out = out.transpose(perm=[0, 2, 1])  # (batch, n_fft, num_frames)

    if x_rank == 1:
        out.squeeze_(0)

    return out


424 425 426 427 428 429 430 431 432 433 434 435 436
def istft(
    x,
    n_fft,
    hop_length=None,
    win_length=None,
    window=None,
    center=True,
    normalized=False,
    onesided=True,
    length=None,
    return_complex=False,
    name=None,
):
437
    r"""
438 439 440
    Inverse short-time Fourier transform (ISTFT).

    Reconstruct time-domain signal from the giving complex input and window tensor when
441
        nonzero overlap-add (NOLA) condition is met:
442 443 444 445 446 447 448 449 450 451

    .. math::
        \sum_{t = -\infty}^{\infty}%
            \text{window}^2[n - t \times H]\ \neq \ 0, \ \text{for } all \ n

    Where:
    - :math:`t`: The :math:`t`-th input window.
    - :math:`N`: Value of `n_fft`.
    - :math:`H`: Value of `hop_length`.

452
    Result of `istft` expected to be the inverse of `paddle.signal.stft`, but it is
453 454 455 456 457 458 459
        not guaranteed to reconstruct a exactly realizible time-domain signal from a STFT
        complex tensor which has been modified (via masking or otherwise). Therefore, `istft`
        gives the [Griffin-Lim optimal estimate](https://ieeexplore.ieee.org/document/1164317)
        (optimal in a least-squares sense) for the corresponding signal.

    Args:
        x (Tensor): The input data which is a 2-dimensional or 3-dimensional **complesx**
460
            Tensor with shape `[..., n_fft, num_frames]`.
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
        n_fft (int): The size of Fourier transform.
        hop_length (int, optional): Number of steps to advance between adjacent windows
            from time-domain signal and `0 < hop_length < win_length`. Default: `None`(
            treated as equal to `n_fft//4`)
        win_length (int, optional): The size of window. Default: `None`(treated as equal
            to `n_fft`)
        window (Tensor, optional): A 1-dimensional tensor of size `win_length`. It will
            be center padded to length `n_fft` if `win_length < n_fft`. It should be a
            real-valued tensor if `return_complex` is False. Default: `None`(treated as
            a rectangle window with value equal to 1 of size `win_length`).
        center (bool, optional): It means that whether the time-domain signal has been
            center padded. Default: `True`.
        normalized (bool, optional): Control whether to scale the output by `1/sqrt(n_fft)`.
            Default: `False`
        onesided (bool, optional): It means that whether the input STFT tensor is a half
            of the conjugate symmetry STFT tensor transformed from a real-valued signal
            and `istft` will return a real-valued tensor when it is set to `True`.
            Default: `True`.
        length (int, optional): Specify the length of time-domain signal. Default: `None`(
480
            treated as the whole length of signal).
481 482
        return_complex (bool, optional): It means that whether the time-domain signal is
            real-valued. If `return_complex` is set to `True`, `onesided` should be set to
483
            `False` cause the output is complex.
484 485 486 487 488 489 490
        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`.

    Returns:
        A tensor of least squares estimation of the reconstructed signal(s) with shape
            `[..., seq_length]`

491
    Examples:
492 493 494 495
        .. code-block:: python

            import numpy as np
            import paddle
496
            from paddle.signal import stft, istft
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511

            paddle.seed(0)

            # STFT
            x = paddle.randn([8, 48000], dtype=paddle.float64)
            y = stft(x, n_fft=512)  # [8, 257, 376]

            # ISTFT
            x_ = istft(y, n_fft=512)  # [8, 48000]

            np.allclose(x, x_)  # True
    """
    check_variable_and_dtype(x, 'x', ['complex64', 'complex128'], 'istft')

    x_rank = len(x.shape)
512 513 514 515 516 517
    assert x_rank in [
        2,
        3,
    ], 'x should be a 2D or 3D complex tensor, but got rank of x is {}'.format(
        x_rank
    )
518 519 520 521 522 523 524 525 526 527 528

    if x_rank == 2:  # (batch, n_fft, n_frames)
        x = x.unsqueeze(0)

    if hop_length is None:
        hop_length = int(n_fft // 4)

    if win_length is None:
        win_length = n_fft

    # Assure no gaps between frames.
529 530 531 532 533 534 535 536 537 538 539
    assert (
        0 < hop_length <= win_length
    ), 'hop_length should be in (0, win_length({})], but got {}.'.format(
        win_length, hop_length
    )

    assert (
        0 < win_length <= n_fft
    ), 'win_length should be in (0, n_fft({})], but got {}.'.format(
        n_fft, win_length
    )
540 541 542 543

    n_frames = x.shape[-1]
    fft_size = x.shape[-2]

J
Jiabin Yang 已提交
544
    if _non_static_mode():
545
        if onesided:
546 547 548 549 550
            assert (
                fft_size == n_fft // 2 + 1
            ), 'fft_size should be equal to n_fft // 2 + 1({}) when onesided is True, but got {}.'.format(
                n_fft // 2 + 1, fft_size
            )
551
        else:
552 553 554 555 556
            assert (
                fft_size == n_fft
            ), 'fft_size should be equal to n_fft({}) when onesided is False, but got {}.'.format(
                n_fft, fft_size
            )
557 558

    if window is not None:
559 560 561 562 563
        assert (
            len(window.shape) == 1 and len(window) == win_length
        ), 'expected a 1D window tensor of size equal to win_length({}), but got window with shape {}.'.format(
            win_length, window.shape
        )
564
    else:
565 566 567 568 569 570
        window_dtype = (
            paddle.float32
            if x.dtype in [paddle.float32, paddle.complex64]
            else paddle.float64
        )
        window = paddle.ones(shape=(win_length,), dtype=window_dtype)
571 572 573 574 575

    if win_length < n_fft:
        pad_left = (n_fft - win_length) // 2
        pad_right = n_fft - win_length - pad_left
        # FIXME: Input `window` can be a complex tensor but pad does not supprt complex input.
576 577 578
        window = paddle.nn.functional.pad(
            window, pad=[pad_left, pad_right], mode='constant'
        )
579 580

    x = x.transpose(
581 582
        perm=[0, 2, 1]
    )  # switch n_fft to last dim, egs: (batch, num_frames, n_fft)
583 584 585
    norm = 'ortho' if normalized else 'backward'

    if return_complex:
586 587 588
        assert (
            not onesided
        ), 'onesided should be False when input(output of istft) or window is a complex Tensor.'
589 590 591

        out = fft_c2c(x=x, n=None, axis=-1, norm=norm, forward=False, name=None)
    else:
592 593 594
        assert not is_complex(
            window
        ), 'Data type of window should not be complex when return_complex is False.'
595 596

        if onesided is False:
597
            x = x[:, :, : n_fft // 2 + 1]
598 599
        out = fft_c2r(x=x, n=None, axis=-1, norm=norm, forward=False, name=None)

600
    out = paddle.multiply(out, window).transpose(
601 602 603 604 605
        perm=[0, 2, 1]
    )  # (batch, n_fft, num_frames)
    out = overlap_add(
        x=out, hop_length=hop_length, axis=-1
    )  # (batch, seq_length)
606 607 608

    window_envelop = overlap_add(
        x=paddle.tile(
609
            x=paddle.multiply(window, window).unsqueeze(0),
610 611 612 613
            repeat_times=[n_frames, 1],
        ).transpose(
            perm=[1, 0]
        ),  # (n_fft, num_frames)
614
        hop_length=hop_length,
615 616
        axis=-1,
    )  # (seq_length, )
617 618 619

    if length is None:
        if center:
620 621
            out = out[:, (n_fft // 2) : -(n_fft // 2)]
            window_envelop = window_envelop[(n_fft // 2) : -(n_fft // 2)]
622 623 624 625 626 627
    else:
        if center:
            start = n_fft // 2
        else:
            start = 0

628 629
        out = out[:, start : start + length]
        window_envelop = window_envelop[start : start + length]
630 631

    # Check whether the Nonzero Overlap Add (NOLA) constraint is met.
J
Jiabin Yang 已提交
632
    if _non_static_mode() and window_envelop.abs().min().item() < 1e-11:
633 634 635 636 637 638 639 640 641 642
        raise ValueError(
            'Abort istft because Nonzero Overlap Add (NOLA) condition failed. For more information about NOLA constraint please see `scipy.signal.check_NOLA`(https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.check_NOLA.html).'
        )

    out = out / window_envelop

    if x_rank == 2:
        out.squeeze_(0)

    return out