Python scipy.signal.get_window() Examples

The following are 30 code examples of scipy.signal.get_window(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module scipy.signal , or try the search function .
Example #1
Source File: test_spectral.py    From GraphicDesignPatternByPython with MIT License 7 votes vote down vote up
def test_window_external(self):
        x = np.zeros(16)
        x[0] = 1
        x[8] = 1
        f, p = welch(x, 10, 'hann', nperseg=8)
        win = signal.get_window('hann', 8)
        fe, pe = welch(x, 10, win, nperseg=None)
        assert_array_almost_equal_nulp(p, pe)
        assert_array_almost_equal_nulp(f, fe)
        assert_array_equal(fe.shape, (5,))  # because win length used as nperseg
        assert_array_equal(pe.shape, (5,))
        assert_raises(ValueError, welch, x,
                      10, win, nperseg=4)  # because nperseg != win.shape[-1]
        win_err = signal.get_window('hann', 32)
        assert_raises(ValueError, welch, x,
                      10, win_err, nperseg=None)  # win longer than signal 
Example #2
Source File: signal.py    From arlpy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def sweep(f1, f2, duration, fs, method='linear', window=None):
    """Generate frequency modulated sweep.

    :param f1: starting frequency in Hz
    :param f2: ending frequency in Hz
    :param duration: duration of the pulse in s
    :param fs: sampling rate in Hz
    :param method: type of sweep (``'linear'``, ``'quadratic'``, ``'logarithmic'``, ``'hyperbolic'``)
    :param window: window function to use (``None`` means rectangular window)

    For supported window functions, see documentation for :func:`scipy.signal.get_window`.

    >>> import arlpy
    >>> x1 = arlpy.signal.sweep(20000, 30000, duration=0.5, fs=250000)
    >>> x2 = arlpy.signal.sweep(20000, 30000, duration=0.5, fs=250000, window='hamming')
    >>> x2 = arlpy.signal.sweep(20000, 30000, duration=0.5, fs=250000, window=('kaiser', 4.0))
    """
    n = int(round(duration*fs))
    x = _sig.chirp(time(n, fs), f1, duration, f2, method)
    if window is not None:
        w = _sig.get_window(window, n, False)
        x *= w
    return x 
Example #3
Source File: signal.py    From arlpy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def cw(fc, duration, fs, window=None, complex_output=False):
    """Generate a sinusoidal pulse.

    :param fc: frequency of the pulse in Hz
    :param duration: duration of the pulse in s
    :param fs: sampling rate in Hz
    :param window: window function to use (``None`` means rectangular window)
    :param complex_output: True to return complex signal, False for a real signal

    For supported window functions, see documentation for :func:`scipy.signal.get_window`.

    >>> import arlpy
    >>> x1 = arlpy.signal.cw(fc=27000, duration=0.5, fs=250000)
    >>> x2 = arlpy.signal.cw(fc=27000, duration=0.5, fs=250000, window='hamming')
    >>> x3 = arlpy.signal.cw(fc=27000, duration=0.5, fs=250000, window=('kaiser', 4.0))
    """
    n = int(round(duration*fs))
    x = _np.exp(2j*_np.pi*fc*time(n, fs)) if complex_output else _np.sin(2*_np.pi*fc*time(n, fs))
    if window is not None:
        w = _sig.get_window(window, n, False)
        x *= w
    return x 
Example #4
Source File: ns.py    From setk with Apache License 2.0 6 votes vote down vote up
def __init__(self,
                 alpha=0.92,
                 alpha_s=0.9,
                 alpha_d=0.85,
                 b_min=1.66,
                 gamma0=4.6,
                 gamma1=3,
                 zeta0=1.67,
                 xi_min_db=-18,
                 gmin_db=-10,
                 w_mcra=1,
                 h_mcra="hann",
                 beta=1.47,
                 V=15,
                 U=8):
        self.alpha = {"s": alpha_s, "d": alpha_d, "t": alpha}
        self.beta = beta
        self.gamma0, self.gamma1 = gamma0, gamma1
        self.zeta0 = zeta0
        self.b_min = 1 / b_min
        self.xi_min = 10**(xi_min_db / 10)
        self.gain_min = 10**(gmin_db / 10)
        self.w_m = ss.get_window(h_mcra, w_mcra * 2 + 1)
        self.V = V
        self.U = U 
Example #5
Source File: test_utils.py    From mne-features with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_psd():
    n_channels, n_times = data.shape
    _data = data[None, ...]
    # Only test output shape when `method='welch'` or `method='multitaper'`
    # since it is actually just a wrapper for MNE functions:
    psd_welch, _ = power_spectrum(sfreq, _data, psd_method='welch')
    psd_multitaper, _ = power_spectrum(sfreq, _data, psd_method='multitaper')
    psd_fft, freqs_fft = power_spectrum(sfreq, _data, psd_method='fft')
    assert_equal(psd_welch.shape, (1, n_channels, n_times // 2 + 1))
    assert_equal(psd_multitaper.shape, (1, n_channels, n_times // 2 + 1))
    assert_equal(psd_fft.shape, (1, n_channels, n_times // 2 + 1))

    # Compare result obtained with `method='fft'` to the Scipy's result
    # (implementation of Welch's method with rectangular window):
    expected_freqs, expected_psd = signal.welch(data, sfreq,
                                                window=signal.get_window(
                                                    'boxcar', data.shape[-1]),
                                                return_onesided=True,
                                                scaling='density')
    assert_almost_equal(expected_freqs, freqs_fft)
    assert_almost_equal(expected_psd, psd_fft[0, ...]) 
Example #6
Source File: test_spectral.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def test_window_external(self):
        x = np.zeros(16)
        x[0] = 1
        x[8] = 1
        f, p = csd(x, x, 10, 'hann', 8)
        win = signal.get_window('hann', 8)
        fe, pe = csd(x, x, 10, win, nperseg=None)
        assert_array_almost_equal_nulp(p, pe)
        assert_array_almost_equal_nulp(f, fe)
        assert_array_equal(fe.shape, (5,))  # because win length used as nperseg
        assert_array_equal(pe.shape, (5,))
        assert_raises(ValueError, csd, x, x,
                      10, win, nperseg=256)  # because nperseg != win.shape[-1]
        win_err = signal.get_window('hann', 32)
        assert_raises(ValueError, csd, x, x,
              10, win_err, nperseg=None)  # because win longer than signal 
Example #7
Source File: test_spectral.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def test_window_external(self):
        x = np.random.randn(1024)

        fs = 1.0
        window = ('tukey', 0.25)
        nperseg = 16
        noverlap = 2
        f, _, P = spectrogram(x, fs, window, nperseg, noverlap)

        win = signal.get_window(('tukey', 0.25), 16)
        fe, _, Pe = spectrogram(x, fs, win, nperseg=None, noverlap=2)
        assert_array_equal(fe.shape, (9,))  # because win length used as nperseg
        assert_array_equal(Pe.shape, (9,73))
        assert_raises(ValueError, spectrogram, x,
                      fs, win, nperseg=8)  # because nperseg != win.shape[-1]
        win_err = signal.get_window(('tukey', 0.25), 2048)
        assert_raises(ValueError, spectrogram, x,
                      fs, win_err, nperseg=None)  # win longer than signal 
Example #8
Source File: window.py    From recruit with Apache License 2.0 5 votes vote down vote up
def _prep_window(self, **kwargs):
        """
        Provide validation for our window type, return the window
        we have already been validated.
        """

        window = self._get_window()
        if isinstance(window, (list, tuple, np.ndarray)):
            return com.asarray_tuplesafe(window).astype(float)
        elif is_integer(window):
            import scipy.signal as sig

            # the below may pop from kwargs
            def _validate_win_type(win_type, kwargs):
                arg_map = {'kaiser': ['beta'],
                           'gaussian': ['std'],
                           'general_gaussian': ['power', 'width'],
                           'slepian': ['width']}
                if win_type in arg_map:
                    return tuple([win_type] + _pop_args(win_type,
                                                        arg_map[win_type],
                                                        kwargs))
                return win_type

            def _pop_args(win_type, arg_names, kwargs):
                msg = '%s window requires %%s' % win_type
                all_args = []
                for n in arg_names:
                    if n not in kwargs:
                        raise ValueError(msg % n)
                    all_args.append(kwargs.pop(n))
                return all_args

            win_type = _validate_win_type(self.win_type, kwargs)
            # GH #15662. `False` makes symmetric window, rather than periodic.
            return sig.get_window(win_type, window, False).astype(float) 
Example #9
Source File: bf.py    From arlpy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def bartlett(x, fc, sd, shading=None, complex_output=False):
    """Frequency-domain Bartlett beamformer.

    The timeseries data must be 2D with narrowband complex timeseries for each sensor in
    individual rows. The steering delays must also be 2D with a row per steering direction.

    If the timeseries data is specified as 1D array, it is assumed to represent multiple sensors
    at a single time.

    :param x: narrowband complex timeseries data for multiple sensors (row per sensor)
    :param fc: carrier frequency for the array data (Hz)
    :param sd: steering delays (s)
    :param shading: window function to use for array shading (None means no shading)
    :param complex_output: True for complex signal, False for beamformed power
    :returns: beamformer output averaged across time

    >>> from arlpy import bf
    >>> import numpy as np
    >>> # narrowband (1 kHz) timeseries array data assumed to be loaded in x
    >>> # sensor positions assumed to be in pos
    >>> y = bf.bartlett(x, 1000, bf.steering(pos, 1500, np.linspace(-np.pi/2, np.pi/2, 181)))
    """
    if x.ndim == 1:
        x = x[:,_np.newaxis]
    if x.shape[0] != sd.shape[1]:
        raise ValueError('Sensor count mismatch in data and steering vector')
    if fc == 0:
        a = _np.ones_like(sd)
    else:
        a = _np.exp(-2j*_np.pi*fc*sd)/_np.sqrt(sd.shape[1])
    if shading is not None:
        s = _sig.get_window(shading, a.shape[1])
        a *= s/_np.sqrt(_np.mean(s**2))
    if complex_output:
        return a.conj().dot(x)
    else:
        R = covariance(x)
        return _np.array([a[j].conj().dot(R).dot(a[j]).real for j in range(a.shape[0])]) 
Example #10
Source File: test_basic.py    From arlpy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_stft(self):
        x = np.ones((5, 1024))
        y = bf.stft(x, 64)
        self.assertEqual(y.shape, (5, 16, 64))
        self.assertArrayEqual(y[:,:,0], 64*np.ones((5, 16)))
        self.assertArrayEqual(y[:,:,1:], np.zeros((5, 16, 63)))
        y = bf.stft(x, 64, 32)
        self.assertEqual(y.shape, (5, 31, 64))
        self.assertArrayEqual(y[:,:,0], 64*np.ones((5, 31)))
        self.assertArrayEqual(y[:,:,1:], np.zeros((5, 31, 63)))
        y = bf.stft(x, 64, window='hanning')
        self.assertEqual(y.shape, (5, 16, 64))
        self.assertArrayEqual(y[:,:,0], 32*np.ones((5, 16)), precision=0)
        self.assertArrayEqual(y[0,0,:], np.fft.fft(sp.get_window('hanning', 64))) 
Example #11
Source File: stft.py    From TTS-Cube with Apache License 2.0 5 votes vote down vote up
def __init__(self, filter_length=800, hop_length=200, win_length=800,
                 window='hann'):
        super(STFT, self).__init__()
        self.filter_length = filter_length
        self.hop_length = hop_length
        self.win_length = win_length
        self.window = window
        self.forward_transform = None
        scale = self.filter_length / self.hop_length
        fourier_basis = np.fft.fft(np.eye(self.filter_length))

        cutoff = int((self.filter_length / 2 + 1))
        fourier_basis = np.vstack([np.real(fourier_basis[:cutoff, :]),
                                   np.imag(fourier_basis[:cutoff, :])])

        forward_basis = torch.FloatTensor(fourier_basis[:, None, :])
        inverse_basis = torch.FloatTensor(
            np.linalg.pinv(scale * fourier_basis).T[:, None, :])

        if window is not None:
            assert(win_length >= filter_length)
            # get window and zero center pad it to filter_length
            fft_window = get_window(window, win_length, fftbins=True)
            fft_window = pad_center(fft_window, filter_length)
            fft_window = torch.from_numpy(fft_window).float()

            # window the bases
            forward_basis *= fft_window
            inverse_basis *= fft_window

        self.register_buffer('forward_basis', forward_basis.float())
        self.register_buffer('inverse_basis', inverse_basis.float()) 
Example #12
Source File: convolve.py    From tsaug with Apache License 2.0 5 votes vote down vote up
def window(self, w: Union[str, Tuple, List[Union[str, Tuple]]]) -> None:
        WINDOW_ERROR_MSG = (
            "Parameter `window` must be a str or a tuple that can pass to "
            "`scipy.signal.get_window`, or a list of such objects. See "
            "https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.get_window.html "
            "for more details."
        )
        if not isinstance(w, list):
            try:
                get_window(w, 7)
            except TypeError:
                raise TypeError(WINDOW_ERROR_MSG)
            except ValueError:
                raise ValueError(WINDOW_ERROR_MSG)
            except:
                raise RuntimeError(WINDOW_ERROR_MSG)
        else:
            for ww in w:
                try:
                    get_window(ww, 7)
                except TypeError:
                    raise TypeError(WINDOW_ERROR_MSG)
                except ValueError:
                    raise ValueError(WINDOW_ERROR_MSG)
                except:
                    raise RuntimeError(WINDOW_ERROR_MSG)
        self._window = w 
Example #13
Source File: stft.py    From LightSpeech with MIT License 5 votes vote down vote up
def __init__(self, filter_length=800, hop_length=200, win_length=800,
                 window='hann'):
        super(STFT, self).__init__()
        self.filter_length = filter_length
        self.hop_length = hop_length
        self.win_length = win_length
        self.window = window
        self.forward_transform = None
        scale = self.filter_length / self.hop_length
        fourier_basis = np.fft.fft(np.eye(self.filter_length))

        cutoff = int((self.filter_length / 2 + 1))
        fourier_basis = np.vstack([np.real(fourier_basis[:cutoff, :]),
                                   np.imag(fourier_basis[:cutoff, :])])

        forward_basis = torch.FloatTensor(fourier_basis[:, None, :])
        inverse_basis = torch.FloatTensor(
            np.linalg.pinv(scale * fourier_basis).T[:, None, :])

        if window is not None:
            assert(filter_length >= win_length)
            # get window and zero center pad it to filter_length
            fft_window = get_window(window, win_length, fftbins=True)
            fft_window = pad_center(fft_window, filter_length)
            fft_window = torch.from_numpy(fft_window).float()

            # window the bases
            forward_basis *= fft_window
            inverse_basis *= fft_window

        self.register_buffer('forward_basis', forward_basis.float())
        self.register_buffer('inverse_basis', inverse_basis.float()) 
Example #14
Source File: window.py    From Splunking-Crime with GNU Affero General Public License v3.0 5 votes vote down vote up
def _prep_window(self, **kwargs):
        """
        provide validation for our window type, return the window
        we have already been validated
        """

        window = self._get_window()
        if isinstance(window, (list, tuple, np.ndarray)):
            return _asarray_tuplesafe(window).astype(float)
        elif is_integer(window):
            import scipy.signal as sig

            # the below may pop from kwargs
            def _validate_win_type(win_type, kwargs):
                arg_map = {'kaiser': ['beta'],
                           'gaussian': ['std'],
                           'general_gaussian': ['power', 'width'],
                           'slepian': ['width']}
                if win_type in arg_map:
                    return tuple([win_type] + _pop_args(win_type,
                                                        arg_map[win_type],
                                                        kwargs))
                return win_type

            def _pop_args(win_type, arg_names, kwargs):
                msg = '%s window requires %%s' % win_type
                all_args = []
                for n in arg_names:
                    if n not in kwargs:
                        raise ValueError(msg % n)
                    all_args.append(kwargs.pop(n))
                return all_args

            win_type = _validate_win_type(self.win_type, kwargs)
            # GH #15662. `False` makes symmetric window, rather than periodic.
            return sig.get_window(win_type, window, False).astype(float) 
Example #15
Source File: stft.py    From melgan with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, filter_length=800, hop_length=200, win_length=800,
                 window='hann'):
        super(STFT, self).__init__()
        self.filter_length = filter_length
        self.hop_length = hop_length
        self.win_length = win_length
        self.window = window
        self.forward_transform = None
        scale = self.filter_length / self.hop_length
        fourier_basis = np.fft.fft(np.eye(self.filter_length))

        cutoff = int((self.filter_length / 2 + 1))
        fourier_basis = np.vstack([np.real(fourier_basis[:cutoff, :]),
                                   np.imag(fourier_basis[:cutoff, :])])

        forward_basis = torch.FloatTensor(fourier_basis[:, None, :])
        inverse_basis = torch.FloatTensor(
            np.linalg.pinv(scale * fourier_basis).T[:, None, :])

        if window is not None:
            assert(filter_length >= win_length)
            # get window and zero center pad it to filter_length
            fft_window = get_window(window, win_length, fftbins=True)
            fft_window = pad_center(fft_window, filter_length)
            fft_window = torch.from_numpy(fft_window).float()

            # window the bases
            forward_basis *= fft_window
            inverse_basis *= fft_window

        self.register_buffer('forward_basis', forward_basis.float())
        self.register_buffer('inverse_basis', inverse_basis.float()) 
Example #16
Source File: stft.py    From FastSpeech with MIT License 5 votes vote down vote up
def __init__(self, filter_length=800, hop_length=200, win_length=800,
                 window='hann'):
        super(STFT, self).__init__()
        self.filter_length = filter_length
        self.hop_length = hop_length
        self.win_length = win_length
        self.window = window
        self.forward_transform = None
        scale = self.filter_length / self.hop_length
        fourier_basis = np.fft.fft(np.eye(self.filter_length))

        cutoff = int((self.filter_length / 2 + 1))
        fourier_basis = np.vstack([np.real(fourier_basis[:cutoff, :]),
                                   np.imag(fourier_basis[:cutoff, :])])

        forward_basis = torch.FloatTensor(fourier_basis[:, None, :])
        inverse_basis = torch.FloatTensor(
            np.linalg.pinv(scale * fourier_basis).T[:, None, :])

        if window is not None:
            assert(filter_length >= win_length)
            # get window and zero center pad it to filter_length
            fft_window = get_window(window, win_length, fftbins=True)
            fft_window = pad_center(fft_window, filter_length)
            fft_window = torch.from_numpy(fft_window).float()

            # window the bases
            forward_basis *= fft_window
            inverse_basis *= fft_window

        self.register_buffer('forward_basis', forward_basis.float())
        self.register_buffer('inverse_basis', inverse_basis.float()) 
Example #17
Source File: window.py    From elasticintel with GNU General Public License v3.0 5 votes vote down vote up
def _prep_window(self, **kwargs):
        """
        provide validation for our window type, return the window
        we have already been validated
        """

        window = self._get_window()
        if isinstance(window, (list, tuple, np.ndarray)):
            return _asarray_tuplesafe(window).astype(float)
        elif is_integer(window):
            import scipy.signal as sig

            # the below may pop from kwargs
            def _validate_win_type(win_type, kwargs):
                arg_map = {'kaiser': ['beta'],
                           'gaussian': ['std'],
                           'general_gaussian': ['power', 'width'],
                           'slepian': ['width']}
                if win_type in arg_map:
                    return tuple([win_type] + _pop_args(win_type,
                                                        arg_map[win_type],
                                                        kwargs))
                return win_type

            def _pop_args(win_type, arg_names, kwargs):
                msg = '%s window requires %%s' % win_type
                all_args = []
                for n in arg_names:
                    if n not in kwargs:
                        raise ValueError(msg % n)
                    all_args.append(kwargs.pop(n))
                return all_args

            win_type = _validate_win_type(self.win_type, kwargs)
            # GH #15662. `False` makes symmetric window, rather than periodic.
            return sig.get_window(win_type, window, False).astype(float) 
Example #18
Source File: stft.py    From fac-via-ppg with Apache License 2.0 5 votes vote down vote up
def __init__(self, filter_length=800, hop_length=200, win_length=800,
                 window='hann'):
        super(STFT, self).__init__()
        self.filter_length = filter_length
        self.hop_length = hop_length
        self.win_length = win_length
        self.window = window
        self.forward_transform = None
        scale = self.filter_length / self.hop_length
        fourier_basis = np.fft.fft(np.eye(self.filter_length))

        cutoff = int((self.filter_length / 2 + 1))
        fourier_basis = np.vstack([np.real(fourier_basis[:cutoff, :]),
                                   np.imag(fourier_basis[:cutoff, :])])

        forward_basis = torch.FloatTensor(fourier_basis[:, None, :])
        inverse_basis = torch.FloatTensor(
            np.linalg.pinv(scale * fourier_basis).T[:, None, :])

        if window is not None:
            assert(filter_length >= win_length)
            # get window and zero center pad it to filter_length
            fft_window = get_window(window, win_length, fftbins=True)
            fft_window = pad_center(fft_window, filter_length)
            fft_window = torch.from_numpy(fft_window).float()

            # window the bases
            forward_basis *= fft_window
            inverse_basis *= fft_window

        self.register_buffer('forward_basis', forward_basis.float())
        self.register_buffer('inverse_basis', inverse_basis.float()) 
Example #19
Source File: spectrum_analyzer.py    From pyrpl with GNU General Public License v3.0 5 votes vote down vote up
def filter_window(self):
        """
        :return: filter window
        """
        window = sig.get_window(self.window, self.data_length, fftbins=False)
        # empirical value for scaling flattop to sqrt(W)/V
        window/=(np.sum(window)/2)
        return window 
Example #20
Source File: ns.py    From setk with Apache License 2.0 5 votes vote down vote up
def __init__(self,
                 alpha=0.92,
                 delta=5,
                 beta=0.7,
                 alpha_s=0.9,
                 alpha_d=0.85,
                 alpha_p=0.2,
                 gmin_db=-10,
                 xi_min_db=-18,
                 w_mcra=1,
                 w_local=1,
                 w_global=15,
                 h_mcra="hann",
                 h_local="hann",
                 h_global="hann",
                 q_max=0.95,
                 zeta_min_db=-10,
                 zeta_max_db=-5,
                 zeta_p_max_db=10,
                 zeta_p_min_db=0,
                 L=125,
                 M=128):
        self.delta = delta
        self.alpha = {"s": alpha_s, "d": alpha_d, "p": alpha_p, "t": alpha}
        self.gmin = 10**(gmin_db / 10)
        self.beta = beta
        self.w_m = ss.get_window(h_mcra, w_mcra * 2 + 1)
        self.w_g = ss.get_window(h_global, w_global * 2 + 1)
        self.w_l = ss.get_window(h_local, w_local * 2 + 1)
        self.xi_min = 10**(xi_min_db / 10)
        self.zeta_min = 10**(zeta_min_db / 10)
        self.zeta_max = 10**(zeta_max_db / 10)
        self.zeta_p_min = 10**(zeta_p_min_db / 10)
        self.zeta_p_max = 10**(zeta_p_max_db / 10)
        self.L = L
        self.M = M
        self.q_max = q_max 
Example #21
Source File: stft.py    From Tacotron2-Mandarin with MIT License 5 votes vote down vote up
def __init__(self, filter_length=800, hop_length=200, win_length=800,
                 window='hann'):
        super(STFT, self).__init__()
        self.filter_length = filter_length
        self.hop_length = hop_length
        self.win_length = win_length
        self.window = window
        self.forward_transform = None
        scale = self.filter_length / self.hop_length
        fourier_basis = np.fft.fft(np.eye(self.filter_length))

        cutoff = int((self.filter_length / 2 + 1))
        fourier_basis = np.vstack([np.real(fourier_basis[:cutoff, :]),
                                   np.imag(fourier_basis[:cutoff, :])])

        forward_basis = torch.FloatTensor(fourier_basis[:, None, :])
        inverse_basis = torch.FloatTensor(
            np.linalg.pinv(scale * fourier_basis).T[:, None, :])

        if window is not None:
            assert (filter_length >= win_length)
            # get window and zero center pad it to filter_length
            fft_window = get_window(window, win_length, fftbins=True)
            fft_window = pad_center(fft_window, filter_length)
            fft_window = torch.from_numpy(fft_window).float()

            # window the bases
            forward_basis *= fft_window
            inverse_basis *= fft_window

        self.register_buffer('forward_basis', forward_basis.float())
        self.register_buffer('inverse_basis', inverse_basis.float()) 
Example #22
Source File: utils.py    From pycbc with GNU General Public License v3.0 5 votes vote down vote up
def fd_taper(out, start, end, beta=8, side='left'):
    """Applies a taper to the given FrequencySeries.

    A half-kaiser window is used for the roll-off.

    Parameters
    ----------
    out : FrequencySeries
        The ``FrequencySeries`` to taper.
    start : float
        The frequency (in Hz) to start the taper window.
    end : float
        The frequency (in Hz) to end the taper window.
    beta : int, optional
        The beta parameter to use for the Kaiser window. See
        ``scipy.signal.kaiser`` for details. Default is 8.
    side : {'left', 'right'}
        The side to apply the taper to. If ``'left'`` (``'right'``), the taper
        will roll up (down) between ``start`` and ``end``, with all values
        before ``start`` (after ``end``) set to zero. Default is ``'left'``.

    Returns
    -------
    FrequencySeries
        The tapered frequency series.
    """
    out = out.copy()
    width = end - start
    winlen = 2 * int(width / out.delta_f)
    window = Array(signal.get_window(('kaiser', beta), winlen))
    kmin = int(start / out.delta_f)
    kmax = kmin + winlen//2
    if side == 'left':
        out[kmin:kmax] *= window[:winlen//2]
        out[:kmin] *= 0.
    elif side == 'right':
        out[kmin:kmax] *= window[winlen//2:]
        out[kmax:] *= 0.
    else:
        raise ValueError("unrecognized side argument {}".format(side))
    return out 
Example #23
Source File: mel.py    From onsets-and-frames with MIT License 5 votes vote down vote up
def __init__(self, filter_length, hop_length, win_length=None, window='hann'):
        super(STFT, self).__init__()
        if win_length is None:
            win_length = filter_length

        self.filter_length = filter_length
        self.hop_length = hop_length
        self.win_length = win_length
        self.window = window
        self.forward_transform = None
        fourier_basis = np.fft.fft(np.eye(self.filter_length))

        cutoff = int((self.filter_length / 2 + 1))
        fourier_basis = np.vstack([np.real(fourier_basis[:cutoff, :]),
                                   np.imag(fourier_basis[:cutoff, :])])

        forward_basis = torch.FloatTensor(fourier_basis[:, None, :])

        if window is not None:
            assert(filter_length >= win_length)
            # get window and zero center pad it to filter_length
            fft_window = get_window(window, win_length, fftbins=True)
            fft_window = pad_center(fft_window, filter_length)
            fft_window = torch.from_numpy(fft_window).float()

            # window the bases
            forward_basis *= fft_window

        self.register_buffer('forward_basis', forward_basis.float()) 
Example #24
Source File: stft_test.py    From asteroid with MIT License 5 votes vote down vote up
def test_perfect_resyn_window(fb_config, analysis_window_name):
    """ Unit test perfect reconstruction """
    kernel_size = fb_config['kernel_size']
    window = get_window(analysis_window_name, kernel_size)

    enc = Encoder(STFTFB(**fb_config, window=window))
    # Compute window for perfect resynthesis
    synthesis_window = perfect_synthesis_window(enc.filterbank.window,
                                                enc.stride)
    dec = Decoder(STFTFB(**fb_config, window=synthesis_window))
    inp_wav = torch.ones(1, 1, 32000)
    out_wav = dec(enc(inp_wav))[:, :, kernel_size: -kernel_size]
    inp_test = inp_wav[:, :, kernel_size: -kernel_size]
    testing.assert_allclose(inp_test,
                            out_wav) 
Example #25
Source File: bf.py    From arlpy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def stft(x, nfft, overlap=0, window=None):
    """Compute short time Fourier transform (STFT) of array data.

    :param x: passband real timeseries data for multiple sensors (row per sensor)
    :param nfft: window length in samples
    :param overlap: number of samples of overlap between windows
    :param window: window function to use (None means rectangular window)
    :returns: 3d array of time x frequency x sensor

    For supported window functions, see documentation for :func:`scipy.signal.get_window`.
    """
    n, m = x.shape
    if overlap == 0:
        if m % nfft != 0:
            m = (m//nfft)*nfft
        x = _np.reshape(x[:,:m], (n, -1, nfft))
    elif overlap > 0 and overlap < nfft:
        p = (m-overlap)//(nfft-overlap)
        y = _np.empty((n, p, nfft))
        for j in range(p):
            y[:,j,:] = x[:,(nfft-overlap)*j:(nfft-overlap)*j+nfft]
        x = y
    else:
        raise ValueError('overlap must be in the range [0,nfft)')
    if window is not None:
        x *= _sig.get_window(window, nfft)
    x = _np.fft.fft(x, axis=-1)
    return x 
Example #26
Source File: window.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def _prep_window(self, **kwargs):
        """
        provide validation for our window type, return the window
        we have already been validated
        """

        window = self._get_window()
        if isinstance(window, (list, tuple, np.ndarray)):
            return com._asarray_tuplesafe(window).astype(float)
        elif is_integer(window):
            import scipy.signal as sig

            # the below may pop from kwargs
            def _validate_win_type(win_type, kwargs):
                arg_map = {'kaiser': ['beta'],
                           'gaussian': ['std'],
                           'general_gaussian': ['power', 'width'],
                           'slepian': ['width']}
                if win_type in arg_map:
                    return tuple([win_type] + _pop_args(win_type,
                                                        arg_map[win_type],
                                                        kwargs))
                return win_type

            def _pop_args(win_type, arg_names, kwargs):
                msg = '%s window requires %%s' % win_type
                all_args = []
                for n in arg_names:
                    if n not in kwargs:
                        raise ValueError(msg % n)
                    all_args.append(kwargs.pop(n))
                return all_args

            win_type = _validate_win_type(self.win_type, kwargs)
            # GH #15662. `False` makes symmetric window, rather than periodic.
            return sig.get_window(win_type, window, False).astype(float) 
Example #27
Source File: stft.py    From tn2-wg with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, filter_length=800, hop_length=200, win_length=800,
                 window='hann'):
        super(STFT, self).__init__()
        self.filter_length = filter_length
        self.hop_length = hop_length
        self.win_length = win_length
        self.window = window
        self.forward_transform = None
        scale = self.filter_length / self.hop_length
        fourier_basis = np.fft.fft(np.eye(self.filter_length))

        cutoff = int((self.filter_length / 2 + 1))
        fourier_basis = np.vstack([np.real(fourier_basis[:cutoff, :]),
                                   np.imag(fourier_basis[:cutoff, :])])

        forward_basis = torch.FloatTensor(fourier_basis[:, None, :])
        inverse_basis = torch.FloatTensor(
            np.linalg.pinv(scale * fourier_basis).T[:, None, :])

        if window is not None:
            assert(filter_length >= win_length)
            # get window and zero center pad it to filter_length
            fft_window = get_window(window, win_length, fftbins=True)
            fft_window = pad_center(fft_window, filter_length)
            fft_window = torch.from_numpy(fft_window).float()

            # window the bases
            forward_basis *= fft_window
            inverse_basis *= fft_window

        self.register_buffer('forward_basis', forward_basis.float())
        self.register_buffer('inverse_basis', inverse_basis.float()) 
Example #28
Source File: test_spectral.py    From Computable with MIT License 5 votes vote down vote up
def test_window_external(self):
        x = np.zeros(16)
        x[0] = 1
        f, p = periodogram(x, 10, 'hanning')
        win = signal.get_window('hanning', 16)
        fe, pe = periodogram(x, 10, win)
        assert_array_almost_equal_nulp(p, pe)
        assert_array_almost_equal_nulp(f, fe) 
Example #29
Source File: test_spectral.py    From Computable with MIT License 5 votes vote down vote up
def test_window_external(self):
        x = np.zeros(16)
        x[0] = 1
        x[8] = 1
        f, p = welch(x, 10, 'hanning', 8)
        win = signal.get_window('hanning', 8)
        fe, pe = welch(x, 10, win, 8)
        assert_array_almost_equal_nulp(p, pe)
        assert_array_almost_equal_nulp(f, fe) 
Example #30
Source File: test_windows.py    From Computable with MIT License 5 votes vote down vote up
def test_boxcar(self):
        w = signal.get_window('boxcar', 12)
        assert_array_equal(w, np.ones_like(w))