Пример #1
0
    def _design(self):
        if not self.ripple and 'ripple' in self.filter_parameters:
            self.ripple = self.filter_parameters['ripple']
        elif not self.ripple and 'ripple' not in self.filter_parameters:
            raise ValueError("Needs a ripple value.")

        if self.already_normalized_Wn:
            self.Z, self.P, self.K = signal.cheby1(self.N, self.ripple, self.Wn,
                                                   self.filter_kind, analog=False,
                                                   output='zpk')
        else:
            self.Z, self.P, self.K = signal.cheby1(self.N, self.ripple, self.normalize_Wn(),
                                                   self.filter_kind, analog=False,
                                                   output='zpk')
Пример #2
0
def decimate_coeffs(q, n=None, ftype='iir'):

    q = int(q)

    if n is None:
        if ftype == 'fir':
            n = 30
        else:
            n = 8

    if ftype == 'fir':
        coeffs = GlobalVars.decimate_fir_coeffs
        if (n, 1./q) not in coeffs:
            coeffs[n, 1./q] = signal.firwin(n+1, 1./q, window='hamming')

        b = coeffs[n, 1./q]
        return b, [1.], n

    else:
        coeffs = GlobalVars.decimate_iir_coeffs
        if (n, 0.05, 0.8/q) not in coeffs:
            coeffs[n, 0.05, 0.8/q] = signal.cheby1(n, 0.05, 0.8/q)

        b, a = coeffs[n, 0.05, 0.8/q]
        return b, a, n
Пример #3
0
 def bandpass(x, y):
     cutoff1 = int(x)
     cutoff2 = int(y)
     fs = 48000
     Wn = [cutoff1/(fs/2), cutoff2/(fs/2)]
     b, a = signal.cheby1(1, 1, Wn, 'bandpass', analog=False)
     return b, a
def test_decimate():
    from numpy import arange,sin
    from scipy.signal import decimate, resample, cheby1, lfilter, filtfilt
    t = arange(0,30)
    q = 2
    n = 8
    print(t)
    print(decimate(t,2))
    print(resample(t, len(t)/2))
    t2 = sin(t)
    print(t2)
    print(len(t2))
    d2 = decimate(t2,2, ftype='fir')
    print(d2)
    print(len(d2))
    b, a = cheby1(n, 0.05, 0.8 / q)
    print(b,a)
    y = filtfilt(b, a, t2)
    print(y)
    sl = [slice(None)] * y.ndim

    sl[-1] = slice(None, None, -q)
    print(sl)
    print(y[sl])
    print(t2[sl])
    #r2 = resample(t2, len(t2)/2)
    #print(r2)
    #print(len(r2))
    assert(False)
Пример #5
0
def decimate_coeffs(q, n=None, ftype='iir'):

    if type(q) != type(1):
        raise Error, "q should be an integer"

    if n is None:
        if ftype == 'fir':
            n = 30
        else:
            n = 8
            
    if ftype == 'fir':
        coeffs = GlobalVars.decimate_fir_coeffs
        if (n, 1./q) not in coeffs:
            coeffs[n,1./q] = signal.firwin(n+1, 1./q, window='hamming')
        
        b = coeffs[n,1./q]
        return b, [1.], n 

    else:
        coeffs = GlobalVars.decimate_iir_coeffs
        if (n,0.05,0.8/q) not in coeffs:
            coeffs[n,0.05,0.8/q] = signal.cheby1(n, 0.05, 0.8/q)
           
        b, a = coeffs[n,0.05,0.8/q]
        return b, a, n
Пример #6
0
    def data_hpass(self, x, Wp, srate):
        ''' High-pass filter '''
        Wp = float(Wp*2/srate)
        Ws = Wp*float(self.lineEdit_19.text())
        Rp = float(self.lineEdit_17.text())
        Rs = float(self.lineEdit_18.text())

        tempstring = self.lineEdit_16.text()
        if tempstring == 'auto':
            if self.comboBox_2.currentIndex() == 0:
                (norder, Wn) = buttord(Wp, Ws, Rp, Rs)
            elif self.comboBox_2.currentIndex() == 1:
                (norder, Wn) = ellipord(Wp, Ws, Rp, Rs)
            else:
                (norder, Wn) = cheb1ord(Wp, Ws, Rp, Rs)
        else:
            norder = float(tempstring)
            Wn = Wp

        if self.comboBox_2.currentIndex() == 0:
            (b, a)  =  butter(norder, Wn, btype = 'high')
        elif self.comboBox_2.currentIndex() == 1:
            (b, a)  =  ellip(norder, Rp, Rs, Wn)
        else:
            (b, a)  =  cheby1(norder, Rp, Wn)


        y  =  filtfilt(b, a, x)

        return(y)
Пример #7
0
def decimate(x, q, n=None, ftype='iir', axis=-1, zero_phase=False):
    """
    Downsample the signal by using a filter.

    By default, an order 8 Chebyshev type I filter is used.  A 30 point FIR
    filter with hamming window is used if `ftype` is 'fir'.

    Parameters
    ----------
    x : ndarray
        The signal to be downsampled, as an N-dimensional array.
    q : int
        The downsampling factor.
    n : int, optional
        The order of the filter (1 less than the length for 'fir').
    ftype : str {'iir', 'fir'}, optional
        The type of the lowpass filter.
    axis : int, optional
        The axis along which to decimate.
    zero_phase : bool
        Prevent phase shift by filtering with ``filtfilt`` instead of ``lfilter``.
    Returns
    -------
    y : ndarray
        The down-sampled signal.

    See also
    --------
    resample

    Notes
    -----
    The ``zero_phase`` keyword was added in 0.17.0.
    The possibility to use instances of ``lti`` as ``ftype`` was added in 0.17.0.

    """

    if not isinstance(q, int):
        raise TypeError("q must be an integer")

    if ftype == 'fir':
        if n is None:
            n = 30
        system = lti(firwin(n + 1, 1. / q, window='hamming'), 1.)

    elif ftype == 'iir':
        if n is None:
            n = 8
        system = lti(*cheby1(n, 0.05, 0.8 / q))
    else:
        system = ftype

    if zero_phase:
        y = filtfilt(system.num, system.den, x, axis=axis)
    else:
        y = lfilter(system.num, system.den, x, axis=axis)

    sl = [slice(None)] * y.ndim
    sl[axis] = slice(None, None, q)
    return y[sl]
Пример #8
0
 def HPmin(self, fil_dict):
     self._get_params(fil_dict)
     self.N, self.F_PBC = cheb1ord(self.F_PB,self.F_SB, self.A_PB,self.A_SB,
                                                       analog=self.analog)
     if not self._test_N():
         return -1
     self._save(fil_dict, sig.cheby1(self.N, self.A_PB, self.F_PBC,
                     btype='highpass', analog=self.analog, output=self.FRMT))
Пример #9
0
 def BSmin(self, fil_dict):
     self._get_params(fil_dict)
     self.N, self.F_PBC = cheb1ord([self.F_PB, self.F_PB2],
         [self.F_SB, self.F_SB2], self.A_PB,self.A_SB, analog = self.analog)
     if not self._test_N():
         return -1
     self._save(fil_dict, sig.cheby1(self.N, self.A_PB, self.F_PBC,
                     btype='bandstop', analog=self.analog, output=self.FRMT))
Пример #10
0
def cheby_filter(frames):
    b, a = signal.cheby1(order, rp, Wn, 'bandpass', analog=False)
    print "Filtering..."
    frames = signal.filtfilt(b, a, frames, axis=0)
    #for i in range(frames.shape[-1]):
    #    frames[:, i] = signal.filtfilt(b, a, frames[:, i])
    print "Done!"
    return frames
Пример #11
0
 def __init__(self, threshold_freq, order=2, design='cheby1'):
     """
     :param threshold_freq: Threshold frequency to filter out, as a fraction of sampling freq.  E.g. 0.1
     """
     self.b, self.a = \
         butter(N=order, Wn=threshold_freq, btype='low') if design == 'butter' else \
         cheby1(N=order, rp=0.1, Wn=threshold_freq, btype='low') if design == 'cheby1' else \
         bad_value(design)
     self.filter_state = lfilter_zi(b=self.b, a=self.a)
Пример #12
0
def decimate(x, q, n=None, ftype='iir', axis=-1):
    """Downsample the signal x by an integer factor q, using an order n filter

    By default, an order 8 Chebyshev type I filter is used or a 30 point FIR 
    filter with hamming window if ftype is 'fir'.

    (port to python of the GNU Octave function decimate.)

    Inputs:
        x -- the signal to be downsampled (N-dimensional array)
        q -- the downsampling factor
        n -- order of the filter (1 less than the length of the filter for a
             'fir' filter)
        ftype -- type of the filter; can be 'iir' or 'fir'
        axis -- the axis along which the filter should be applied

    Outputs:
        y -- the downsampled signal

    """

    if type(q) != type(1):
        raise TypeError("q should be an integer")

    if n is None:
        if ftype == 'fir':
            n = 30
        else:
            n = 8
    if ftype == 'fir':
        # PBS - This method must be verified
        b = firwin(n+1, 1./q, window='hamming')
        y = lfilter(b, 1., x, axis=axis)
    else:
        (b, a) = cheby1(n, 0.05, 0.8/q)

        # reshape the data to 2D with time on the 2nd dimension
        origshape = x.shape
        y = reshape_to_2d(x,axis)

        # loop over final dimension
        for i in range(y.shape[0]):
            y[i] = filtfilt(b,a,y[i])
        #y = filtfilt2(b,a,y)

        # reshape the data back
        y = reshape_from_2d(y,axis,origshape)

        # This needs to be filtfilt eventually
        #y = lfilter(b, a, x, axis=axis)

    return y.swapaxes(0,axis)[::q].swapaxes(0,axis)
