Python scipy.signal.tukey() Examples

The following are 15 code examples of scipy.signal.tukey(). 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: wrapper.py    From THOR with MIT License 6 votes vote down vote up
def _make_template(self, crop):
        temp = {}
        temp['raw'] = crop.to(self.device)
        temp['im'] = torch_to_img(crop)

        temp['kernel'] = self._net.featureExtract(temp['raw'])
        temp['reg'] = self._net.conv_r1(temp['kernel'])
        temp['cls'] = self._net.conv_cls1(temp['kernel'])
        t_s = temp['reg'].data.size()[-1]

        temp['reg_anc'] = temp['reg'].view(self._net.anchor*4, self._net.feature_out, t_s, t_s)
        temp['cls_anc'] = temp['cls'].view(self._net.anchor*2, self._net.feature_out, t_s, t_s)

        # add the tukey window to the temp for comparison
        alpha = self._cfg.tukey_alpha
        win = np.outer(tukey(self.kernel_sz, alpha), tukey(self.kernel_sz, alpha))
        temp['compare'] = temp['kernel'] * torch.Tensor(win).to(self.device)
        return temp 
Example #2
Source File: test_basic.py    From arlpy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_cw(self):
        self.assertArrayEqual(signal.cw(10000, 0.1, 50000), np.sin(2*np.pi*10000*np.arange(5000, dtype=np.float)/50000), precision=6)
        self.assertArrayEqual(signal.cw(10000, 0.1, 50000, complex_output=True), np.exp(2j*np.pi*10000*np.arange(5000, dtype=np.complex)/50000), precision=6)
        self.assertArrayEqual(signal.cw(10000, 0.1, 50000, ('tukey', 0.1)), sp.tukey(5000, 0.1)*np.sin(2*np.pi*10000*np.arange(5000, dtype=np.float)/50000), precision=2) 
Example #3
Source File: test_basic.py    From arlpy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_sweep(self):
        self.assertArrayEqual(signal.sweep(5000, 10000, 0.1, 50000), sp.chirp(np.arange(5000, dtype=np.float)/50000, 5000, 0.1, 10000, 'linear'))
        self.assertArrayEqual(signal.sweep(5000, 10000, 0.1, 50000, 'hyperbolic'), sp.chirp(np.arange(5000, dtype=np.float)/50000, 5000, 0.1, 10000, 'hyperbolic'))
        self.assertArrayEqual(signal.sweep(5000, 10000, 0.1, 50000, window=('tukey', 0.1)), sp.tukey(5000, 0.1)*sp.chirp(np.arange(5000, dtype=np.float)/50000, 5000, 0.1, 10000), precision=2) 
Example #4
Source File: dataset.py    From pytorch-asr with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, sample_rate, window_shift, window_size, nfft, window=tukey):
        self.nfft = nfft
        self.window_size = int(sample_rate * window_size)
        self.window_shift = int(sample_rate * window_shift)
        self.window = torch.FloatTensor(window(self.window_size)) 
Example #5
Source File: wrapper.py    From THOR with MIT License 5 votes vote down vote up
def _make_template(self, crop):
        temp = {}
        temp['raw'] = crop.to(self.device)
        temp['im'] = torch_to_img(crop)
        temp['kernel'] = self._net.feature(temp['raw'])

        # add the tukey window to the temp for comparison
        alpha = self._cfg.tukey_alpha
        win = np.outer(tukey(self.kernel_sz, alpha), tukey(self.kernel_sz, alpha))
        temp['compare'] = temp['kernel'] * torch.Tensor(win).to(self.device)
        return temp 
Example #6
Source File: wrapper.py    From THOR with MIT License 5 votes vote down vote up
def _make_template(self, crop):
        temp = {}
        temp['raw'] = crop.to(self.device)
        temp['im'] = torch_to_img(crop)
        temp['kernel'] = self._net.template(temp['raw'])

        # add the tukey window to the temp for comparison
        alpha = self._cfg.tukey_alpha
        win = np.outer(tukey(self.kernel_sz, alpha), tukey(self.kernel_sz, alpha))
        temp['compare'] = temp['kernel'] * torch.Tensor(win).to(self.device)
        return temp 
Example #7
Source File: dictionary.py    From alphacsc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def tukey_window(n_times_atom):
    window = signal.tukey(n_times_atom)
    window[0] = 1e-9
    window[-1] = 1e-9
    return window 
