示例#1
1
文件: cq.py 项目: erikvdp/Thesis
def pitch_filter_bank(ratios_pitches=None, fs=16000, Q=25.0, max_loss_pass=1.0, min_attenuation_stop=50.0):
    """
    lowest pitch: 20.6 Hz = pitch 16, the lowest pitch above the low threshold of hearing
    highest pitch: 7458.6 Hz = pitch 118, the highest pitch below half of the sampling frequency (fs = 16000Hz)
    Note that 119 is technically below the nyquist frequency (~7900Hz), but the right stopband frequency wouldn't be.
    
    fs: sampling frequency of the input in Hz
    Q: Q factor = frequency / bandwidth, used to determine passband and stopband frequencies of the elliptic filters
    max_loss_pass: maximal loss in passband in dB
    min_attenuation_stop: minimal attenuation in stopband in dB
    """
    if ratios_pitches is None:
        ratios_pitches = RATIOS_PITCHES_DEFAULT
        # structure: tuples of sampling frequency ratios and sets of pitches

    filters = {} # dictionary indexed by sampling frequency ratio. Each item is again a dictionary indexed by pitch, giving a filter coefficient tuple.
    
    for ratio, pitches in ratios_pitches:
        filters[ratio] = {}
        current_fs = float(fs / ratio) # input sampling frequency for the current set of pitches
        nyquist_freq = current_fs / 2
        for pitch in pitches:
            freq = pitch2freq(pitch)
            w = freq / nyquist_freq # omega = normalised frequency
            w_pass = (w * (1 - 1 / (2*Q)), w * (1 + 1 / (2*Q)))
            w_stop = (w * (1 - 1 / Q), w * (1 + 1 / Q))
            n, w_natural = sig.ellipord(w_pass, w_stop, max_loss_pass, min_attenuation_stop)
            coeff_b, coeff_a = sig.ellip(n, max_loss_pass, min_attenuation_stop, w_natural, btype='bandpass') # get filter coefficients
            # note that scipy's ellip differs from matlab's in that it will always generate a lowpass filter by default.
            # btype='bandpass' needs to be passed explicitly!
            filters[ratio][pitch] = (coeff_b, coeff_a)
    
    return filters
示例#2
0
    def __parameters_custom_order(self):
        order = self.custom_order
        if self.approx_type == 'butterworth':
            N, self.wn = signal.buttord(self.wp,
                                        self.ws,
                                        self.template.att_p,
                                        self.template.att_s,
                                        analog=True)
            N_norm, self.wn_N = signal.buttord(self.template.omega_pN,
                                               self.template.omega_sN,
                                               self.template.att_p,
                                               self.template.att_s,
                                               analog=True)
        elif self.approx_type == 'bessel':
            pass
        elif self.approx_type == 'cheby_1':
            N, self.wn = signal.cheb1ord(self.wp,
                                         self.ws,
                                         self.template.att_p,
                                         self.template.att_s,
                                         analog=True)
            N_norm, self.wn_N = signal.cheb2ord(self.template.omega_pN,
                                                self.template.omega_sN,
                                                self.template.att_p,
                                                self.template.att_s,
                                                analog=True)
        elif self.approx_type == 'cheby_2':
            N, self.wn = signal.cheb2ord(self.wp,
                                         self.ws,
                                         self.template.att_p,
                                         self.template.att_s,
                                         analog=True)
            N_norm, self.wn_N = signal.cheb2ord(self.template.omega_pN,
                                                self.template.omega_sN,
                                                self.template.att_p,
                                                self.template.att_s,
                                                analog=True)
        elif self.approx_type == 'legendre':
            pass
        elif self.approx_type == 'gauss':
            pass
        elif self.approx_type == 'cauer':
            N, self.wn = signal.ellipord(self.wp,
                                         self.ws,
                                         self.template.att_p,
                                         self.template.att_s,
                                         analog=True)
            N_norm, self.wn_N = signal.ellipord(self.template.omega_pN,
                                                self.template.omega_sN,
                                                self.template.att_p,
                                                self.template.att_s,
                                                analog=True)

        return order
示例#3
0
文件: cw5.py 项目: PUT-JUG/lab-icmwr
def filter_emg(data: np.array, fs: int, Rs: int, notch: bool):

    N, fn = signal.ellipord([46.0, 54.0], [47.0, 53], .01, Rs, fs=fs)
    be, ae = signal.ellip(N, .01, Rs, fn, fs=fs, btype='bandstop')
    N, fn = signal.ellipord([96, 104.0], [97, 103], .01, Rs, fs=fs)
    be_100, ae_100 = signal.ellip(N, .01, Rs, fn, fs=fs, btype='bandstop')
    N, fn = signal.cheb2ord(15, 10, .0086, 55, fs=500)
    bb, ab = signal.cheby2(N, 50, fn, 'high', fs=fs)
    signal_filtered = signal.lfilter(
        be_100, ae_100, signal.lfilter(be, ae, signal.lfilter(bb, ab, data)))
    #     signal_filtered = data
    signal_filtered_zero_ph = signal.filtfilt(
        be_100, ae_100, signal.filtfilt(be, ae, signal.filtfilt(bb, ab, data)))
    return signal_filtered, signal_filtered_zero_ph