Пример #13
0
def cheby1_lowpass_filter(_data, _frequency_cutoff, _carrier_frequency, order):
    """

    :param _data: The data to be lowpassed
    :param _frequency_cutoff: The frequency cutoff for the filter
    :param _carrier_frequency: The carrier frequency for the filter
    :param order: The order of the filter
    :return: The output of the lowpass filter (entire window)
    """
    nyq = 0.5 * _carrier_frequency
    low = _frequency_cutoff / nyq
    b, a = signal.cheby1(order, 5, low, 'low', analog=False, output='ba')
    return signal.lfilter(b, a, _data)
Пример #14
0
def decimate(x, q, n=None, ftype='iir', axis=-1):
    """
    Downsample the signal by using a filter.

    By default, an order 8 Chebyshev type I filter is used. A 30 point FIR
    filter with hamming window is used if `ftype` is 'fir'.

    Parameters
    ----------
    x : ndarray
    The signal to be downsampled, as an N-dimensional array.
    q : int
    The downsampling factor.
    n : int, optional
    The order of the filter (1 less than the length for 'fir').
    ftype : str {'iir', 'fir'}, optional
    The type of the lowpass filter.
    axis : int, optional
    The axis along which to decimate.

    Returns
    -------
    y : ndarray
    The down-sampled signal.

    See also
    --------
    resample

    """

    if not isinstance(q, int):
        raise TypeError("q must be an integer")

    if n is None:
        if ftype == 'fir':
            n = 30
        else:
            n = 8

    if ftype == 'fir':
        b = signal.firwin(n + 1, 1. / q, window='hamming')
        a = 1.
    else:
        b, a = signal.cheby1(n, 0.05, 0.8 / q)

    y = signal.lfilter(b, a, x, axis=axis)

    sl = [slice(None)] * y.ndim
    sl[axis] = slice(None, None, q)
    return y[sl]
Пример #15
0
 def __init__(self,M_change = 12,fcutoff=0.9,N_filt_order=8,ftype='butter'):
     """
     Object constructor method
     """
     self.M = M_change # Rate change factor M or L
     self.fc = fcutoff*.5 # must be fs/(2*M), but scale by fcutoff
     self.N_forder = N_filt_order
     if ftype.lower() == 'butter':
         self.b, self.a = signal.butter(self.N_forder,2/self.M*self.fc)
     elif ftype.lower() == 'cheby1':
         # Set the ripple to 0.05 dB
         self.b, self.a = signal.cheby1(self.N_forder,0.05,2/self.M*self.fc)
     else:
         print('ftype must be "butter" or "cheby1"')
Пример #16
0
def decimate(q, target):
    b, a = signal.cheby1(4, 0.05, 0.8/q)
    if np.any(np.abs(np.roots(a)) > 1):
        raise ValueError, 'Unstable filter coefficients'
    zf = signal.lfilter_zi(b, a)
    y_remainder = np.array([])
    while True:
        y = np.r_[y_remainder, (yield)]
        remainder = len(y) % q
        if remainder != 0:
            y, y_remainder = y[:-remainder], y[-remainder:]
        else:
            y_remainder = np.array([])
        y, zf = signal.lfilter(b, a, y, zi=zf)
        target(y[::q])
Пример #17
0
def chebyshevplot(fs):
    """
    https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.cheby1.html#scipy.signal.cheby1
    """
    b, a = signal.cheby1(4, 5, 100, 'high', analog=True)
    w, h = signal.freqs(b, a)

    ax = figure().gca()
    ax.semilogx(w, 20*np.log10(abs(h)))
    ax.set_title('Chebyshev Type I frequency response (rp=5)')
    ax.set_xlabel('Frequency [radians / second]')
    ax.set_ylabel('Amplitude [dB]')
    ax.grid(which='both', axis='both')
    ax.axvline(100, color='green')  # cutoff frequency
    ax.axhline(-5, color='green')  # rp
Пример #18
0
def cheby1_highpass_test():
  import numpy as np
  from numpy.testing import assert_almost_equal
  
  from scipy.signal import cheby1

  x = np.arange(10000).reshape(1, -1)
  d = np.sin(x * 2 * np.pi * 1000 / 48000)
  
  out, b, a = filter_high(d)
  
  bref, aref = cheby1(5, 3, 1000/24000., btype='highpass')
  
  assert_almost_equal(-b, bref)
  assert_almost_equal(np.hstack(([1], -a[::-1])), aref)
def blackbox(x, samplerate, axis=0):
    """Some unknown (except that it's LTI) digital system.

    Parameters
    ----------
    x : array_like
        Input signal.
    samplerate : float
        Sampling rate in Hertz.
    axis : int, optional
        The axis of the input data array along which to apply the
        system.  By default, this is the first axis.

    Returns
    -------
    numpy.ndarray
        The output signal.

    """
    # You are not supposed to look!
    b, a = signal.cheby1(8, 0.1, 3400 * 2 / samplerate)
    x = signal.lfilter(b, a, x, axis)
    b, a = signal.cheby1(4, 0.1, 300 * 2 / samplerate, 'high')
    return signal.lfilter(b, a, x, axis)
Пример #20
0
def cheby_filter(frames, low_limit, high_limit):
    nyq = frame_rate/2.0
    low_limit = low_limit/nyq
    high_limit = high_limit/nyq
    order = 4
    rp = 0.1
    Wn = [low_limit, high_limit]
    
    b, a = signal.cheby1(order, rp, Wn, 'bandpass', analog=False)
    print "Filtering..."
    frames = signal.filtfilt(b, a, frames, axis=0)
    #frames = parmap.map(filt, frames.T, b, a)
    #for i in range(frames.shape[-1]):
    #    frames[:, i] = signal.filtfilt(b, a, frames[:, i])
    print "Done!"
    return frames
Пример #21
0
    def data_lpass(self, x, Wp, srate):
        ''' Low-pass filter using various filter type '''
        tempstring = self.lineEdit_16.text()
        
        if tempstring == 'auto':
            Wp = float(Wp*2/srate)
            Ws = Wp*float(self.lineEdit_19.text())
            Rp = float(self.lineEdit_17.text())
            Rs = float(self.lineEdit_18.text())
            
            if self.comboBox_2.currentIndex() == 0:
                (norder, Wn) = buttord(Wp, Ws, Rp, Rs)
            elif self.comboBox_2.currentIndex() == 1:
                (norder, Wn) = ellipord(Wp, Ws, Rp, Rs)
            else:
                (norder, Wn) = cheb1ord(Wp, Ws, Rp, Rs)

        else:
            norder = float(tempstring)
            Wp = float(Wp*2/srate)
            Ws = Wp*2
            self.lineEdit_19.setText(str(Ws/Wp))
            Rp = 3
            self.lineEdit_17.setText(str(Rp))
            Rs = 0.3*norder*20
            self.lineEdit_18.setText(str(Rs))
            
            if self.comboBox_2.currentIndex() == 0:
                (norder, Wn) = buttord(Wp, Ws, Rp, Rs)
            elif self.comboBox_2.currentIndex() == 1:
                (norder, Wn) = ellipord(Wp, Ws, Rp, Rs)
            else:
                (norder, Wn) = cheb1ord(Wp, Ws, Rp, Rs)
            
        if self.comboBox_2.currentIndex() == 0:
            (b, a)  =  butter(norder, Wn)
        elif self.comboBox_2.currentIndex() == 1:
            (b, a)  =  ellip(norder, Rp, Rs, Wn)
        else:
            (b, a)  =  cheby1(norder, Rp, Wn)
            
        
        y  =  filtfilt(b, a, x)
        
        return(y)
Пример #22
0
def iir_basic(a):
  
        filt_type = a["Response Type"]
        
        print('filt_type', filt_type)
        design_method = a["Design_Methode"]
        if design_method == 'Elliptic':
            ftype = 'ellip'
        elif design_method == 'Chebychev 1':
            ftype = 'cheby1'
        elif design_method == 'Chebychev 2':
            ftype = 'cheby2'
        elif design_method == 'Butterworth':
            ftype = 'butter'
#        else: raise_exception
            
        print('design_method', design_method)
        N = a['Order']
        print('order',N)
        fs = a["Fs"]
        F_pass = 2 * a["Fpass"]/fs
#        F_stop = 2 * a[3][2][2]/fs
        F_stop = 0.8
        print('fs','fpass','fstop',fs, F_pass, F_stop)
        A_pass = a["Apass"]
        A_stop = a["Astop"]