Example #8
Source File: check_detrend_performance.py    From NoisePy with MIT License 5 votes vote down vote up
def taper1(data):
    '''
    apply a cosine taper using tukey window
    '''
    ndata = np.zeros(shape=data.shape,dtype=data.dtype)
    if data.ndim == 1:
        npts  = data.shape[0]
        win   = signal.tukey(npts,alpha=0.05)
        ndata = data*win
    elif data.ndim == 2:
        npts = data.shape[1]
        win   = signal.tukey(npts,alpha=0.05)
        for ii in range(data.shape[0]):
            ndata[ii] = data[ii]*win
    return ndata 
Example #9
Source File: check_detrend_performance.py    From NoisePy with MIT License 5 votes vote down vote up
def taper(data):
    '''
    apply a cosine taper using tukey window
    '''
    #ndata = np.zeros(shape=data.shape,dtype=data.dtype)
    if data.ndim == 1:
        npts = data.shape[0]

        # window length 
        if npts*0.05>20:wlen = 20
        else:wlen = npts*0.05
        
        # taper values
        func = _get_function_from_entry_point('taper', 'hann')
        if 2*wlen == npts:
            taper_sides = func(2*wlen)
        else:
            taper_sides = func(2*wlen + 1)

        # taper window
        win  = np.hstack((taper_sides[:wlen], np.ones(npts-2*wlen),taper_sides[len(taper_sides) - wlen:]))
        data = data*win
    elif data.ndim == 2:
        npts = data.shape[1]
    
        # window length 
        if npts*0.05>20:wlen = 20
        else:wlen = npts*0.05
        
        # taper values
        func = _get_function_from_entry_point('taper', 'hann')
        if 2*wlen == npts:
            taper_sides = func(2*wlen)
        else:
            taper_sides = func(2*wlen + 1)

        # taper window
        win  = np.hstack((taper_sides[:wlen], np.ones(npts-2*wlen),taper_sides[len(taper_sides) - wlen:]))
        for ii in range(data.shape[0]):
            data[ii] = data[ii]*win
    return data 
Example #10
Source File: check_detrend_demean_taper.py    From NoisePy with MIT License 5 votes vote down vote up
def taper1(data):
    '''
    apply a cosine taper using tukey window
    '''
    ndata = np.zeros(shape=data.shape,dtype=data.dtype)
    if data.ndim == 1:
        npts  = data.shape[0]
        win   = signal.tukey(npts,alpha=0.05)
        ndata = data*win
    elif data.ndim == 2:
        npts = data.shape[1]
        win   = signal.tukey(npts,alpha=0.05)
        for ii in range(data.shape[0]):
            ndata[ii] = data[ii]*win
    return ndata 
Example #11
Source File: noise_module.py    From NoisePy with MIT License 5 votes vote down vote up
def clean_up(corr,sampling_rate,freqmin,freqmax):
    if corr.ndim == 2:
        axis = 1
    else:
        axis = 0
    corr = scipy.signal.detrend(corr,axis=axis,type='constant')
    corr = scipy.signal.detrend(corr,axis=axis,type='linear')
    percent = sampling_rate * 20 / corr.shape[axis]
    #taper = scipy.signal.tukey(corr.shape[axis],percent)
    taper = tukey(corr.shape[axis],percent)
    corr *= taper
    corr = bandpass(corr,freqmin,freqmax,sampling_rate,zerophase=True)
    return corr 
Example #12
Source File: noise_module.py    From NoisePy with MIT License 5 votes vote down vote up
def clean_up(corr, sampling_rate, freqmin, freqmax):
    if corr.ndim == 2:
        axis = 1
    else:
        axis = 0
    corr = scipy.signal.detrend(corr, axis=axis, type='constant')
    corr = scipy.signal.detrend(corr, axis=axis, type='linear')
    percent = np.min([sampling_rate * 20 / corr.shape[axis],0.05])
    taper = scipy.signal.tukey(corr.shape[axis], percent)
    corr *= taper
    corr = bandpass(corr, freqmin, freqmax, sampling_rate, zerophase=True)
    return corr 
Example #13
Source File: wrapper.py    From AutoMask with MIT License 5 votes vote down vote up
def _make_template(self, crop):
        temp = {}
        temp['raw'] = crop.to(self.device)
        temp['im'] = torch_to_img(crop)
        temp['kernel'] = self._net.template(temp['raw'])

        # add the tukey window to the temp for comparison
        alpha = self._cfg.tukey_alpha
        win = np.outer(tukey(self.kernel_sz, alpha), tukey(self.kernel_sz, alpha))
        temp['compare'] = temp['kernel'] * torch.Tensor(win).to(self.device)
        return temp 