示例#4
0
    def _sos(self, sfreq):
        nyq = sfreq / 2.
        low_stop, low_pass, high_pass, high_stop, gpass, gstop = self.args
        if high_stop is None:
            assert low_stop is not None
            assert high_pass is None
        else:
            high_stop /= nyq
            high_pass /= nyq

        if low_stop is None:
            assert low_pass is None
        else:
            low_pass /= nyq
            low_stop /= nyq

        if low_stop is None:
            btype = 'lowpass'
            wp, ws = high_pass, high_stop
        elif high_stop is None:
            btype = 'highpass'
            wp, ws = low_pass, low_stop
        else:
            btype = 'bandpass'
            wp, ws = (low_pass, high_pass), (low_stop, high_stop)
        order, wn = signal.ellipord(wp, ws, gpass, gstop)
        return signal.ellip(order, gpass, gstop, wn, btype, output='sos')
示例#5
0
文件: Linx.py 项目: Bruyant/Linx
    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)
示例#6
0
    def _get_filter_coeffs(self, output='sos', analog=False):
        from scipy import signal

        # Compute the filter params
        N, Wn = signal.ellipord(
            wp=self._f_pass,
            ws=self._f_stop,
            gpass=self._max_suppression_pass,
            gstop=self._min_suppression_stop,
            analog=False,
            fs=self._f_sample
        )
        if analog:
            fs = None
        else:
            fs = self._f_sample

        coeffs = signal.ellip(
            N,
            rp=self._max_suppression_pass,
            rs=self._min_suppression_stop,
            Wn=Wn,
            btype=self._kind,
            analog=analog,
            output=output,
            fs=fs
        )

        return coeffs
示例#7
0
 def design_filter(self, fs):
     if np.isinf(self.LPFcutoff):
         N, Ws = ellipord(self.HPFcutoff * 1e3 / fs * 2,
                          max(5 * 1e3 / fs * 2,
                              (self.HPFcutoff - 5) * 1e3 / fs * 2),
                          self.Rp,
                          self.Rs)
         b, a = ellip(N, self.Rp, self.Rs, Ws, 'high')
     else:
         N, Ws = ellipord([self.HPFcutoff * 1e3 / fs * 2, self.LPFcutoff * 1e3 / fs * 2],
                          [max(5*1e3/fs*2,(self.HPFcutoff-5)*1e3/fs*2),
                           min((fs/2-5e3)/fs*2,(self.LPFcutoff+5)*1e3/fs*2)],
                          self.Rp,
                          self.Rs)
         b, a = ellip(N, self.Rp, self.Rs, Ws)
     return b, a
示例#8
0
文件: Nmax.py 项目: tc-grupo-4/TP04
def NmaxCauer(Qmax):
    wp = 1
    ws = 
    gpass = 
    gstop = 
    N, Wn = signal.ellipord(wp,ws,gpass,gstop,analog = True)
    return N
示例#9
0
 def LPmin(self, fil_dict):
     """Elliptic LP filter, minimum order"""
     self.get_params(fil_dict)
     self.N, self.F_PBC = ellipord(self.F_PB,self.F_SB, self.A_PB,self.A_SB,
                                                       analog = self.analog)
     self.save(fil_dict, sig.ellip(self.N, self.A_PB, self.A_SB, self.F_PBC,
                         btype='low', analog = self.analog, output = frmt))
示例#10
0
 def BPmin(self, fil_dict):
     """Elliptic BP filter, minimum order"""
     self.get_params(fil_dict)
     self.N, self.F_PBC = ellipord([self.F_PB, self.F_PB2],
         [self.F_SB, self.F_SB2], self.A_PB, self.A_SB, analog = self.analog)
     self.save(fil_dict, sig.ellip(self.N, self.A_PB, self.A_SB, self.F_PBC,
                     btype='bandpass', analog = self.analog, output = frmt))
示例#11
0
def get_filter(spec, filter_type='but', method='zoh'):
    
    if filter_type.lower() in ('butterworth'):
        N, Wn = signal.buttord(2*np.pi*spec['fp'], 2*np.pi*spec['fs'], spec['Amax'], spec['Amin'], analog=True)
        z, p, k = signal.butter(N, Wn, output='zpk', btype='low', analog=True)
    elif filter_type.lower() in ('cauer' + 'elliptic'):
        N, Wn = signal.ellipord(2*np.pi*fp, 2*np.pi*spec['fs'], spec['Amax'], spec['Amin'], analog=True)
        z, p, k = signal.ellip(N, spec['Amax'], spec['Amin'], Wn, output='zpk', btype='low', analog=True)

    def matched_method(z, p, k, dt):
        zd = np.exp(z*dt)
        pd = np.exp(p*dt)
        kd = k * np.abs(np.prod(1-pd)/np.prod(1-zd) * np.prod(z)/np.prod(p))
        return zd, pd, kd, dt

    if method == 'matched':
        zd, pd, kd, dt = matched_method(z, p, k, spec['dt'])
        kd *= 1 - (1 - 10 ** (-spec['Amax']/20))/2
    else:
        zd, pd, kd, dt = signal.cont2discrete((z,p,k), spec['dt'], method=method)

    analog_system = (z,p,k)
    discrete_system = (zd,pd,kd)

    return analog_system, discrete_system