#        A_stop = a[4][2][2]
        print('A_pass', 'A_stop', A_pass, A_stop)
#        W = a[5]
#        print('W',W)
        
        if N == 'min':
            b,a = sig.iirdesign(F_pass, F_stop, A_pass, A_stop, analog = False, 
                                ftype = ftype, output = 'ba')            
        else:
            if ftype == 'ellip':
                b,a = sig.ellip(N, A_pass, A_stop, [F_pass, F_stop], btype ='low' )
            elif ftype == 'cheby1':
                b,a = sig.cheby1(N, A_pass, [F_pass, F_stop], btype ='low' )
            elif ftype == 'cheby2':
                b,a = sig.cheby2(N, A_stop, [F_pass, F_stop], btype ='low' )
            elif ftype == 'butter':
                b,a = sig.butter(N, (2 * a["Fc"]/fs), btype ='low' )
        return b, a
Пример #23
0
    def cheby_filter(self, frames, low_limit, high_limit, frame_rate):
        nyq = frame_rate / 2.0
        low_limit = low_limit / nyq
        high_limit = high_limit / nyq
        order = 4
        rp = 0.1 # Ripple in the passband. Maximum allowable ripple
        Wn = [low_limit, high_limit]

        b, a = signal.cheby1(order, rp, Wn, 'bandpass', analog=False)
        print("Filtering...")
        frames = signal.filtfilt(b, a, frames, axis=0)
        # non-working parallized version
        # def filt(pixel, b, a):
        #     return signal.filtfilt(b, a, pixel)
        # frames = parmap.map(filt, frames.T, b, a)
        # for i in range(frames.shape[-1]):
        #    frames[:, i] = 'signal.filtfilt(b, a, frames[:, i])
        print("Done!")
        return frames
Пример #24
0
 def design(self, ripple=None):
     if self.filter_class == 'butterworth':
         self.B, self.A = signal.butter(self.N, self.Wn,
                                        self.filter_type, analog=True,
                                        output='ba')
     elif self.filter_class == 'chebyshev_1':
         if ripple is None or ripple <= 0:
             raise ValueError("Must give a ripple that is > 0")
         self.B, self.A = signal.cheby1(self.N, ripple, self.Wn,
                                        self.filter_type, analog=True,
                                        output='ba')
     elif self.filter_class == 'chebyshev_2':
         self.B, self.A = signal.cheby2(self.N, self.stopband_attenuation, self.Wn,
                                        self.filter_type, analog=True, output='ba')
     elif self.filter_class == 'elliptical':
         self.B, self.A = signal.ellip(self.N, self.passband_attenuation,
                                       self.stopband_attenuation, self.Wn,
                                       self.filter_type, analog=True, output='ba')
     elif self.filter_class == 'bessel':
         self.B, self.A = signal.bessel(self.N, self.Wn, self.filter_type, analog=True)
     else:
         raise NotImplementedError("Computation of {} not implemented yet.".format(self.filter_class))
Пример #25
0
def decimate(x, q, n=None, ftype='iir', axis=-1):
    """downsample the signal x by an integer factor q, using an order n filter
    
    By default, an order 8 Chebyshev type I filter is used or a 30 point FIR 
    filter with hamming window if ftype is 'fir'.

    (port to python of the GNU Octave function decimate.)

    Inputs:
        x -- the signal to be downsampled (N-dimensional array)
        q -- the downsampling factor
        n -- order of the filter (1 less than the length of the filter for a
             'fir' filter)
        ftype -- type of the filter; can be 'iir' or 'fir'
        axis -- the axis along which the filter should be applied
    
    Outputs:
        y -- the downsampled signal

    """

    if type(q) != type(1):
        raise Error, "q should be an integer"

    if n is None:
        if ftype == 'fir':
            n = 30
        else:
            n = 4
    if ftype == 'fir':
        b = firwin(n+1, 1./q, window='hamming')
        y = lfilter(b, 1., x, axis=axis)
    else:
        (b, a) = cheby1(n, 0.05, 0.8/q)

        y = lfilter(b, a, x, axis=axis)

    return y.swapaxes(0,axis)[::q].swapaxes(0,axis)
Пример #26
0
def TPI(dataset,n,rp,wn):
    """
    A function to apply a 13 year Chebyshev low pass filter
    to the unfiltered TPI output, from TPIunfil().  The
    filter design is a digital, type 1 (passband) Chebyshev filter.
    The filter itself is a zero-phase filter, as a forward-in-time
    only filter shifts the signal as it filters (resulting in
    a delayed signal).

    Parameters:
    -----------
    dataset : the data to filter.  Will either be: Had_monthsTPI_uf or
            Acc_monthsTPI_uf (see 'tpi_csv.py').
    n = filter order (Henley et al.: n = 6).
    rp = peak to peak passband ripple. In decibels; positive number.
        (Henley et al.: rp = 13).
    wn = critical frequencies.  Between 0-1, where 1 is
        the Nyquist frequency, pi radians/sample.
        (Henley et al.: wn = 0.1).
    """
    b, a = signal.cheby1(n, rp, wn, btype='low', analog=False, output='ba')
    TPI = signal.filtfilt(b,a,dataset)
    return TPI
Пример #27
0
def TPI(dataset, n, rp, wn):
    """
    A function to apply a 13 year Chebyshev low pass filter
    to the unfiltered TPI output, from TPIunfil().  The
    filter design is a digital, type 1 (passband) Chebyshev filter.
    The filter itself is a zero-phase filter, as a forward-in-time
    only filter shifts the signal as it filters (resulting in
    a delayed signal).

    Parameters:
    -----------
    dataset : the data to filter.  Will either be: Had_monthsTPI_uf or
            Acc_monthsTPI_uf (see 'tpi_csv.py').
    n = filter order (Henley et al.: n = 6).
    rp = peak to peak passband ripple. In decibels; positive number.
        (Henley et al.: rp = 13).
    wn = critical frequencies.  Between 0-1, where 1 is
        the Nyquist frequency, pi radians/sample.
        (Henley et al.: wn = 0.1).
    """
    b, a = signal.cheby1(n, rp, wn, btype='low', analog=False, output='ba')
    TPI = signal.filtfilt(b, a, dataset)
    return TPI
Пример #28
0
Файл: plot.py Проект: mrow4a/UNI
def cheby1_bandpass(low, high, fs, order):
    nyq = 0.5 * fs
    n_low = low / nyq
    n_high = high / nyq
    b, a = cheby1(order,0.2, [n_low, n_high], btype='band', analog=False)
    fig2 = plt.figure()
    plt.title('Digital filter frequency response')
    ax1 = fig2.add_subplot(211)
    w, h = signal.freqz(b,a)
    plt.plot(w/(math.pi*2)*fs, abs(h), 'b')
    plt.ylabel('Amplitude', color='b')
    plt.xlabel('Frequency [freq/sample]')
    ax2 = ax1.twinx()
    angles = np.unwrap(np.angle(h))
    plt.plot(w/(math.pi*2)*fs, angles, 'g')
    plt.ylabel('Angle (radians)', color='g')
    plt.grid()
    plt.axis('tight')
    
    
    
    plt.show()
    return b, a
Пример #29
0
    def __init__(
        self,
        low_freq_cutoff,
        high_freq_cutoff,
        frame_rate,
        order=4,
        rp=0.1,
    ):
        """
        Create Bandpass Filter object with frequency cutoff attributes

        :param low_freq_cutoff: first critical frequency
        :type: float>0
        :param high_freq_cutoff: second critical frequency
        :type: float>0
        :param frame_rate: frame rate of the footage
        :type: float>0
        :param order: the order of the filter
        :type: int
        :param rp: maximum ripple allowed below unity gain in the passband. Specified in decibels, as a positive number
        :type: float>0
        """
        nyq = frame_rate * 0.5
        passband = low_freq_cutoff / nyq
        stopband = high_freq_cutoff / nyq

        numerator, denominator = signal.cheby1(
            order,
            rp,
            Wn=[passband, stopband],
            btype="bandpass",
            analog=False,
        )
        self.numerator, self.denominator = (
            numerator,
            denominator,
        )
Пример #30
0
def make_filter(
                dataset: list,
                bandwidth: list,
                fs: int,
                order: int,
                rp: int) -> list:
    """
    Apply Chebyshev bandpass filter to dataset with bandwidth.

    input:
        dataset - data of EEG signal for filtering;
        bandwidth - list of borders frequencies for filtering in Hz;
        fs - frequency sample rate;
        order - order of Chebyshev filter;
        rp - The maximum ripple allowed below unity gain in the passband;
    Returns:
        list of filtered data of EEG signal.

    """

    #  prepare data of signal
    data = np.array(dataset)
    #  convert border frequencies from Hz
    #  to sampling frequency of the digital system
    nyq = 0.5 * fs
    normal_bandpass = [bandwidth[0] / nyq, bandwidth[1] / nyq]
    #  applying Butterworth filter
    #  b, a = butter(
    b, a = cheby1(
            N=order,
            rp=rp,
            Wn=normal_bandpass,
            btype='bandpass',
            analog=False)
    #  b, a  - Numerator (b) and denominator
    #  (a) polynomials of the IIR filter
    return filtfilt(b, a, data)  # lfilter(b, a, data)