Example #14
Source File: signal.py    From alphacsc with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def split_signal(X, n_splits=1, apply_window=True):
    """Split the signal in ``n_splits`` chunks for faster training.

    This function can be used to accelerate the dictionary learning algorithm
    by creating independent chunks that can be processed in parallel. This can
    bias the estimation and can create border artifacts so the number of chunks
    should be kept as small as possible (`e.g.` equal to ``n_jobs``).

    Also, it is advised to not use the result of this function to
    call the ``DictionaryLearning.transform`` method, as it would return an
    approximate reduction of the original signal in the sparse basis.

    Note that this is a lossy operation, as all chunks will have length
    ``n_times // n_splits`` and the last ``n_times % n_splits`` samples are
    discarded.

    Parameters
    ----------
    X : ndarray, shape (n_channels, n_times)
        Signal to be split. It should be a single signal.
    n_splits : int (default: 1)
        Number of splits to create from the original signal. Default is 1.
    apply_window : bool (default: True)
        If set to True (default), a tukey window is applied to each split to
        reduce the border artifacts by reducing the weights of the chunk
        borders.

    Return
    ------
    X_split: ndarray, shape (n_splits, n_channels, n_times // n_splits)
        The signal splitted in ``n_splits``.
    """
    assert X.ndim == 2, (
        "This splitting utility is only designed for one multivariate "
        "signal (n_channels, n_times). Found X.ndim={}.".format(X.ndim))

    n_splits = int(n_splits)
    assert n_splits > 0, "The number of splits should be large than 0."

    n_channels, n_times = X.shape
    n_times = n_times // n_splits
    X_split = X[:, :n_splits * n_times]
    X_split = X_split.reshape(n_channels, n_splits, n_times).swapaxes(0, 1)

    # Apply a window to the signal to reduce the border artifacts
    if apply_window:
        X_split *= tukey(n_times, alpha=0.1)[None, None, :]

    return X_split 
Example #15
Source File: whitening.py    From alphacsc with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def whitening(X, ordar=10, block_length=256, sfreq=1., zero_phase=True,
              plot=False, use_fooof=False):
    n_trials, n_channels, n_times = X.shape

    ar_model = Arma(ordar=ordar, ordma=0, fs=sfreq, block_length=block_length)
    ar_model.periodogram(X.reshape(-1, n_times), hold=False, mean_psd=True)

    if use_fooof:  # pragma: no cover
        # Fit the psd with a 1/f^a background model plus a gaussian mixture.
        # We keep only the background model
        # (pip install fooof)
        from fooof import FOOOF
        fm = FOOOF(background_mode='fixed', verbose=False)
        power_spectrum = ar_model.psd[-1][0]
        freqs = np.linspace(0, sfreq / 2.0, len(power_spectrum))

        fm.fit(freqs, power_spectrum, freq_range=None)
        # repete first point, which is f_0
        bg_fit = np.r_[fm._bg_fit[0], fm._bg_fit][None, :]
        ar_model.psd.append(np.power(10, bg_fit))

    if zero_phase:
        ar_model.psd[-1] = np.sqrt(ar_model.psd[-1])
    ar_model.estimate()

    # apply the whitening for zero-phase filtering
    X_white = apply_whitening(ar_model, X, zero_phase=zero_phase, mode='same')
    assert X_white.shape == X.shape

    # removes edges
    n_times_white = X_white.shape[-1]
    X_white *= signal.tukey(n_times_white,
                            alpha=3 / float(n_times_white))[None, None, :]

    if plot:  # pragma: no cover
        import matplotlib.pyplot as plt
        # plot the Power Spectral Density (PSD) before/after
        ar_model.arma2psd(hold=True)
        if zero_phase:
            ar_model.psd[-2] **= 2
            ar_model.psd[-1] **= 2
        ar_model.periodogram(
            X_white.reshape(-1, n_times), hold=True, mean_psd=True)
        labels = ['signal', 'model AR', 'signal white']
        if use_fooof:
            labels = ['signal', 'FOOOF fit', 'model AR', 'signal white']
        ar_model.plot('periodogram before/after whitening',
                      labels=labels, fscale='lin')
        plt.legend(loc='lower left')

    return ar_model, X_white