示例#12
0
def get_filter(spec, filter_type='but', method='zoh'):

    wp = 2*np.pi*spec['fp']
    ws = 2*np.pi*spec['fs']

    if method == 'bilinear':
        wp = 2/spec['dt'] * np.arctan(wp * spec['dt']/2)
        ws = 2/spec['dt'] * np.arctan(ws * spec['dt']/2)
    
    if filter_type.lower() in ('butterworth'):
        N, Wn = signal.buttord(wp, ws, spec['Amax'], spec['Amin'], analog=True)
        z, p, k = signal.butter(N, Wn, output='zpk', btype='low', analog=True)
    elif filter_type.lower() in ('cauer' + 'elliptic'):
        N, Wn = signal.ellipord(wp, ws, spec['Amax'], spec['Amin'], analog=True)
        z, p, k = signal.ellip(N, spec['Amax'], spec['Amin'], Wn, output='zpk', btype='low', analog=True)

    if method == 'matched':
        zd, pd, kd, dt = matched_method(z, p, k, spec['dt'])
        kd *= 1 - (1 - 10 ** (-spec['Amax']/20))/2
    else:
        zd, pd, kd, dt = signal.cont2discrete((z,p,k), spec['dt'], method=method)

    analog_system = (z,p,k)
    discrete_system = (zd,pd,kd)

    return analog_system, discrete_system
示例#13
0
def ellip_bp(atten, ripple, lo=0, hi=0, hp_width=0, lp_width=0, Fs=2.0):
    if hp_width == 0 and lo > 0:
        hp_width = 0.1 * (hi - lo)
        if lo - hp_width <= 0:
            # set hp_width to halfway between 0 and lo
            hp_width = 0.5 * lo
            print('bad HP stopband, adjusting to {0:.1f}'.format(hp_width))
    if lp_width == 0 and hi > 0:
        lp_width = 0.1 * (hi - lo)
        if hi + lp_width >= Fs / 2:
            # make lp_width to halfway between hi and Nyquist
            lp_width = 0.5 * (Fs / 2 - hi)
            print('bad LP stopband, adjusting to {0:.1f}'.format(lp_width))
    if lo > 0 and hi > 0:
        # bandpass design
        wp = np.array([lo, hi]) * 2 / Fs
        ws = np.array([lo - hp_width, hi + lp_width]) * 2 / Fs
        btype = 'bandpass'
    elif lo > 0:
        # highpass design
        wp = 2 * lo / Fs
        ws = 2 * (lo - hp_width) / Fs
        btype = 'highpass'
    elif hi > 0:
        # lowpass design
        wp = 2 * hi / Fs
        ws = 2 * (hi + lp_width) / Fs
        btype = 'lowpass'

    order, wn = signal.ellipord(wp, ws, ripple, atten)
    return signal.ellip(order, ripple, atten, wn, btype=btype)
示例#14
0
    def _sos(self, sfreq):
        nyq = sfreq / 2.
        low_stop, low_pass, high_pass, high_stop, gpass, gstop = self.args
        if high_stop is None:
            assert low_stop is not None
            assert high_pass is None
        else:
            high_stop /= nyq
            high_pass /= nyq

        if low_stop is None:
            assert low_pass is None
        else:
            low_pass /= nyq
            low_stop /= nyq

        if low_stop is None:
            btype = 'lowpass'
            wp, ws = high_pass, high_stop
        elif high_stop is None:
            btype = 'highpass'
            wp, ws = low_pass, low_stop
        else:
            btype = 'bandpass'
            wp, ws = (low_pass, high_pass), (low_stop, high_stop)
        order, wn = signal.ellipord(wp, ws, gpass, gstop)
        return signal.ellip(order, gpass, gstop, wn, btype, output='sos')
示例#15
0
 def _sos(self, sfreq):
     nyq = sfreq / 2.
     low_stop, low_pass, high_pass, high_stop, gpass, gstop = self.args
     order, wn = signal.ellipord((low_pass / nyq, high_pass / nyq),
                                 (low_stop / nyq, high_stop / nyq), gpass,
                                 gstop)
     return signal.ellip(order, gpass, gstop, wn, 'bandpass', output='sos')
示例#16
0
def ellip_bp(fs, fm, B, rpass, gstop):
    fpass = np.array([fm - B / 2, fm + B / 2])
    fstop = np.array([fm - B / 2 - 0.1 * B, fm + B / 2 + 0.1 * B])
    wpass = 2 * fpass / fs
    wstop = 2 * fstop / fs
    [order, wn] = signal.ellipord(wpass, wstop, rpass, gstop)
    sos = signal.ellip(order, rpass, gstop, wn, btype='bandpass', output='sos')
    return sos