Пример #31
0
def decimate(x, q, n=None, ftype='iir', axis=-1):
    """downsample the signal x by an integer factor q, using an order n filter
    
    By default, an order 8 Chebyshev type I filter is used or a 30 point FIR 
    filter with hamming window if ftype is 'fir'.

    (port to python of the GNU Octave function decimate.)

    Inputs:
        x -- the signal to be downsampled (N-dimensional array)
        q -- the downsampling factor
        n -- order of the filter (1 less than the length of the filter for a
             'fir' filter)
        ftype -- type of the filter; can be 'iir' or 'fir'
        axis -- the axis along which the filter should be applied
    
    Outputs:
        y -- the downsampled signal

    """

    if type(q) != type(1):
        raise Error, "q should be an integer"

    if n is None:
        if ftype == 'fir':
            n = 30
        else:
            n = 8
    if ftype == 'fir':
        b = signal.firwin(n + 1, 1. / q, window='hamming')
        y = signal.lfilter(b, 1., x, axis=axis)
    else:
        (b, a) = signal.cheby1(n, 0.05, 0.8 / q)
        y = signal.lfilter(b, a, x, axis=axis)

    return y.swapaxes(0, axis)[n / 2::q].swapaxes(0, axis)
Пример #32
0
def decimate(s, r, n=None, fir=False):
    """Decimation - decrease sampling rate by r. The decimation process filters 
    the input data s with an order n lowpass filter and then resamples the 
    resulting smoothed signal at a lower rate. By default, decimate employs an 
    eighth-order lowpass Chebyshev Type I filter with a cutoff frequency of 
    0.8/r. It filters the input sequence in both the forward and reverse 
    directions to remove all phase distortion, effectively doubling the filter 
    order. If 'fir' is set to True decimate uses an order 30 FIR filter (by 
    default otherwise n), instead of the Chebyshev IIR filter. Here decimate 
    filters the input sequence in only one direction. This technique conserves 
    memory and is useful for working with long sequences.
    """
    if fir:
        if n is None:
            n = 30
        b = signal.firwin(n, 1.0/r)
        a = 1
        f = signal.lfilter(b, a, s)
    else: #iir
        if n is None:
            n = 8
        b, a = signal.cheby1(n, 0.05, 0.8/r)
        f = signal.filtfilt(b, a, s)
    return downsample(f, r)
Пример #33
0
    def __init__(self,channels=8,yamp = 100,timerange=5,srate = 250, notchfilter=True,bandpass = [1,90]):
        self.channels = channels
        self.yamp = yamp
        self.timerange = timerange
        self.srate = srate
        self.notchfilter = notchfilter
        self.bandpass = [1,90]
        fs = self.srate/2
        if self.bandpass is not None:
            self._bp = True
            # bandpass filter
            Wp = np.array([bandpass[0] / fs, bandpass[1] / fs])
            Ws = np.array([(bandpass[0]*0.5) / fs, (bandpass[1]+10) / fs])
            N, Wn = scipy_signal.cheb1ord(Wp, Ws, 3, 40)
            self.bpB, self.bpA = scipy_signal.cheby1(N, 0.5, Wn, 'bandpass')
        else:
            self._bp = False

        # notch filter
        Fo = 50
        Q = 15
        w0 = Fo / (fs)
        self.notchB, self.notchA = scipy_signal.iirnotch(w0=w0, Q=Q)


        self._plength = self.srate * timerange
        self._flength = self.srate * (1+timerange)

        self._t = np.arange(0,timerange,1/self.srate)
        self.signal = [np.ones([self.channels,self._t.size])]

        self.update_yscale()
        self.ticks = []
        for i in range(self.channels):
            self.ticks.append('ch'+str(i+1))
        plt.ion()
Пример #34
0
def createCoeffs(order, cutoff, filterType, design='butter', rp=1, rs=1, fs=0):

    #defining the acceptable inputs for the design and filterType params
    designs = ['butter', 'cheby1', 'cheby2']
    filterTypes1 = [
        'lowpass', 'highpass', 'Lowpass', 'Highpass', 'low', 'high'
    ]
    filterTypes2 = ['bandstop', 'bandpass', 'Bandstop', 'Bandpass']

    #Error handling: other errors can arise too, but those are dealt with
    #in the signal package.
    isThereAnError = 1  #if there was no error then it will be set to 0
    COEFFS = [0]  #with no error this will hold the coefficients

    if design not in designs:
        print('Gave wrong filter design! Remember: butter, cheby1, cheby2.')
    elif filterType not in filterTypes1 and filterType not in filterTypes2:
        print('Gave wrong filter type! Remember: lowpass, highpass',
              ', bandpass, bandstop.')
    elif fs < 0:
        print('The sampling frequency has to be positive!')
    else:
        isThereAnError = 0

    #if fs was given then the given cutoffs need to be normalised to Nyquist
    if fs and isThereAnError == 0:
        for i in range(len(cutoff)):
            cutoff[i] = cutoff[i] / fs * 2

    if design == 'butter' and isThereAnError == 0:
        COEFFS = signal.butter(order, cutoff, filterType, output='sos')
    elif design == 'cheby1' and isThereAnError == 0:
        COEFFS = signal.cheby1(order, rp, cutoff, filterType, output='sos')
    elif design == 'cheby2' and isThereAnError == 0:
        COEFFS = signal.cheby2(order, rs, cutoff, filterType, output='sos')
    return COEFFS
Пример #35
0
 def _filterbank(self, eeg, idx_fbi):
     '''
     '''
     if eeg.ndim == 2:
         num_chans = eeg.shape[0]
         num_trials = 1
     else:
         num_chans, _, num_trials = eeg.shape
     fs = self.fs / 2
     passband = [6, 14, 22, 30, 38, 46, 54, 62, 70, 78]
     stopband = [4, 10, 16, 24, 32, 40, 48, 56, 64, 72]
     Wp = [passband[idx_fbi]/fs, 90/fs]
     Ws = [stopband[idx_fbi]/fs, 100/fs]
     [N, Wn] = cheb1ord(Wp, Ws, 3, 40)
     [B, A] = cheby1(N, 0.5, Wn, 'bp')
     yy = np.zeros_like(eeg)
     if num_trials == 1:
         yy = filtfilt(B, A, eeg, axis=1)
     else:
         for trial_i in range(num_trials):
             for ch_i in range(num_chans):
                 # yy[ch_i, :, trial_i] = filtfilt(B, A, eeg[ch_i, :, trial_i])
                 yy[ch_i, :, trial_i] = filtfilt(B, A, eeg[ch_i, :, trial_i], padtype='odd', padlen=3*(max(len(B),len(A))-1))
     return yy
Пример #36
0
def bandpass(eeg, sfreq, Wp, Ws):
    """Filter bank design for decomposing EEG data into sub-band components.

    Parameters
    ----------
    eeg : np.array, shape=(n_samples, n_chans[, n_trials])
        Training data.
    sfreq : int
        Sampling frequency of the data.
    Wp : 2-tuple
        Passband for Chebyshev filter.
    Ws : 2-tuple
        Stopband for Chebyshev filter.

    Returns
    -------
    y: np.array, shape=(n_trials, n_chans, n_samples)
        Sub-band components decomposed by a filter bank.

    See Also
    --------
    scipy.signal.cheb1ord :
        Chebyshev type I filter order selection.

    """
    # Chebyshev type I filter order selection.
    N, Wn = cheb1ord(Wp, Ws, 3, 40, fs=sfreq)

    # Chebyshev type I filter design
    B, A = cheby1(N, 0.5, Wn, btype="bandpass", fs=sfreq)

    # the arguments 'axis=0, padtype='odd', padlen=3*(max(len(B),len(A))-1)'
    # correspond to Matlab filtfilt : https://dsp.stackexchange.com/a/47945
    y = filtfilt(B, A, eeg, axis=0, padtype='odd',
                 padlen=3 * (max(len(B), len(A)) - 1))
    return y
Пример #37
0
def decimate(s, r, n=None, fir=False):
    """Decimation - decrease sampling rate by r. The decimation process filters 
    the input data s with an order n lowpass filter and then resamples the 
    resulting smoothed signal at a lower rate. By default, decimate employs an 
    eighth-order lowpass Chebyshev Type I filter with a cutoff frequency of 
    0.8/r. It filters the input sequence in both the forward and reverse 
    directions to remove all phase distortion, effectively doubling the filter 
    order. If 'fir' is set to True decimate uses an order 30 FIR filter (by 
    default otherwise n), instead of the Chebyshev IIR filter. Here decimate 
    filters the input sequence in only one direction. This technique conserves 
    memory and is useful for working with long sequences.
    """
    if fir:
        if n is None:
            n = 30
        b = signal.firwin(n, 1.0 / r)
        a = 1
        f = signal.lfilter(b, a, s)
    else:  #iir
        if n is None:
            n = 8
        b, a = signal.cheby1(n, 0.05, 0.8 / r)
        f = signal.filtfilt(b, a, s)
    return downsample(f, r)
Пример #38
0
fs = 3  # 阻止域端周波数[Hz]
gpass = 1  # 通過域最大損失量[dB]
gstop = 40  # 阻止域最小減衰量[dB]
# 正規化
Wp = fp / fn
Ws = fs / fn

# ローパスフィルタで波形整形
# バターワースフィルタ
N, Wn = signal.buttord(Wp, Ws, gpass, gstop)
b1, a1 = signal.butter(N, Wn, "low")
y1 = signal.filtfilt(b1, a1, y)

# 第一種チェビシェフフィルタ
N, Wn = signal.cheb1ord(Wp, Ws, gpass, gstop)
b2, a2 = signal.cheby1(N, gpass, Wn, "low")
y2 = signal.filtfilt(b2, a2, y)

# 第二種チェビシェフフィルタ
N, Wn = signal.cheb2ord(Wp, Ws, gpass, gstop)
b3, a3 = signal.cheby2(N, gstop, Wn, "low")
y3 = signal.filtfilt(b3, a3, y)

# 楕円フィルタ
N, Wn = signal.ellipord(Wp, Ws, gpass, gstop)
b4, a4 = signal.ellip(N, gpass, gstop, Wn, "low")
y4 = signal.filtfilt(b4, a4, y)

# ベッセルフィルタ
N = 4
b5, a5 = signal.bessel(N, Ws, "low")
    def initial_preprocessing(self,
                              bp_lowcut=1,
                              bp_highcut=70,
                              bp_order=2,
                              notch_freq_Hz=[60.0, 120.0],
                              notch_order=2):
        """
       Filters the data by applying
       - An SL filter
       - A zero-phase Butterworth bandpass was applied from 1 – 70 Hz. 
       - A 60-120 Hz notch filter to suppress line noise
      
       
       Input:
           - bp_ lowcut: lower cutoff frequency for bandpass filter
           - bp_highcut: higher cutoff frequency for bandpass filter
           - bp_order: order of bandpass filter
           - notch_freq_Hz: cutoff frequencies for notch fitltering
           - notch_order: order of notch filter

        
        """
        self.nyq = 0.5 * self.sample_rate  #Nyquist frequency
        self.low = bp_lowcut / self.nyq
        self.high = bp_highcut / self.nyq

        # SL filter
        self.sl_filtered_data = self.raw_eeg_data
        raw_channels = self.raw_eeg_data.transpose()
        sl_channels = deepcopy(raw_channels)

        # Subtract average of adjacent electrodes
        sl_channels[0] -= (raw_channels[1] + raw_channels[2] +
                           raw_channels[4]) / 3  # C1 -= (C2 + C3 + Cp1) / 3
        sl_channels[1] -= (raw_channels[0] + raw_channels[3] +
                           raw_channels[5]) / 3  # C2 -= (C1 + C4 + Cp2) / 3
        sl_channels[2] -= (raw_channels[0] +
                           raw_channels[6]) / 3  # C3 -= (C1 + Cp3) / 2
        sl_channels[3] -= (raw_channels[1] +
                           raw_channels[7]) / 3  # C4 -= (C2 + Cp4) / 2
        sl_channels[4] -= (raw_channels[5] + raw_channels[6] +
                           raw_channels[0]) / 3  # Cp1 -= (Cp2 + Cp3 + C1) / 3
        sl_channels[5] -= (raw_channels[4] + raw_channels[7] +
                           raw_channels[1]) / 3  # Cp2 -= (Cp1 + Cp4 + C2) / 3
        sl_channels[6] -= (raw_channels[4] +
                           raw_channels[2]) / 3  # Cp3 -= (Cp1 + C3) / 2
        sl_channels[7] -= (raw_channels[5] +
                           raw_channels[3]) / 3  # Cp4 -= (Cp2 + C4) / 2

        self.sl_filtered_data = sl_channels.transpose()

        #Bandpass filter
        plt.figure(figsize=(16, 12))

        # bunch of different filters
        plt.subplot(221)
        b_bandpass, a_bandpass = butter(bp_order, [bp_lowcut, bp_highcut],
                                        btype='band',
                                        analog=True)
        w, h = freqs(b_bandpass, a_bandpass)
        #plt.plot(w, 20 * np.log10(abs(h)))
        plt.semilogx(w, 20 * np.log10(abs(h)))
        plt.xscale('log')
        plt.xlim([0.1, 1000])
        plt.title('Butterworth filter frequency response ')
        plt.xlabel('Frequency [radians / second]')
        plt.ylabel('Amplitude [dB]')
        plt.margins(0, 0.1)
        plt.grid(which='both', axis='both')

        plt.subplot(222)
        b, a = ellip(bp_order,
                     5,
                     40, [bp_lowcut, bp_highcut],
                     'bandpass',
                     analog=True)
        w, h = freqs(b, a)
        plt.semilogx(w, 20 * np.log10(abs(h)))
        plt.xlim([0.1, 1000])
        plt.title('Elliptic filter frequency response (rp=5, rs=40)')
        plt.xlabel('Frequency [radians / second]')
        plt.ylabel('Amplitude [dB]')
        plt.margins(0, 0.1)
        plt.grid(which='both', axis='both')

        plt.subplot(223)
        b, a = cheby1(bp_order,
                      5, [bp_lowcut, bp_highcut],
                      'bandpass',
                      analog=True)
        w, h = freqs(b, a)
        plt.plot(w, 20 * np.log10(abs(h)))
        plt.xlim([0.1, 1000])
        plt.xscale('log')
        plt.title('Chebyshev Type I frequency response (rp=5)')
        plt.ylabel('Amplitude [dB]')
        plt.margins(0, 0.1)
        plt.grid(which='both', axis='both')

        plt.subplot(224)
        b, a = cheby2(bp_order,
                      5, [bp_lowcut, bp_highcut],
                      'bandpass',
                      analog=True)
        w, h = freqs(b, a)
        plt.plot(w, 20 * np.log10(abs(h)))
        plt.xlim([0.1, 1000])
        plt.xscale('log')
        plt.title('Chebyshev Type II frequency response (rp=5)')
        plt.ylabel('Amplitude [dB]')
        plt.margins(0, 0.1)
        plt.grid(which='both', axis='both')

        # filter designed using the windowing method (firwin). this filter with specified parameters seem to have decent passband, good supression of 60/120 hz artifacts and would be useful online due to relitavely short memory (in this case 2^6-1 = 63)
        # can vue time domain of filter plt.plot(b). x-axis is sample
        b = firwin(2**6 - 1, [0.5, 30],
                   width=0.05,
                   pass_zero=False,
                   fs=sampling_freq)  # length = order + 1
        plt.figure()
        b_fft = np.fft.rfft(b)
        f = np.linspace(0, 125, len(b_fft))
        plt.plot(f, abs(b_fft))

        b_bandpass, a_bandpass = butter(bp_order, [self.low, self.high],
                                        btype='band',
                                        analog=True)

        #       plt.figure()
        #       plt.plot(b_bandpass,a_bandpass)

        self.bp_filtered_eeg_data = np.apply_along_axis(
            lambda l: lfilter(b_bandpass, a_bandpass, l), 0,
            self.sl_filtered_data)

        self.notch_filtered_eeg_data = self.bp_filtered_eeg_data

        for freq_Hz in notch_freq_Hz:
            bp_stop_Hz = freq_Hz + float(notch_order) * np.array(
                [-1, 1])  # set the stop band
            b_notch, a_notch = butter(notch_order, bp_stop_Hz / self.nyq,
                                      'bandstop')
            self.notch_filtered_eeg_data = np.apply_along_axis(
                lambda l: lfilter(b_notch, a_notch, l), 0,
                self.notch_filtered_eeg_data)
Пример #40
0
        for index in range(sos.shape[0]):
            ba = sos[index]
            filter_tmp = IIR2Filter(ba[0], ba[1], ba[2], ba[3], ba[4], ba[5])
            self.sos_filters.append(filter_tmp)

    def filter(self, x):  #x as input  acc_input=accumulator input
        output = x
        for filter in self.sos_filters:
            output = filter.filter(output)
        return output


if (__name__ == "__main__"):
    fs = 1000
    T = 1 / fs
    n = 1000
    x = np.linspace(0, (n - 1) * T, n)
    y = 3 * np.cos(2 * np.pi * 80 * x) + np.cos(2 * np.pi * 200 * x) + np.cos(
        2 * np.pi * 300 * x)

    sos = signal.cheby1(8, 1, 100 / fs * 2, output='sos')

    result = np.array([])
    filter = IIRFilter(sos)
    for yi in y:
        result = np.append(result, filter.filter(yi))

    plt.plot(y, label="raw data")
    plt.plot(result, label="filtered")
    plt.legend()
    plt.show()
def cheby_design(cutoff, fs, type, order):
    return cheby1(N=order,
                  rp=2.5,
                  Wn=cutoff / (0.5 * fs),
                  btype=type,
                  analog=False)