示例#17
0
文件: Linx.py 项目: Bruyant/Linx
    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)
示例#18
0
文件: ellip.py 项目: chipmuenk/pyFDA
 def BPmin(self, fil_dict):
     """Elliptic BP filter, minimum order"""
     self._get_params(fil_dict)
     self.N, self.F_PBC = ellipord([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.ellip(self.N, self.A_PB, self.A_SB, self.F_PBC,
                     btype='bandpass', analog=self.analog, output=self.FRMT))
def ellip_spec(f0, f1, M):
    """Compute full spectrum of backwards/forwards high-pass elliptic
    filter."""
    gpass = 0.01
    gstop = 40
    N, Wn = ellipord(f0, f1, gpass, gstop, fs=1)
    b, a = ellip(N, gpass, gstop, Wn, 'high', fs=1)
    f, H = freqz(b, a, fs=1, whole=True, worN=M)
    return np.abs(H*H)
示例#20
0
 def BPmin(self, fil_dict):
     """Elliptic BP filter, minimum order"""
     self._get_params(fil_dict)
     self.N, self.F_PBC = ellipord([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.ellip(self.N, self.A_PB, self.A_SB, self.F_PBC,
                     btype='bandpass', analog=self.analog, output=self.FRMT))
示例#21
0
    def bessel(self, save=True, show=False):
        N, Wn = signal.ellipord(self.Wpass, self.Wstop, self.gpass, self.gstop)
        b, a = signal.bessel(N, Wn, 'low')
        y = signal.filtfilt(b, a, self.output)

        if show:
            self.showGraph(data=y)
        if save:
            self.output = y
def ellip_bf(x, f0, f1):
    """backwards/forwards elliptic filter"""
    gpass = 0.01
    gstop = 40
    N, Wn = ellipord(f0, f1, gpass, gstop, fs=1)
    b, a = ellip(N, gpass, gstop, Wn, 'high', fs=1)
    x2 = lfilter(b, a, x[::-1])
    x3 = lfilter(b, a, x2[::-1])
    return x3
示例#23
0
    def compute_parameters(self, target='stopband'):
        """ This function computes the order and the -3 dB-frequency
            of the filter for the specific parameters.

            Arguments:

                target: The optimization goal for the filter computation.
                Choices are:
                    - stopband: optimize to the stopband (like MATLAB)
                    - passband: optimize to the passband
        """

        if target not in ['passband', 'stopband', None]:
            raise ValueError("Target must be one of passband or stopband, \
                             or not given if filter is not Butterworth.")
        else:
            self.filter_target = target

        if True: # Change here to be more verbose.
            print("Ws = ", self.Ws)
            print("Wp = ", self.Wp)
            print("Rp = ", self.passband_attenuation)
            print("Rs = ", self.stopband_attenuation)

        if self.filter_class == 'butterworth':
            if target == 'passband':
                self.N, self.Wn = signal.buttord(self.Wp, self.Ws,
                                                 self.passband_attenuation,
                                                 self.stopband_attenuation,
                                                 analog=True)
            elif target == 'stopband':
                self.N, self.Wn = custom.custom_buttord(self.Wp, self.Ws,
                                                        self.passband_attenuation,
                                                        self.stopband_attenuation,
                                                        analog=True)
            else:
                raise ValueError("Butterworth filters must match either the \
                                 passband or the stopband.")
        elif self.filter_class == 'chebyshev_1':
            self.N, self.Wn = signal.cheb1ord(self.Wp, self.Ws,
                                              self.passband_attenuation,
                                              self.stopband_attenuation,
                                              analog=True)
        elif self.filter_class == 'chebyshev_2':
            self.N, self.Wn = signal.cheb2ord(self.Wp, self.Ws,
                                              self.passband_attenuation,
                                              self.stopband_attenuation,
                                              analog=True)
        elif self.filter_class == 'elliptical':
            self.N, self.Wn = signal.ellipord(self.Wp, self.Ws,
                                              self.passband_attenuation,
                                              self.stopband_attenuation,
                                              analog=True)
        else:
            raise NotImplementedError(
                "Filter family {} not yet implemented".format(self.filter_class))
        pass
示例#24
0
 def test_ellipord_4(self):
     # Test case for bandstop filter
     ORD = IIRDesign.ellipord(self.f4, self.f3, self.Rp, self.Rs)
     ord = signal.ellipord(self.f4,
                           self.f3,
                           self.Rp,
                           self.Rs,
                           analog=False,
                           fs=2)
     self.assertTrue((ORD[0] == ord[0]) and np.all(ORD[1] == ord[1]))
示例#25
0
    def HPmin(self, fil_dict):
        """Elliptic HP filter, minimum order"""
        self._get_params(fil_dict)
        self.N, self.F_PBC = ellipord(self.F_PB,self.F_SB, self.A_PB,self.A_SB,
                                                          analog=self.analog)
#       force even N
        if (self.N%2)== 1:
            self.N += 1
        self._save(fil_dict, sig.ellip(self.N, self.A_PB, self.A_SB, self.F_PBC,
                        btype='highpass', analog=self.analog, output=self.FRMT))
示例#26
0
 def test_ellipord_2(self):
     # Test case for highpass filter
     ORD = IIRDesign.ellipord(self.f2, self.f1, self.Rp, self.Rs)
     ord = signal.ellipord(self.f2,
                           self.f1,
                           self.Rp,
                           self.Rs,
                           analog=False,
                           fs=2)
     self.assertTrue((ORD[0] == ord[0]) and np.all(ORD[1] == ord[1]))
示例#27
0
    def BSmin(self, fil_dict):
        """Elliptic BP filter, minimum order"""
        self._get_params(fil_dict)
        self.N, self.F_PBC = ellipord([self.F_PB, self.F_PB2],
                                [self.F_SB, self.F_SB2], self.A_PB,self.A_SB,
                                                        analog=self.analog)
#       force even N
        if (self.N%2)== 1:
            self.N += 1
        self._save(fil_dict, sig.ellip(self.N, self.A_PB, self.A_SB, self.F_PBC,
                        btype='bandstop', analog=self.analog, output=self.FRMT))
示例#28
0
 def BPmin(self, fil_dict):
     """Elliptic BP filter, minimum order"""
     self._get_params(fil_dict)
     self.N, self.F_PBC = ellipord([self.F_PB, self.F_PB2],
         [self.F_SB, self.F_SB2], self.A_PB, self.A_SB, analog=self.analog)
     #logger.warning(" "+str(self.F_PBC) + " " + str(self.N))
     if (self.N%2)== 1:
         self.N += 1
     #logger.warning("-"+str(self.F_PBC) + " " + str(self.A_SB))
     self._save(fil_dict, sig.ellip(self.N, self.A_PB, self.A_SB, self.F_PBC,
                     btype='bandpass', analog=self.analog, output=self.FRMT))
示例#29
0
    def LPmin(self, fil_dict):
        """Elliptic LP filter, minimum order"""
        self._get_params(fil_dict)
        self.N, self.F_PBC = ellipord(self.F_PB,self.F_SB, self.A_PB,self.A_SB,
                                                          analog=self.analog)
#       force even N
        if (self.N%2)== 1:
            self.N += 1
        #logger.warning("and "+str(self.F_PBC) + " " + str(self.N))
        self._save(fil_dict, sig.ellip(self.N, self.A_PB, self.A_SB, self.F_PBC,
                            btype='low', analog=self.analog, output=self.FRMT))
示例#30
0
    def __order_min_max_cauer(self):
        N, self.wn = signal.ellipord(self.wp,
                                     self.ws,
                                     self.template.att_p,
                                     self.template.att_s,
                                     analog=True)
        N_norm, self.wn_N = signal.ellipord(self.template.omega_pN,
                                            self.template.omega_sN,
                                            self.template.att_p,
                                            self.template.att_s,
                                            analog=True)

        if N < self.min_order:
            order = self.min_order
        elif N > self.max_order:
            order = self.max_order
        else:
            order = N

        return order
示例#31
0
    def BSmin(self, fil_dict):
        """Elliptic BP filter, minimum order"""
        self._get_params(fil_dict)
        self.N, self.F_PBC = ellipord([self.F_PB, self.F_PB2],
                                [self.F_SB, self.F_SB2], self.A_PB,self.A_SB,                                                       analog=self.analog)
#       force even N
        if (self.N%2)== 1:
            self.N += 1
        if not self._test_N():
            return -1  
        self._save(fil_dict, sig.ellip(self.N, self.A_PB, self.A_SB, self.F_PBC,
                        btype='bandstop', analog=self.analog, output=self.FRMT))
def get_ellip_bp2():
    """Elliptical filter frequency response."""
    wp = [1 / 19.0, 1 / 9.0]
    ws = [1 / 21.0, 1 / 8.0]
    gpass = 0.01
    gstop = 40
    N, Wn = ellipord(wp, ws, gpass, gstop, fs=1)
    b, a = ellip(N, gpass, gstop, Wn, 'bandpass', fs=1)
    fs = 1
    M = 512
    f, H = freqz(b, a, fs=fs, worN=M)
    return f, H
示例#33
0
    def LPmin(self, fil_dict):
        """Elliptic LP filter, minimum order"""
        self._get_params(fil_dict)
        self.N, self.F_PBC = ellipord(self.F_PB,self.F_SB, self.A_PB,self.A_SB,                                                        analog=self.analog)
#       force even N
        if (self.N%2)== 1:
            self.N += 1
        if not self._test_N():
            return -1              
        #logger.warning("and "+str(self.F_PBC) + " " + str(self.N))
        self._save(fil_dict, sig.ellip(self.N, self.A_PB, self.A_SB, self.F_PBC,
                            btype='low', analog=self.analog, output=self.FRMT))
def get_ellip_h1():
    """Elliptical filter frequency response."""
    wp = 1 / 7.0
    ws = 1 / 8.0
    gpass = 0.01
    gstop = 40
    N, Wn = ellipord(wp, ws, gpass, gstop, fs=1)
    b, a = ellip(N, gpass, gstop, Wn, 'high', fs=1)
    fs = 1
    M = 512
    f, H = freqz(b, a, fs=fs, worN=M)
    return f, H
示例#35
0
def highPassIIRellip(wav_file_path, plot_interval, verbose=False):
    # ------------------------------------------------
    # Create a signal.
    # ------------------------------------------------

    samplerate, x = wavfile.read(wav_file_path)
    nsamples = x.size
    t = arange(nsamples) / samplerate

    # ------------------------------------------------
    # Create a IIR filter and apply it to x.
    # ------------------------------------------------

    N, Wn = ellipord(wp=0.5, ws=0.45, gstop=60, gpass=1)
    b, a = ellip(N, 1, 60, Wn, btype='high')
    w, h = freqz(b, a, fs=240000)

    fig = plt.figure()
    h_dB = 20 * np.log10(np.abs(h))
    plt.plot(w, h_dB, 'b-')
    #plt.ylim(-150, 5)
    plt.ylabel('Magnitude (dB)')
    plt.xlabel('Frequency (Hz)')
    plt.grid(True)
    fig.savefig('results_a6/ellip_frequency_response.png', bbox_inches='tight')

    # Apply filtfilt to signal
    filtered_x = lfilter(b, a, x)
    wavfile.write('looneytunes_IIR_HP_6K.filtered_wav', samplerate, filtered_x)

    fig = plt.figure()
    # Plot the original signal.
    plt.subplot(2, 1, 1)
    plt.title('Original')
    plt.plot(t, x, 'b-', linewidth=0.5)
    plt.xlabel('Time (s)')
    plt.xlim(plot_interval)
    plt.ylim(-20500, 20500)
    plt.grid(True)
    # Plot the filtered signal, shifted to compensate for the phase delay.
    plt.subplot(2, 1, 2)
    plt.title('Filtered')
    plt.plot(t, filtered_x, 'g', linewidth=0.5)
    plt.xlim(plot_interval)
    plt.ylim(-20500, 20500)
    plt.xlabel('Time (s)')
    plt.grid(True)
    plt.subplots_adjust(hspace=0.7)
    fig.savefig('results_a6/ellip_filtered_output.png', bbox_inches='tight')

    if verbose:
        plt.show()
示例#36
0
 def BPmin(self, fil_dict):
     """Elliptic BP filter, minimum order"""
     self._get_params(fil_dict)
     self.N, self.F_PBC = ellipord([self.F_PB, self.F_PB2],
         [self.F_SB, self.F_SB2], self.A_PB, self.A_SB, analog=self.analog)
     #logger.warning(" "+str(self.F_PBC) + " " + str(self.N))
     if (self.N%2)== 1:
         self.N += 1
     if not self._test_N():
         return -1  
     #logger.warning("-"+str(self.F_PBC) + " " + str(self.A_SB))
     self._save(fil_dict, sig.ellip(self.N, self.A_PB, self.A_SB, self.F_PBC,
                     btype='bandpass', analog=self.analog, output=self.FRMT))
示例#37
0
def ellip_bp():
    fs = 48e3
    fpass = np.array([300, 4500])
    fstop = np.array([0, 5000])
    gpass = 1
    gstop = 60

    wpass = 2 * fpass / fs
    wstop = 2 * fstop / fs

    [order, wn] = signal.ellipord(wpass, wstop, gpass, gstop)
    print(wn)
    sos = signal.ellip(order, gpass, gstop, wn, btype='bandpass', output='sos')
    return sos
示例#38
0
def design(params):
  while(1): # Loop until we're happy with our parameters
    print(params)
    wp = params['wp']
    ws = params['ws']
    gstop = params['gstop']
    gpass = params['gpass']
    if wp < ws:
      btype = 'lowpass'
    else:
      btype = 'highpass'
    print(f'This is a {btype} filter.')
    
    # Calculate the orders of each filter type
    cheby1 = sig.cheb1ord(  
          params['wp'], params['ws'], params['gpass'], params['gstop'])
    cheby2 = sig.cheb2ord(
          params['wp'], params['ws'], params['gpass'], params['gstop'])
    butter = sig.buttord(
          params['wp'], params['ws'], params['gpass'], params['gstop'])
    elliptic = sig.ellipord(
          params['wp'], params['ws'], params['gpass'], params['gstop'])
    
    x = int(input(F'''Please select an implementation:
    1: Chebyshev type I ({cheby1[0]} order, corner at {cheby1[1]*nyquist} Hz)
    2: Chebyshev type II ({cheby2[0]} order, corner at {cheby2[1]*nyquist} Hz)
    3: Butterworth ({butter[0]} order, corner at {butter[1]*nyquist} Hz)
    4: Elliptic ({elliptic[0]} order, corner at {elliptic[1]*nyquist} Hz)
    5: Choose new design constraints
    6: Quit
    '''))
    if x == 1:
      sos = sig.cheby1(N=cheby1[0], rp=params['gpass'] , Wn=cheby1[1], 
                      btype=btype, output='sos' )
    elif x == 2:
      sos = sig.cheby2(N=cheby2[0], rs=params['gstop'] , Wn=cheby2[1], 
                      btype=btype, output='sos' )
    elif x == 3:
      sos = sig.butter(N=butter[0], Wn=butter[1], 
                      btype=btype, output='sos' )
    elif x == 4:
      sos = sig.ellip(N=elliptic[0], rp=params['gpass'], rs=params['gstop'], 
      Wn=elliptic[1], btype=btype, output='sos' )
    elif x==5:
      params = get_params()
      continue
    else:
      exit()
    return(sos,params) #Break out of the loop
示例#39
0
 def LPmin(self, fil_dict):
     """Elliptic LP filter, minimum order"""
     self._get_params(fil_dict)
     self.N, self.F_PBC = ellipord(self.F_PB,
                                   self.F_SB,
                                   self.A_PB,
                                   self.A_SB,
                                   analog=self.analog)
     self._save(
         fil_dict,
         sig.ellip(self.N,
                   self.A_PB,
                   self.A_SB,
                   self.F_PBC,
                   btype='low',
                   analog=self.analog,
                   output=self.FRMT))
示例#40
0
 def HPmin(self, fil_dict):
     """Elliptic HP filter, minimum order"""
     self.get_params(fil_dict)
     self.N, self.F_PBC = ellipord(self.F_PB,
                                   self.F_SB,
                                   self.A_PB,
                                   self.A_SB,
                                   analog=self.analog)
     self.save(
         fil_dict,
         sig.ellip(self.N,
                   self.A_PB,
                   self.A_SB,
                   self.F_PBC,
                   btype='highpass',
                   analog=self.analog,
                   output=frmt))
示例#41
0
 def BSmin(self, fil_dict):
     """Elliptic BP filter, minimum order"""
     self.get_params(fil_dict)
     self.N, self.F_PBC = ellipord([self.F_PB, self.F_PB2],
                                   [self.F_SB, self.F_SB2],
                                   self.A_PB,
                                   self.A_SB,
                                   analog=self.analog)
     self.save(
         fil_dict,
         sig.ellip(self.N,
                   self.A_PB,
                   self.A_SB,
                   self.F_PBC,
                   btype='bandstop',
                   analog=self.analog,
                   output=frmt))
示例#42
0
def pitch_filter_bank(ratios_pitches=None,
                      fs=16000,
                      Q=25.0,
                      max_loss_pass=1.0,
                      min_attenuation_stop=50.0):
    """
    lowest pitch: 20.6 Hz = pitch 16, the lowest pitch above the low threshold of hearing
    highest pitch: 7458.6 Hz = pitch 118, the highest pitch below half of the sampling frequency (fs = 16000Hz)
    Note that 119 is technically below the nyquist frequency (~7900Hz), but the right stopband frequency wouldn't be.
    
    fs: sampling frequency of the input in Hz
    Q: Q factor = frequency / bandwidth, used to determine passband and stopband frequencies of the elliptic filters
    max_loss_pass: maximal loss in passband in dB
    min_attenuation_stop: minimal attenuation in stopband in dB
    """
    if ratios_pitches is None:
        ratios_pitches = RATIOS_PITCHES_DEFAULT
        # structure: tuples of sampling frequency ratios and sets of pitches

    filters = {
    }  # dictionary indexed by sampling frequency ratio. Each item is again a dictionary indexed by pitch, giving a filter coefficient tuple.

    for ratio, pitches in ratios_pitches:
        filters[ratio] = {}
        current_fs = float(
            fs /
            ratio)  # input sampling frequency for the current set of pitches
        nyquist_freq = current_fs / 2
        for pitch in pitches:
            freq = pitch2freq(pitch)
            w = freq / nyquist_freq  # omega = normalised frequency
            w_pass = (w * (1 - 1 / (2 * Q)), w * (1 + 1 / (2 * Q)))
            w_stop = (w * (1 - 1 / Q), w * (1 + 1 / Q))
            n, w_natural = sig.ellipord(w_pass, w_stop, max_loss_pass,
                                        min_attenuation_stop)
            coeff_b, coeff_a = sig.ellip(
                n,
                max_loss_pass,
                min_attenuation_stop,
                w_natural,
                btype='bandpass')  # get filter coefficients
            # note that scipy's ellip differs from matlab's in that it will always generate a lowpass filter by default.
            # btype='bandpass' needs to be passed explicitly!
            filters[ratio][pitch] = (coeff_b, coeff_a)

    return filters
示例#43
0
def calcFiltros(A1,A2,Wc,Wp):
    plt.figure()
    Nb, Wnb = signal.buttord(Wp,Wc,A1,A2,True)  
    Nc, Wnc = signal.cheb1ord(Wp,Wc,A1,A2,True)
    Ne, Wne = signal.ellipord(Wp,Wc,A1,A2,True)

    print('Butterbord Wp =' + str(Wp))
    print("N = "+ str(Nb) )
    print("Wn = "+ str(Wnb) )
    Zb,Pb,Kb = signal.buttap(Nb)
    ab,bb = signal.zpk2tf(Zb,Pb,Kb)
    print("H(s) = ")
    strFunTrans = funTrans([ab,bb])
    print(strFunTrans)
    print("\n")
    wb, hb = freqs(ab, bb)
    plt.semilogx(wb, abs(hb))

    print('Chebychev Wp =' + str(Wp))
    print("N = "+ str(Nc) )
    print("Wn = "+ str(Wnc) )
    Zc,Pc,Kc = signal.buttap(Nc)
    ac,bc = signal.zpk2tf(Zc,Pc,Kc)
    print("H(s) = ")
    strFunTrans = funTrans([ac,bc])
    print(strFunTrans)
    print("\n")
    wc, hc = freqs(ac, bc)  
    plt.semilogx(wc, abs(hc))

    print('Eliptica Wp =' + str(Wp))
    print("N = "+ str(Ne) )
    print("Wn = "+ str(Wne) )
    Ze,Pe,Ke = signal.buttap(Ne)
    ae,be = signal.zpk2tf(Ze,Pe,Ke)
    print("H(s) = ")
    strFunTrans = funTrans([ae,be])
    print(strFunTrans)
    print("\n")  
    we, he = freqs(ae, be)
    plt.semilogx(we, abs(he))

    plt.xlabel('Frequency')
    plt.ylabel('Amplitude response')
    plt.grid()
示例#44
0
 def __filter_order(self):
     """ Computing filters order and maximum value of X axis. """
     if self.ftype == "butter":
         if self.btype == 'highpass':
             self.xaxis_max = 0.2
         else:
             self.xaxis_max = 0.15
         (self.ord, self.wn) = signal.buttord(self.wp_norm,
                                              self.ws_norm,
                                              self.gpass,
                                              self.gstop,
                                              analog=True)
     elif self.ftype == "cheby1":
         if self.btype == 'highpass':
             self.xaxis_max = 0.6
         else:
             self.xaxis_max = 0.15
         (self.ord, self.wn) = signal.cheb1ord(self.wp_norm,
                                               self.ws_norm,
                                               self.gpass,
                                               self.gstop,
                                               analog=True)
     elif self.ftype == "cheby2":
         if self.btype == 'highpass':
             self.xaxis_max = 0.2
         else:
             self.xaxis_max = 0.3
         (self.ord, self.wn) = signal.cheb2ord(self.wp_norm,
                                               self.ws_norm,
                                               self.gpass,
                                               self.gstop,
                                               analog=True)
     elif self.ftype == "ellip":
         if self.btype == 'highpass':
             self.xaxis_max = 0.6
         else:
             self.xaxis_max = 0.2
         (self.ord, self.wn) = signal.ellipord(self.wp_norm,
                                               self.ws_norm,
                                               self.gpass,
                                               self.gstop,
                                               analog=True)
示例#45
0
 def _compute_parameters(self):
     normalized_pb, normalized_sb = self.normalized_pb_sb()
     self.N, self.Wn = signal.ellipord(normalized_pb, normalized_sb,
                                       self.filter_parameters['passband_attenuation'],
                                       self.filter_parameters['stopband_attenuation'])
     self.already_normalized_Wn = True
data_suav=data
#se calcula es espectro de la senal suavizada para poder ver las frecuencias que externas que pueden estar afectando la medida
# por lo general la senal de ecg tiene su  mayor informacion distribida entre 0 y 40 hz
spectr=np.absolute(fft(data_suav))


###########################################
####      ETAPA DE  FILTRADO          #####
########################################### 

# se disena un filtro pasa altas para poder eliminar el valor dc y tratar de atenuar frecuencias  muy bajas que de acuerdo a la 
# literatura afecta a la senal para los propósitos que se buscan aqui
# se va a usar un filtro eliptico pasa altas que provee scipy
wl1=(2.0)*(1.0)/(fs)
wl2=(2.0)*(0.00001)/(fs)
N2,Wn2=signal.ellipord(wl1,wl2,9.0,10.0)
b1,a1=signal.ellip(N2,9.0,10.0,Wn2,'high')
w1,h1=signal.freqz(b1,a1,fs)
# elaborado el filtro se procede a pasar la senal por este
senal_high=signal.lfilter(b1,a1,data_suav)

#se comienza el diseno del filtro pasabajas usando un filtro eliptico, la senal de ecg tiene su mayor informacion entre 0 y 40 hz, el filtro
#pasabajas es usado con el fin de eliminar todas las componentes que esten por encima de 40 hz, adempas permite eliminar el ruido introducido
# por las lineas de alimentacion que afecta las frecuencias de 50 y 60 hz
wp1=(2.0)*(30.0)/(fs)
wp2=(2.0)*(40.0)/(fs)
N,Wn=signal.ellipord(wp1,wp2,0.01,100.0)
b,a=signal.ellip(N,0.01,100.0,Wn)
w,h=signal.freqz(b,a,fs,0)
#disenado el filtro se hace pasar la senal por el
senal_filtrada1=signal.lfilter(b,a,senal_high)