Пример #42
0
 def test_cheby1_5(self):
     # Test case for bandpass filter without default
     IIR = IIRDesign.cheby1(self.n, self.Rp, self.Wp2, ftype='bandpass')
     iir = signal.cheby1(self.n, self.Rp, self.Wp2, btype='bandpass', fs=2)
     self.assertTrue((IIR[0] == iir[0]).all() and (IIR[1] == iir[1]).all())
Пример #43
0
    def __init__(self,
                 ninputs,
                 enc_fmaps,
                 kwidth,
                 activations,
                 lnorm=False,
                 dropout=0.,
                 pooling=2,
                 z_dim=256,
                 z_all=False,
                 skip=True,
                 skip_blacklist=[],
                 dec_activations=None,
                 cuda=False,
                 bias=False,
                 aal=False,
                 wd=0.,
                 skip_init='one',
                 skip_dropout=0.,
                 no_tanh=False,
                 aal_out=False,
                 rnn_core=False,
                 linterp=False,
                 mlpconv=False,
                 dec_kwidth=None,
                 no_z=False,
                 skip_type='alpha',
                 num_spks=None,
                 multilayer_out=False,
                 skip_merge='sum',
                 snorm=False,
                 convblock=False,
                 post_skip=False,
                 pos_code=False,
                 satt=False,
                 dec_fmaps=None,
                 up_poolings=None,
                 post_proc=False,
                 out_gate=False,
                 linterp_mode='linear',
                 hidden_comb=False,
                 big_out_filter=False,
                 z_std=1,
                 freeze_enc=False,
                 skip_kwidth=11,
                 pad_type='constant'):
        # if num_spks is specified, do onehot coditioners in dec stages
        # subract_mean: from output signal, get rif of mean by windows
        # multilayer_out: add some convs in between gblocks in decoder
        super().__init__(name='Generator1D')
        self.dec_kwidth = dec_kwidth
        self.skip_kwidth = skip_kwidth
        self.skip = skip
        self.skip_init = skip_init
        self.skip_dropout = skip_dropout
        self.snorm = snorm
        self.z_dim = z_dim
        self.z_all = z_all
        self.pos_code = pos_code
        self.post_skip = post_skip
        self.big_out_filter = big_out_filter
        self.satt = satt
        self.post_proc = post_proc
        self.pad_type = pad_type
        self.onehot = num_spks is not None
        if self.onehot:
            assert num_spks > 0
        self.num_spks = num_spks
        # do not place any z
        self.no_z = no_z
        self.do_cuda = cuda
        self.wd = wd
        self.no_tanh = no_tanh
        self.skip_blacklist = skip_blacklist
        self.z_std = z_std
        self.freeze_enc = freeze_enc
        self.gen_enc = nn.ModuleList()
        if aal or aal_out:
            # Make cheby1 filter to include into pytorch conv blocks
            from scipy.signal import cheby1, dlti, dimpulse
            system = dlti(*cheby1(8, 0.05, 0.8 / pooling))
            tout, yout = dimpulse(system)
            filter_h = yout[0]
        if aal:
            self.filter_h = filter_h
        else:
            self.filter_h = None

        if dec_kwidth is None:
            dec_kwidth = kwidth

        if isinstance(activations, str):
            if activations != 'glu':
                activations = getattr(nn, activations)()
        if not isinstance(activations, list):
            activations = [activations] * len(enc_fmaps)
        if not isinstance(pooling, list) or len(pooling) == 1:
            pooling = [pooling] * len(enc_fmaps)
        skips = {}
        # Build Encoder
        for layer_idx, (fmaps, pool,
                        act) in enumerate(zip(enc_fmaps, pooling,
                                              activations)):
            if layer_idx == 0:
                inp = ninputs
            else:
                inp = enc_fmaps[layer_idx - 1]
            if self.skip and layer_idx < (len(enc_fmaps) - 1):
                if layer_idx not in self.skip_blacklist:
                    l_i = layer_idx
                    gskip = GSkip(skip_type,
                                  fmaps,
                                  skip_init,
                                  skip_dropout,
                                  merge_mode=skip_merge,
                                  cuda=self.do_cuda,
                                  kwidth=self.skip_kwidth)
                    skips[l_i] = {'alpha': gskip}
                    setattr(self, 'alpha_{}'.format(l_i), skips[l_i]['alpha'])
            self.gen_enc.append(
                GBlock(inp,
                       fmaps,
                       kwidth,
                       act,
                       padding=None,
                       lnorm=lnorm,
                       dropout=dropout,
                       pooling=pool,
                       enc=True,
                       bias=bias,
                       aal_h=self.filter_h,
                       snorm=snorm,
                       convblock=convblock,
                       satt=self.satt,
                       pad_type=pad_type))
        self.skips = skips
        dec_inp = enc_fmaps[-1]
        if dec_fmaps is None:
            if mlpconv:
                dec_fmaps = enc_fmaps[:-1][::-1] + [16, 8, 1]
                print(dec_fmaps)
                up_poolings = [pooling] * (len(dec_fmaps) - 2) + [1] * 3
                add_activations = [nn.PReLU(16), nn.PReLU(8), nn.PReLU(1)]
                raise NotImplementedError('MLPconv is not useful and should be'
                                          ' deleted')
            else:
                dec_fmaps = enc_fmaps[:-1][::-1] + [1]
                up_poolings = pooling[::-1]
                #up_poolings = [pooling] * len(dec_fmaps)
            print('up_poolings: ', up_poolings)
            self.up_poolings = up_poolings
        else:
            assert up_poolings is not None
            self.up_poolings = up_poolings
        if rnn_core:
            self.z_all = False
            z_all = False
            # place a bidirectional RNN layer in the core to condition
            # everything to everything AND Z will be the init state of it
            self.rnn_core = nn.LSTM(dec_inp,
                                    dec_inp // 2,
                                    bidirectional=True,
                                    batch_first=True)
        else:
            if no_z:
                all_z = False
            else:
                dec_inp += z_dim
        #print(dec_fmaps)
        # Build Decoder
        self.gen_dec = nn.ModuleList()

        if dec_activations is None:
            # assign same activations as in Encoder
            dec_activations = [activations[0]] * len(dec_fmaps)
        else:
            if mlpconv:
                dec_activations = dec_activations[:-1]
                dec_activations += add_activations

        enc_layer_idx = len(enc_fmaps) - 1
        for layer_idx, (fmaps,
                        act) in enumerate(zip(dec_fmaps, dec_activations)):
            if skip and layer_idx > 0 and enc_layer_idx not in skip_blacklist \
                and up_poolings[layer_idx] > 1:
                if skip_merge == 'concat':
                    dec_inp *= 2
                print('Added skip conn input of enc idx: {} and size:'
                      ' {}'.format(enc_layer_idx, dec_inp))

            if z_all and layer_idx > 0:
                dec_inp += z_dim

            if self.onehot:
                dec_inp += self.num_spks

            if layer_idx >= len(dec_fmaps) - 1:
                if self.no_tanh:
                    act = None
                else:
                    act = nn.Tanh()
                lnorm = False
                dropout = 0
            if up_poolings[layer_idx] > 1:
                pooling = up_poolings[layer_idx]
                self.gen_dec.append(
                    GBlock(dec_inp,
                           fmaps,
                           dec_kwidth,
                           act,
                           padding=0,
                           lnorm=lnorm,
                           dropout=dropout,
                           pooling=pooling,
                           enc=False,
                           bias=bias,
                           linterp=linterp,
                           linterp_mode=linterp_mode,
                           convblock=convblock,
                           comb=hidden_comb,
                           pad_type=pad_type))
            else:
                self.gen_dec.append(
                    GBlock(
                        dec_inp,
                        fmaps,
                        dec_kwidth,
                        act,
                        lnorm=lnorm,
                        dropout=dropout,
                        pooling=1,
                        padding=0,  #kwidth//2,
                        enc=True,
                        bias=bias,
                        convblock=convblock,
                        pad_type=pad_type))
            dec_inp = fmaps
        if aal_out:
            # make AAL filter to put in output
            self.aal_out = nn.Conv1d(1,
                                     1,
                                     filter_h.shape[0] + 1,
                                     stride=1,
                                     padding=filter_h.shape[0] // 2,
                                     bias=False)
            print('filter_h shape: ', filter_h.shape)
            # apply AAL weights, reshaping impulse response to match
            # in channels and out channels
            aal_t = torch.FloatTensor(filter_h).view(1, 1, -1)
            aal_t = torch.cat((aal_t, torch.zeros(1, 1, 1)), dim=-1)
            self.aal_out.weight.data = aal_t
            print('aal_t size: ', aal_t.size())

        if post_proc:
            self.comb_net = PostProcessingCombNet(1, 512)
        if out_gate:
            self.out_gate = OutGate(1, 1)
        if big_out_filter:
            self.out_filter = nn.Conv1d(1, 1, 513, padding=513 // 2)
Пример #44
0
 def test_cheby1_6(self):
     # Test case for bandstop filter
     IIR = IIRDesign.cheby1(self.n, self.Rp, self.Wp2, ftype='stop')
     iir = signal.cheby1(self.n, self.Rp, self.Wp2, btype='bandstop', fs=2)
     self.assertTrue((IIR[0] == iir[0]).all() and (IIR[1] == iir[1]).all())
def cheby_lowpass(cutoff, fs, order, rp):
    nyq = 0.5 * fs
    normal_cutoff = cutoff / nyq
    b, a = cheby1(order, rp, normal_cutoff, btype='low', analog=False)
    return b, a
Пример #46
0
plt.ylim([-60, 12])
plt.ylabel('Amplitude [dB]')
plt.grid(which='both', axis='both')
plt.axvline(omega_c * np.pi, color='black')  # cutoff frequency
plt.legend()
plt.savefig('Butterworth.png')

# ---------- chebyshev 1 ----------
bArray = []
aArray = []
wArray = []
hArray = []
orderArray = [1, 2, 4, 5]
omega_c = 0.25
for i in orderArray:
    b, a = signal.cheby1(N=i, rp=6, Wn=omega_c)
    if i == 4:
        filterSystems.append([b, a])
    w, h = signal.freqz(b, a)
    bArray.append(b)
    aArray.append(a)
    wArray.append(w)
    hArray.append(h)

fig = plt.figure(figsize=(16, 9))
for index in range(len(orderArray)):
    plt.plot(wArray[index],
             20 * np.log10(abs(hArray[index])),
             label="order = " + str(orderArray[index]))
plt.title('Chebyshev Type 1 Filter Frequency Response: Comparison')
plt.xlabel('Frequency [up to Nyquist]')
Пример #47
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 13 12:14:28 2019

@author: ivanpauno
"""

import scipy.signal as sig
import matplotlib.pyplot as plt
import filter_utils

# Comparación orden 3, att max 3dB
num, den = sig.butter(3, 1, analog=True)  # n, wp
butter = sig.TransferFunction(num, den)
num, den = sig.cheby1(3, 3, 1, analog=True)  # n, att max, wp
cheby1 = sig.TransferFunction(num, den)
num, den = sig.cheby2(3, 20, 1.539389818149637, analog=True)  # n, att min, ws
cheby2 = sig.TransferFunction(num, den)
num, den = sig.bessel(3, 1, analog=True, norm='mag')  # n, wp
bessel = sig.TransferFunction(num, den)
num, den = sig.ellip(3, 3, 20, 1, analog=True)  # n, att max, att min, wp
ellip = sig.TransferFunction(num, den)

print('Transferencia Butterworth:\n')
filter_utils.pretty(butter.num, butter.den)
print('\n\n')
filter_utils.print_zpk(butter.num, butter.den)
print('\n\nTransferencia Chebyshev tipo 1:\n')
filter_utils.pretty(cheby1.num, cheby1.den)
print('\n\n')
Пример #48
0
def custom_cheby1(data,
                  Fs,
                  N,
                  Rp,
                  Wp,
                  Ws=None,
                  filtresponse='bandpass',
                  analog_value=False,
                  showresponse=0):
    nyquist = Fs / 2

    if filtresponse == 'bandpass':
        Wn = [Wp / nyquist, Ws / nyquist]
    else:
        Wn = [Wp / nyquist]

    b, a = signal.cheby1(N, Rp, Wn, 'bandpass', analog=analog_value)

    if data != []:
        if len(data.shape) > 1:
            #print('Filtering multidimensional array!')
            filtered_data = np.zeros((data.shape[0], data.shape[1]))
            filtered_data = signal.filtfilt(b, a, data, axis=1)
            #for channel_num in range(0, data.shape[0]):
            #    # filtered_data[channel_num,:] = signal.lfilter(b, a, data[channel_num,:])
            #    filtered_data[channel_num, :] = signal.filtfilt(b, a, data[channel_num, :])
        else:
            # filtered_data = signal.lfilter(b, a, data)
            filtered_data = signal.filtfilt(b, a, data)

    if showresponse == 1:
        if showresponse == 1:  # set to 1 if you want to visualize the frequency response of the filter
            FType = 'Chebyshev I'
            mode = 'Digital'

            w, h = signal.freqz(
                b, a, worN=8000
            )  # returns the requency response h, and the normalized angular
            # frequencies w in radians/sample
            # w (radians/sample) * Fs (samples/sec) * (1 cycle/2pi*radians) = Hz
            f = Fs * w / (2 * np.pi)  # Hz

            plt.figure(figsize=(10, 5))
            # plt.subplot(211)
            plt.semilogx(f, np.abs(h), 'b')
            plt.xscale('log')

            if Ws is not None:
                plt.title(
                    '%s Bandpass Filter Frequency Response (Order = %s, Wp=%s (Hz), Ws =%s (Hz))'
                    % (FType, N, Wp, Ws))
            else:
                plt.title(
                    '%s Lowpass Filter Frequency Response (Order = %s, Wp=%s (Hz))'
                    % (FType, N, Wp))

            plt.xlabel('Frequency(Hz)')
            plt.ylabel('Gain [V/V]')
            plt.margins(0, 0.1)
            plt.grid(which='both', axis='both')
            plt.axvline(Wp, color='green')
            if Ws is not None:
                plt.axvline(Ws, color='green')
                # plt.plot(Ws, 0.5*np.sqrt(2), 'ko') # cutoff frequency
            plt.show()

    return filtered_data
Пример #49
0
import numpy as np
import librosa
import librosa.display
import matplotlib.pyplot as plt

filename = r'1.wav'
# Load the example clip
y, sr = librosa.load(filename)
y = y - 0.97 * y

from scipy import signal
import numpy as np
import math
# b, a = signal.butter(4, 16000/sr*0.5, "highpass") # lowpass
# 阶数;最大纹波允许低于通频带中的单位增益。以分贝表示,以正数表示;频率(Hz)/奈奎斯特频率(采样率*0.5)
b, a = signal.cheby1(4, 5, 16000 / sr * 0.5, "highpass")  # lowpass
yt = signal.filtfilt(b, a, y)
y = yt

S, phase = librosa.magphase(librosa.stft(y=y))
cent = librosa.feature.spectral_centroid(y=y, sr=sr)

print('rms.shape:', cent.shape)

plt.figure()
plt.subplot(211)
plt.semilogy(cent.T, label='Spectral centroid')
plt.ylabel('Hz')
plt.xticks([])
plt.xlim([0, cent.shape[-1]])
plt.subplot(212)
Пример #50
0
 def LPman(self, fil_dict):
     self._get_params(fil_dict)
     if not self._test_N():
         return -1
     self._save(fil_dict, sig.cheby1(self.N, self.A_PB, self.F_C,
                         btype='low', analog=self.analog, output=self.FRMT))
Пример #51
0
 def test_cheby1_7(self):
     # Test case for analog filter
     IIR = IIRDesign.cheby1(self.n, self.Rp, self.Wps, zs='s')
     iir = signal.cheby1(self.n, self.Rp, self.Wps, analog=True)
     self.assertTrue((IIR[0] == iir[0]).all() and (IIR[1] == iir[1]).all())
Пример #52
0
# sampling rate
fs = 24000

# cutoffs
f1 = 300
f2 = 2700

# scaling factor in bits
q = 14
# scaling factor as facor...
scaling_factor = 2**q

# let's generate a sequence of 2nd order IIR filters
#sos = signal.butter(2,[f1/fs*2,f2/fs*2],'pass',output='sos')
sos = signal.cheby1(3,
                    0.2, [f1 / fs * 2, f2 / fs * 2],
                    'bandpass',
                    output='sos')

sos = np.round(sos * scaling_factor)

# print coefficients
for biquad in sos:
    for coeff in biquad:
        print(int(coeff), ",", sep="", end="")
    print(q)

# plot the frequency response
b, a = signal.sos2tf(sos)
w, h = signal.freqz(b, a)
pl.plot(w / np.pi / 2 * fs, 20 * np.log(np.abs(h)))
pl.xlabel('frequency/Hz')
Пример #53
0
 def BSman(self, fil_dict):
     self._get_params(fil_dict)
     if not self._test_N():
         return -1
     self._save(fil_dict, sig.cheby1(self.N, self.A_PB, [self.F_C,self.F_C2],
                     btype='bandstop', analog=self.analog, output=self.FRMT))
Пример #54
0
As = 0.1
Ap = 0.9

fsl = (fpl * fph) / fsh
Os = (fsh - fsl) / (fph - fpl)
delta = np.sqrt((1 / As) - 1)
e = np.sqrt((1 / Ap) - 1)
n = (math.acosh(delta / e)) / (math.acosh(Os))
n = np.round(n)

## Funcion de transferencia

Fs = 44100.0
Fn = 0.5 * Fs  #Frecuencia de Nyquist
rp = -10 * math.log10(0.9)
b, a = signal.cheby1(n,
                     rp,
                     np.array([200, 6000]) / Fn,
                     'bandpass',
                     analog=False)

## Respuesta en la frecuencia 0 a 1000 Hz incrementos de 10 Hz
f = np.arange(0, 10000, 10)
w = np.pi * f / Fn
w, h = signal.freqz(b, a, w)

##Grafica

pyplot.plot(f, np.abs(h))
pyplot.show()
Пример #55
0
 A = 0.5 * (c.full_scale_32 - 1
            )  # Half of 32 bit full scale, because noise can be added
 K_Noise = 1 / 50  # Gaussian noise relative std amplitude
 FORMAT = pyaudio.paInt32  # Signed 32 bit (Little Endian byte order)
 CHANNELS = int(2)
 byte_width = 4
 bytes_size = CHANNELS * byte_width * c.N_FRAMES  # Bytes in each period
 #
 fc = 500  # Filter central frequency
 f1 = fc / 1.4142
 f2 = fc * 1.4142
 #                     butter(N,       [W1, w2]         btype='bp', analog=False, output='ba')
 #                     cheby1(N, rp,   [W1, W2]         btype='bp', analog=False, output='ba')
 B_hp, A_hp = cheby1(4,
                     0.03, [f1 / Fnyq, f2 / Fnyq],
                     'bp',
                     analog=False,
                     output='ba')
 #
 #                     freqz(b,      a=1,    worN=None,  whole=0,     plot=None)
 w_norm, h_bp = freqz(b=B_hp, a=A_hp, worN=f_range, whole=False, plot=None)
 f_hz = (w_norm * Fnyq / np.pi)
 #
 if SIGNAL == "chirp":
     x = c.PUT_AUDIO_PEAK * chirp(t, Fmin, T, Fmax, method='linear',
                                  phi=90) / PI_OUT_GAIN  # Chirp signal
     y = lfilter(B_hp, A_hp, x)  # Chirp signal filtered with a bp
     if PLOT_FILTER:
         fig_0 = plt.figure()
         plt.subplot(111)
         plt.semilogx(f_hz[sel], 20 * np.log10(np.abs(h_bp[sel])))
Пример #56
0
    def _update_canvas(self):
        """
        Update the figure when the user changes an input value
        :return:
        """
        # Get the parameters from the form
        filter_order = int(self.filter_order.text())
        critical_frequency = int(self.critical_frequency.text())
        maximum_ripple = float(self.maximum_ripple.text())
        minimum_attenuation = float(self.minimum_attenuation.text())

        # Get the selected filter from the form
        filter_type = self.filter_type.currentText()

        if filter_type == 'Butterworth':
            b, a = signal.butter(filter_order,
                                 critical_frequency,
                                 'low',
                                 analog=True)
        elif filter_type == 'Chebyshev':
            b, a = signal.cheby1(filter_order,
                                 maximum_ripple,
                                 critical_frequency,
                                 'low',
                                 analog=True)
        elif filter_type == 'Bessel':
            b, a = signal.bessel(filter_order,
                                 critical_frequency,
                                 'low',
                                 analog=True,
                                 norm='phase')
        elif filter_type == 'Elliptic':
            b, a = signal.ellip(filter_order,
                                maximum_ripple,
                                minimum_attenuation,
                                critical_frequency,
                                'low',
                                analog=True)

        w, h = signal.freqs(b, a)

        # Clear the axes for the updated plot
        self.axes1.clear()

        # Create the line plot
        self.axes1.semilogx(w, 20 * log10(abs(h)))

        # Set the y axis limit
        self.axes1.set_ylim(-80, 5)

        # Set the x and y axis labels
        self.axes1.set_xlabel("Frequency (Hz)", size=12)
        self.axes1.set_ylabel("Amplitude (dB)", size=12)

        # Turn on the grid
        self.axes1.grid(linestyle=':', linewidth=0.5)

        # Set the plot title and labels
        self.axes1.set_title('Filter Response', size=14)

        # Set the tick label size
        self.axes1.tick_params(labelsize=12)

        # Update the canvas
        self.my_canvas.draw()
Пример #57
0
# Importing the dataset
dataset = pd.read_csv(f'{file}/csv_files/bode_chevy.csv')
freq = dataset.iloc[:, 0].values
mag = dataset.iloc[:, 1].values

Fn = 22e3
fc = 2*np.pi*Fn
ordem = [8]
rp = 0.5

# Grafico 1
plt.semilogx(freq, mag, label='Filtro implementado')
# Grafico2
for N in ordem:
    b, a = signal.cheby1(N, rp, fc, 'low', analog=True)
    w, h = signal.freqs(b, a)
    plt.semilogx(w/(2*np.pi), 20 * np.log10(abs(h)), label=f'Filtro ideal')


plt.title('Resposta em frequência do filtro Chevyshev')
plt.xlabel('Frequencia [Hz]')
plt.ylabel('Amplitude [dB]')
plt.margins(0, 0.1)
plt.grid(which='both', axis='both')
plt.axvline(Fn, color='green')  # cutoff frequency
plt.axhline(-0.5, color='green') # ripple
plt.legend(loc='upper left')
plt.tight_layout()
plt.show()
Пример #58
0
from scipy import signal
import matplotlib.pyplot as plt
import librosa
import soundfile as sf

(Frequency, array) = librosa.load('audio10.wav', sr=None)

len(Frequency)

plt.plot(Frequency)
plt.title('Original Signal Spectrum')
plt.xlabel('Frequency(Hz)')
plt.ylabel('Amplitude')
# plt.show()

b, a = signal.cheby1(5, 3, 1000 / (0.5 * array), btype='highpass')

filteredSignal = signal.lfilter(b, a, Frequency)
plt.plot(filteredSignal)  # plotting the signal.
plt.title('Highpass Filter')
plt.xlabel('Frequency(Hz)')
plt.ylabel('Amplitude')
# plt.show()

c, d = signal.cheby1(5, 3, 380 / (0.5 * array), btype='lowpass')  # ButterWorth low-filter
newFilteredSignal = signal.lfilter(c, d, filteredSignal)  # Applying the filter to the signal
plt.plot(newFilteredSignal)  # plotting the signal.
plt.title('Lowpass Filter')
plt.xlabel('Frequency(Hz)')
plt.ylabel('Amplitude')
# plt.show()
Пример #59
0
    })
    df.plot(x='f', logy=True, logx=True, xlim=(10, fs / 2))


def noisy_chirp(fs=44100, seconds=1.0):
    t = numpy.linspace(0, 1, int(seconds * fs), False)
    chirp = signal.chirp(t, f0=6, f1=fs / 2.0, t1=seconds, method='linear')
    noise = numpy.random.normal(0, 1.0, size=len(t))
    sig = chirp + 0.05 * noise
    return t, sig


FS = 32000
FILTERS = {
    'cheby1-order1-lowpass':
    signal.cheby1(N=1, rp=3, Wn=1000, btype='lp', fs=FS, output='sos'),
    'cheby1-order2-highpass':
    signal.cheby1(N=2, rp=3, Wn=2000, btype='hp', fs=FS, output='sos'),
    'cheby1-order4-highpass':
    signal.cheby1(N=4, rp=3, Wn=2000, btype='hp', fs=FS, output='sos'),
    'cheby1-order5-bandpass':
    signal.cheby1(N=5, rp=12, Wn=[2000, 4000], btype='bp', fs=FS,
                  output='sos'),
    'cheby1-order12-highpass':
    signal.cheby1(N=12, rp=12, Wn=4000, btype='hp', fs=FS, output='sos'),
}


@pytest.mark.parametrize('filtername', FILTERS.keys())
def test_iir_filter(filtername):
    sos = FILTERS[filtername]
def calcularPlotImpinvar(f0,
                         fs,
                         mode="butter",
                         n=4,
                         filename="out.png",
                         title="noTitle"):
    w0 = 2 * pi * f0
    print("f0 = ", f0)

    if mode == "butter":
        b, a = signal.butter(n, w0, 'low', analog=True)
    elif mode == "cheby":
        b, a = signal.cheby1(n, 1, w0, 'low', analog=True)

    sys = signal.lti(b, a)

    w_range = linspace(0, fs, 100000) * 2 * pi

    w, h = signal.freqresp(sys, w_range)  # signal.freqs(b, a, 100000)

    w_m2 = -1

    for i in range(len(w)):
        if 20 * log10(abs(h[i])) <= -2 and w_m2 == -1:
            w_m2 = w[i]

    if mode == "butter":
        b, a = signal.butter(n, w0 * (w0 / w_m2), 'low', analog=True)
    elif mode == "cheby":
        b, a = signal.cheby1(n, 1, w0 * (w0 / w_m2), 'low', analog=True)

    sys = signal.lti(b, a)
    sys_original = sys

    w, h = signal.freqresp(sys, w_range)
    f = w / 2 / pi

    b2, a2 = impinvar_causal(b, a, fs=fs, tol=0.0001)

    sys = signal.dlti(b2, a2)

    w2, h2 = signal.dfreqresp(sys, w_range / fs)

    factor = h[0] / h2[0]

    sys = signal.dlti(b2 / factor, a2)

    f2 = w2 / 2 / pi * fs

    CombinedPlot() \
        .setTitle(title) \
        .setXTitle("Frecuencia (hz)") \
        .setYTitle("Amplitud (Db)") \
        .addSignalPlot(
        signal=Senial.Senial(
            f, 20 * log10(abs(h))
        ),
        color="red",
        name="Analógica"
    ).addSignalPlot(
        signal=Senial.Senial(
            f2, 20 * log10(abs(h2) * factor)
        ),
        color="blue",
        name="Digital método invariante al impulso"
    ).plot().save("output/" + filename)