Exemplo n.º 1
0
def butter_filter(x, y, cutoffs, Btype = 'low', ax = 0, bl = 3, GP = 1, GS = 30, padtype=None, padlen = None):
    """
    low, high or band pass butterworth filter: cutoffs is the low and high frq edges
    of pass band. 
    """
    x = x - x[0]
    if x.ndim == 1:
        dt = np.diff(x).mean()
        df = 1./(x[-1]-x[0])
    else:
        dt = np.diff(x, axis=0).mean()
        df = (1./(x[-1]-x[0]))[0]
    
    nyq = 0.5 * (1. / dt)
    bl = int(bl)
    
    if Btype == 'band':
        order, wc = buttord(cutoffs/nyq, [cutoffs[0]-bl*df, cutoffs[1]+bl*df]/nyq, gpass = GP, gstop = GS)
    elif Btype == 'low':
        order, wc = buttord(cutoffs/nyq, (cutoffs+bl*df)/nyq, gpass = GP, gstop = GS)
    elif Btype == 'high':
        order, wc = buttord(cutoffs/nyq, (cutoffs-bl*df)/nyq, gpass = GP, gstop = GS)
    else:
        raise ValueError, "Btype is low, high or band only."
    
    b, a = butter(order, wc, btype = Btype)
    yn = filtfilt(b, a, y, axis = ax, padtype = padtype, padlen = padlen)
    
    return yn
Exemplo n.º 2
0
def prepare_audio_filters():
    tf_rangel = 100000
    tf_rangeh = 170000

    # audio filters
    tf = SysParams['audio_lfreq']
    N, Wn = sps.buttord([(tf - tf_rangel) / (freq_hz / 2.0),
                         (tf + tf_rangel) / (freq_hz / 2.0)],
                        [(tf - tf_rangeh) / (freq_hz / 2.0),
                         (tf + tf_rangeh) / (freq_hz / 2.0)], 5, 15)
    Faudl = filtfft(sps.butter(N, Wn, btype='bandpass'))

    tf = SysParams['audio_rfreq']
    N, Wn = sps.buttord([(tf - tf_rangel) / (freq_hz / 2.0),
                         (tf + tf_rangel) / (freq_hz / 2.0)],
                        [(tf - tf_rangeh) / (freq_hz / 2.0),
                         (tf + tf_rangeh) / (freq_hz / 2.0)], 5, 15)
    Faudr = filtfft(sps.butter(N, Wn, btype='bandpass'))

    N, Wn = sps.buttord(0.016 / (afreq / 2.0), 0.024 / (afreq / 2.0), 5, 15)
    FiltAPost = filtfft(sps.butter(N, Wn))

    N, Wn = sps.buttord(3.1 / (freq / 2.0), 3.5 / (freq / 2.0), 1, 20)
    SysParams['fft_audiorf_lpf'] = Faudrf = filtfft(
        sps.butter(N, Wn, btype='lowpass'))

    SysParams['fft_audiolpf'] = FiltAPost  #* FiltAPost * FiltAPost

    SysParams['fft_audio_left'] = Faudrf * Faudl * fft_hilbert
    SysParams['fft_audio_right'] = Faudrf * Faudr * fft_hilbert
Exemplo n.º 3
0
Arquivo: filter.py Projeto: Dengg/mtpy
def butter_bandpass(lowcut, highcut, samplingrate, order=4):
    nyq = 0.5 * samplingrate
    low = lowcut / nyq
    high = highcut / nyq
    print high, low
    if high >=1. and low == 0.:
        b = np.array([1.])
        a = np.array([1.])

    elif high < 0.95 and low > 0. :
        wp = [1.05*low,high-0.05]
        ws = [0.95*low,high+0.05]
 
        print wp,ws
        order,wn = buttord(wp,ws,0., 30.)
        b, a = butter(order, wn, btype='band')
    
    elif high>= 0.95:
        print 'highpass',low,1.2*low,0.8*low
        order,wn = buttord( 15*low,0.05*low,gpass=0.0, gstop=10.0)
        print order,wn
        b, a = butter(order, wn, btype='high')
    elif low <= 0.05:
        print 'lowpass',high
        order,wn = buttord( high-0.05,high+0.05,gpass=0.0, gstop=10.0)
        b, a = butter(order, wn, btype='low')

    return b, a
Exemplo n.º 4
0
def butter_bandpass(lowcut, highcut, samplingrate, order=4):
    nyq = 0.5 * samplingrate
    low = lowcut / nyq
    high = highcut / nyq

    if high >= 1. and low == 0.:
        b = np.array([1.])
        a = np.array([1.])

    elif high < 0.95 and low > 0.:
        wp = [1.05 * low, high - 0.05]
        ws = [0.95 * low, high + 0.05]

        order, wn = signal.buttord(wp, ws, 3., 40.)
        b, a = signal.butter(order, wn, btype='band')

    elif high >= 0.95:
        print 'highpass', low, 1.2 * low, 0.8 * low
        order, wn = signal.buttord(15 * low, 0.05 * low, gpass=0.0, gstop=10.0)
        print order, wn
        b, a = signal.butter(order, wn, btype='high')

    elif low <= 0.05:
        print 'lowpass', high
        order, wn = signal.buttord(high - 0.05,
                                   high + 0.05,
                                   gpass=0.0,
                                   gstop=10.0)
        b, a = signal.butter(order, wn, btype='low')

    return b, a
Exemplo n.º 5
0
def prepare_audio_filters():
    tf_rangel = 100000
    tf_rangeh = 170000

    # audio filters
    tf = SysParams["audio_lfreq"]
    N, Wn = sps.buttord(
        [(tf - tf_rangel) / (freq_hz / 2.0), (tf + tf_rangel) / (freq_hz / 2.0)],
        [(tf - tf_rangeh) / (freq_hz / 2.0), (tf + tf_rangeh) / (freq_hz / 2.0)],
        5,
        15,
    )
    Faudl = filtfft(sps.butter(N, Wn, btype="bandpass"))

    tf = SysParams["audio_rfreq"]
    N, Wn = sps.buttord(
        [(tf - tf_rangel) / (freq_hz / 2.0), (tf + tf_rangel) / (freq_hz / 2.0)],
        [(tf - tf_rangeh) / (freq_hz / 2.0), (tf + tf_rangeh) / (freq_hz / 2.0)],
        5,
        15,
    )
    Faudr = filtfft(sps.butter(N, Wn, btype="bandpass"))

    N, Wn = sps.buttord(0.016 / (afreq / 2.0), 0.024 / (afreq / 2.0), 5, 15)
    FiltAPost = filtfft(sps.butter(N, Wn))

    N, Wn = sps.buttord(3.1 / (freq / 2.0), 3.5 / (freq / 2.0), 1, 20)
    SysParams["fft_audiorf_lpf"] = Faudrf = filtfft(sps.butter(N, Wn, btype="lowpass"))

    SysParams["fft_audiolpf"] = FiltAPost  # * FiltAPost * FiltAPost

    SysParams["fft_audio_left"] = Faudrf * Faudl * fft_hilbert
    SysParams["fft_audio_right"] = Faudrf * Faudr * fft_hilbert
Exemplo n.º 6
0
def prepare_audio_filters():
    forder = 256
    forderd = 0

    tf_rangel = 100000
    tf_rangeh = 170000
    # audio filters
    tf = SP["audio_lfreq"]
    N, Wn = sps.buttord(
        [(tf - tf_rangel) / (freq_hz / 2.0), (tf + tf_rangel) / (freq_hz / 2.0)],
        [(tf - tf_rangeh) / (freq_hz / 2.0), (tf + tf_rangeh) / (freq_hz / 2.0)],
        1,
        15,
    )
    Baudl, Aaudl = sps.butter(N, Wn, btype="bandpass")

    tf = SP["audio_rfreq"]
    N, Wn = sps.buttord(
        [(tf - tf_rangel) / (freq_hz / 2.0), (tf + tf_rangel) / (freq_hz / 2.0)],
        [(tf - tf_rangeh) / (freq_hz / 2.0), (tf + tf_rangeh) / (freq_hz / 2.0)],
        1,
        15,
    )
    N, Wn = sps.buttord(
        [(tf - tf_rangel) / (freq_hz / 2.0), (tf + tf_rangel) / (freq_hz / 2.0)],
        [(tf - tf_rangeh) / (freq_hz / 2.0), (tf + tf_rangeh) / (freq_hz / 2.0)],
        5,
        15,
    )
    Baudr, Aaudr = sps.butter(N, Wn, btype="bandpass")

    N, Wn = sps.buttord(0.016 / (afreq / 2.0), 0.024 / (afreq / 2.0), 2, 15)
    audiolp_filter_b, audiolp_filter_a = sps.butter(N, Wn)

    # USE FIR
    audiolp_filter_b = sps.firwin(257, 0.020 / (afreq / 2.0))
    audiolp_filter_a = [1.0]

    N, Wn = sps.buttord(3.1 / (freq / 2.0), 3.5 / (freq / 2.0), 1, 20)
    audiorf_filter_b, audiorf_filter_a = sps.butter(N, Wn, btype="lowpass")

    [Baudrf_FDLS, Aaudrf_FDLS] = fdls.FDLS_fromfilt(audiorf_filter_b, audiorf_filter_a, forder, forderd, 0)
    SP["fft_audiorf_lpf"] = Faudrf = np.fft.fft(Baudrf_FDLS, blocklen)

    [Baudiolp_FDLS, Aaudiolp_FDLS] = fdls.FDLS_fromfilt(audiolp_filter_b, audiolp_filter_a, forder, forderd, 0)

    FiltAPost = np.fft.fft(Baudiolp_FDLS, blocklen)
    SP["fft_audiolpf"] = FiltAPost * FiltAPost  # * FiltAPost

    [Baudl_FDLS, Aaudl_FDLS] = fdls.FDLS_fromfilt(Baudl, Aaudl, forder, forderd, 0)
    [Baudr_FDLS, Aaudr_FDLS] = fdls.FDLS_fromfilt(Baudr, Aaudr, forder, forderd, 0)

    Faudl = np.fft.fft(Baudl_FDLS, blocklen)
    Faudr = np.fft.fft(Baudr_FDLS, blocklen)

    SP["fft_audio_left"] = Faudrf * Faudl * fft_hilbert
    SP["fft_audio_right"] = Faudrf * Faudr * fft_hilbert
Exemplo n.º 7
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
Exemplo n.º 8
0
    def ButterworthBandpass(self,data,sampleRate,low=0,high=None,minFreq=0,maxFreq=None,order=10,band=50):
        """ Basic IIR bandpass filter.
        Identifies order of filter, max 10.

        """
        if data is None:
            data = self.data
        if sampleRate is None:
            sampleRate = self.sampleRate
        if high is None:
            high = sampleRate/2
        if maxFreq is None:
            maxFreq = sampleRate/2
        low = max(low,0,minFreq)
        high = min(high,maxFreq,sampleRate/2)

        if low == minFreq and high == maxFreq:
            print("No filter needed!")
            return data

        nyquist = sampleRate/2

        if low == minFreq:
            # Low pass
            cut1 = high/nyquist
            cut2 = (high+band)/nyquist
            # calculate the best order
            order,wN = signal.buttord(cut1, cut2, 3, band)
            if order>10:
                order=10
            b, a = signal.butter(order,wN,btype='lowpass')
        elif high == maxFreq:
            # High pass
            cut1 = low/nyquist
            cut2 = (low-band)/nyquist
            # calculate the best order
            order,wN = signal.buttord(cut1, cut2, 3, band)
            if order>10:
                order=10
            b, a = signal.butter(order,wN, btype='highpass')
        else:
            # Band pass
            lowPass = low/nyquist
            highPass = high/nyquist
            lowStop = (low-band)/nyquist
            highStop = (high+band)/nyquist
            # calculate the best order
            order,wN = signal.buttord([lowPass, highPass], [lowStop, highStop], 3, band)
            if order>10:
                order=10
            b, a = signal.butter(order,wN, btype='bandpass')
            #b, a = signal.butter(order,[lowPass, highPass], btype='bandpass')

        return signal.filtfilt(b, a, data)
Exemplo n.º 9
0
    def _build_lpfilter(self, fs):
        """
        builds low-pass filter with a cutoff frequency of 3/7th the resample
        frequency. The filter should be down 40 dB at 1.5 times the cutoff
        frequency (6/7th) the resample frequency.

        Parameters
        ----------
        fs : the base sampling rate

        Returns
        -------
        b, a : array_like
            Numerator (b) and denominator (a) polynomials of the IIR filter. 
        """
        nyq = fs / 2.  # nyquist frequency
        cutoff = (3. / 7.) * self.resample_fs  # cutoff freq defined by Boer
        wp = cutoff * nyq  # pass edge freq (pi radians / sample)
        ws = wp * 2.  # pass edge freq (pi radians / sample)
        gpass = 1.5  # The maximum loss in the passband (dB)
        gstop = 40  # The minimum attenuation in the stopband (dB)
        n, wn = buttord(wp, ws, gpass, gstop)
        #print('n =',n,'wn =',wn)
        b, a = butter(n, wn, analog=True)

        return b, a
Exemplo n.º 10
0
def bpf(x, pass_freq=[3., 35.], cut_freq=[0.5, 40.], sample_rate=100):
  wp = list(np.array(pass_freq)/(sample_rate/2))
  ws = list(np.array(cut_freq)/(sample_rate/2))
  N, Wn = signal.buttord(wp, ws, 3, 40, False)
  b, a = signal.butter(N, Wn, btype='bandpass', analog=False, output='ba')
  y = signal.lfilter(b, a, x)
  return y
Exemplo n.º 11
0
def lpf(x, pass_freq=35., cut_freq=40., sample_rate=100):
  wp = pass_freq/(sample_rate/2)
  ws = cut_freq/(sample_rate/2)
  N, Wn = signal.buttord(wp, ws, 3, 40, False)
  b, a = signal.butter(N, Wn, btype='low', analog=False, output='ba')
  y = signal.lfilter(b, a, x)
  return y
Exemplo n.º 12
0
    def __init2(self, _wp, ws, filter, *args):

        if ws is not None:
            order, _wp = buttord(_wp, ws, args[0], args[1])
            if (len(np.atleast_1d(_wp)) == 1) and (filter[0].lower() == 'b'):
                if filter == 'bandpass':
                    filter = 'highpass'
                else:
                    filter = 'lowpass'
        else:
            order = self.ord

        #----------------------------------------------------------------------
        _sos = butter(order, _wp, btype=filter, output='sos')

        a, b = np.zeros([len(_sos), 3]), np.zeros([len(_sos), 3])
        #----------------------------------------------------------------------

        for i in range(len(_sos)):
            a[i] = _sos[i][3:]
            b[i] = _sos[i][:3]

        self.sos.append(np.zeros(len(a)))
        self.sos[self.flag] = [__sos__(a[i], b[i]) for i in range(len(a))]
        self.flag += 1

        return None
Exemplo n.º 13
0
    def __init__(self):
        # オーディオに関する設定
        self.p = pyaudio.PyAudio()
        self.channels = 1  # マイクがモノラルの場合は1にしないといけない
        self.rate = 16000  #48000 # DVDレベルなので重かったら16000にする
        self.CHUNK = 2**11
        self.format = pyaudio.paInt16
        self.stream = self.p.open(format=self.format,
                                  channels=self.channels,
                                  rate=self.rate,
                                  frames_per_buffer=self.CHUNK,
                                  output=True,
                                  input=True,
                                  stream_callback=self.callback,
                                  input_device_index=4)
        self.ndarray = np.array([])
        self.alldata = np.array([])
        self.cnt = -1

        self.fpass = 1.0 * 10**2  # 通過遮断周波数[Hz]
        self.fstop = 1.0 * 10**3  # 阻止域遮断周波数[Hz]
        self.gpass = 0.4  # 通過域最大損失量[dB]
        self.gstop = 30  # 阻止域最小減衰量[dB]

        #正規化
        self.fn = self.rate / 2
        self.wp = self.fpass / self.fn
        self.ws = self.fstop / self.fn
        #フィルタの係数設計(バタワースフィルタ)
        self.N, self.Wn = signal.buttord(self.wp, self.ws, self.gpass,
                                         self.gstop)  #オーダーとバターワースの正規化周波数を計算
        self.b, self.a = signal.butter(self.N, self.Wn,
                                       "highpass")  #フィルタ伝達関数の分子と分母を計算
def low_pass_filter(signal, fs, end_freq):
    """
    Description
     - Low Pass Filter

    Input
     :param signal:list, 입력 신호
     :param fs: Float, 샘플링 주파수 (sampling frequency)
     :param end_freq: Float, 끝 주파수 (passband)

    Output
     :return list, 필터링된 신호

    Example:
        >>> signal = [0, 1, 2, 3, 2, 1, 0, -1, -2, -3, -2, -1]
        >>> fs = 0.1
        >>> end_freq = 0.02
        >>> low_pass_filter(signal, fs, end_freq)
        array([-7.04764275e-05,  1.06577490e+00,  2.14355722e+00,  2.64998306e+00,
                2.14375040e+00,  1.06552842e+00, -1.00019323e-03, -1.06409485e+00,
               -2.13795954e+00, -2.66057414e+00, -2.17495858e+00, -9.99904965e-01])
    """

    n, wn = buttord(2 * end_freq / fs, 4 * end_freq / fs, 1, 10)  # 'Butterworth Filter'의 차수(order) 구하기
    b, a = butter(n, wn, btype='low')  # 'Butterworth Filter'의 a와 b 파라메터 생성
    sos = tf2sos(b, a)  # 2차수(order) 필터 계수의 배열 구하기

    signal = np.array(signal).reshape(-1)  # 1차원 리스트가 아닌 경우를 위해 1차원으로 변환

    filtered_signal = sosfiltfilt(sos, signal)  # A forward-backward digital filter using cascaded second-order sections.

    return filtered_signal
def high_pass_filter(signal, fs, start_freq, start_stop_freq):
    """
    Description
     - High Pass Filter

    Input
     :param signal:list, 입력 신호
     :param fs: Float, 샘플링 주파수 (sampling frequency)
     :param start_freq: Float, 시작 주파수 (passband)
     :param start_stop_freq: Float, 시작 주파수의 여유 (stopband)

    Output
     :return list, 필터링된 신호

    Example
    >>> signal = [0, 1, 2, 3, 2, 1, 0, -1, -2, -3, -2, -1]
    >>> fs = 0.1
    >>> start_freq = 0.02
    >>> start_stop_freq = 0.03
    >>> high_pass_filter(signal, fs, start_freq, start_stop_freq)
    array([ 0.        ,  0.02923319, -0.12894364,  0.17272625, -0.05544299,
            0.11883306, -0.36247096,  0.09681751,  0.32750824, -0.02172602,
           -0.20884044, -0.34628683])
    """

    n, wn = buttord(start_freq / fs * 2, start_stop_freq / fs * 2, 3, 40)  # 'Butterworth Filter'의 차수(order) 구하기
    b, a = butter(n, wn, btype='high')  # 'Butterworth Filter'의 a와 b 파라메터 생성
    filtered_signal = lfilter(b, a, signal, axis=0)  # A forward-backward digital filter using cascaded second-order sections.

    return filtered_signal
Exemplo n.º 16
0
 def onWsChange(self, ws):
     self.ws = ws / 10
     n1, wn1 = sig.buttord(self.wp, self.ws, self.alphap, self.alphas)
     B, A = sig.butter(n1, wn1)
     w2, h2 = sig.freqz(B, A, 1000)
     self.p1.setData(w2, np.abs(h2))
     self.wsBox.setValue(self.ws)
Exemplo n.º 17
0
    def filter_FMC(self,lowcut,highcut):
        # Backwards compatibility stuff:
        if not hasattr(self, 'Filtered'):
            self.Filtered = False

        if self.Filtered:
            self.Unpacked=False

       # Design filter with parameters...
        pass_stop_width = 0.8
        nyq = 0.5 * self.Fs
        low = lowcut / nyq
        high = highcut / nyq
        order = buttord([low, high],[low*pass_stop_width, high*(2-pass_stop_width)],3,30)
        print('Designing filter with order {}'.format(order[0]))
        b, a = butter(order[0], [low, high], btype='band')
        
        # Apply filter to FMC
        FMC = self.get_FMC()
        n_scans = FMC.shape[0]
        for idx in range(n_scans):
            a_scan = FMC[idx,:]
            a_scan = filtfilt(b, a, a_scan)
            FMC[idx,:] = a_scan
        self.FMC = FMC
        self.Filtered=True
Exemplo n.º 18
0
def _LP_Butterworth(interval, sampling_rate, cutoff, order=5):

    nyq = sampling_rate * 0.5

    stopfreq = float(cutoff)
    cornerfreq = 0.5 * stopfreq
    Ws = stopfreq / nyq
    Wp = cornerfreq / nyq
    N, Wn = buttord(Wp, Ws, 3, 20)  # (?)
    print "The oder of LPF is: %f" % N

    """
    Wp = 2 * np.pi * 100
    Ws = 2 * np.pi * 20
    Rp = 1.5
    Rs = 20
    N, Wn = buttord(Wp, Ws, Rp, Rs)   # (?)
    """

    # for hardcoded order:
    # N = order

    b, a = butter(N, Wn, btype="low")  # should 'high' be here for bandpass?
    # b, a = butter(9, float(20.0/nyq) , btype='high')   # should 'high' be here for bandpass?
    sf = lfilter(b, a, interval)
    return sf, b, a
Exemplo n.º 19
0
 def onAlphapChange(self, alphap):
     self.alphap = alphap
     n1, wn1 = sig.buttord(self.wp, self.ws, self.alphap, self.alphas)
     B, A = sig.butter(n1, wn1)
     w2, h2 = sig.freqz(B, A, 1000)
     self.p1.setData(w2, np.abs(h2))
     self.alphapBox.setValue(self.alphap)
Exemplo n.º 20
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
Exemplo n.º 21
0
def power_line_filter(data, Fs):
    N, Wn = signal.buttord(wp=[48 / Fs, 53 / Fs],
                           ws=[46 / Fs, 55 / Fs],
                           gpass=0.1,
                           gstop=10.0,
                           analog=False)
    b, a = signal.butter(N, Wn, 'bandstop', False)

    w, h = signal.freqz(b, a)
    fig = plt.figure()
    plt.title('Digital filter frequency response')
    ax1 = fig.add_subplot(111)

    plt.plot(w, 20 * np.log10(abs(h)), 'b')
    plt.ylabel('Amplitude [dB]', color='b')
    plt.xlabel('Frequency [rad/sample]')

    ax2 = ax1.twinx()
    angles = np.unwrap(np.angle(h))
    plt.plot(w, angles, 'g')
    plt.ylabel('Angle (radians)', color='g')
    plt.grid()
    plt.axis('tight')
    # plt.show()

    y = signal.lfilter(b, a, data)

    return y
Exemplo n.º 22
0
def besselord(omega_p, omega_s, alfa_max, alfa_min, omega_d, max_pc_delay):

    min_order = 0

    # partimos de suponer que al menos será el orden de un Butter o más grande
    start_order, _ = sig.buttord(omega_p,
                                 omega_s,
                                 alfa_max,
                                 alfa_min + alfa_max,
                                 analog=True)

    # de forma iterativa, intentamos cumplimentar la plantilla
    for ii in range(start_order, 20):

        z, p, k = sig.besselap(ii, norm='delay')

        this_lti = sig.ZerosPolesGain(z, p, k).to_tf()

        _, mm, pp = sig.bode(this_lti,
                             w=[0, 0.0001, omega_p, omega_d, omega_d + 0.0001])

        # attenuation in omega_p, i.e. bandpass end
        this_ripple = -mm[2]

        # relative delay
        this_delay = 1 - np.abs((pp[4] - pp[3]) / (pp[1] - pp[0]))

        if this_ripple <= alfa_max and this_delay <= max_pc_delay:
            break

    min_order = ii

    return min_order
Exemplo n.º 23
0
def lpf(fs, wave, cutoff):
    WP = float(cutoff) / float(fs / 2)
    WS = 1.3 * WP
    N, Wn = sg.buttord(wp=WP, ws=WS, gpass=2, gstop=30, analog=0)
    b, a = sg.butter(N, Wn, btype='low', analog=0, output='ba')
    g = sg.lfilter(b, a, wave)
    return g
Exemplo n.º 24
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
Exemplo n.º 25
0
def butter_lowpass(fr, step, arr, fps=250):
    
    #N, Wn = signal.buttord(1./(1.*fps/step),1./fps, 1/step, fps*0.5)
    N, Wn = buttord(fr/step, fr, 1/step, fps*0.5 ,0.5/fps)
    b, a = butter(N, Wn,'low')
    y = filtfilt(b, a, arr)
    return y
Exemplo n.º 26
0
    def low_pass_filter(self, fp, fs, g_pass, g_stop):
        '''
            Butterworth filter (low pass)

            https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.butter.html
            https://watlab-blog.com/2019/04/30/scipy-lowpass/
        '''
        samples = np.array(self.audio.get_array_of_samples())
        channels = self.audio.channels
        frame_rate = self.audio.frame_rate
        # print(f'samples dim: {samples.ndim} / shape: {samples.shape}\nchannels: {channels}\nfame_rate: {frame_rate}')

        fn = frame_rate / 2
        wp = fp / fn
        ws = fs / fn
        N, Wn = signal.buttord(wp, ws, g_pass, g_stop)
        b, a = signal.butter(N, Wn, 'low')
        sample_res = np.zeros(samples.shape[0], dtype=np.float64)

        for i in range(channels):
            sample_m = samples[i::channels]
            sample_res[i::channels] = signal.filtfilt(
                b, a, sample_m)  # チャンネルごとにフィルタを適用
        # print(samples[1000000:1000010])
        # print(sample_res[1000000:1000010])

        # print(f'samples dim: {samples.ndim} / shape: {sample_res.shape}\nwidth: {self.audio.sample_width}')
        res = AudioSegment(
            sample_res.astype(np.int16).tobytes(),
            sample_width=self.audio.sample_width,
            frame_rate=frame_rate,
            channels=channels,
        )
        return res
Exemplo n.º 27
0
def makefiltersos(sr,fp,fs,gp=3,gs=20):
	""" 	Wrapper function around scipy filter functions.  
	Makes it convenient by providing frequency parameters in terms of 
	frequencies in Hz.   
	INPUT: 	sr - sampling rate in Hz. 
		fp - pass frequency in Hz
		fs - stop frequency in Hz
		gp - pass band ripple in dB, default 3 dB
		gs - stop band attenuation in dB, default 20 dB
		doPlot - make a plot of filter gain versus frequency, default 'no'
	OUTPUT: sos filter coefficients. 
			w,h for making bode plot 
	Automatically detects the type of filter.  if fp < fs the filter
	is low pass but if fp > fs the filter is highpass.  """
#
#set up filter parameters

	fn = sr/2
	wp = fp/fn
	ws = fs/fn
#get the filter order

	n,wn = signal.buttord(wp,ws,gp,gs);                                                            
#design the filter

#lowpass 
	if fp < fs:
		sos = signal.butter(n,wn,btype='lowpass',output='sos')
#highpass
	if fs < fp:
		sos = signal.butter(n,wn,btype='highpass',output='sos')
#get filter respons function	
	w,h = signal.sosfreqz(sos,fs=sr)
	return sos,w,h
Exemplo n.º 28
0
def noise_removal_cheat(source_image, npy=True, show=False):
    if npy:
        source_image = np.load(source_image)
    Fp = 650
    Fc = 750
    Fe = 1600

    order, Wn = signal.buttord(2 * Fp / Fe, 2 * Fc / Fe, gpass=0.5, gstop=40)
    print(order)
    #order = 2
    b, a, *_ = signal.butter(order, Wn)

    if show:
        plt.figure()
        x, y = signal.freqz(b, a)
        plt.plot(x, 20 * np.log10(abs(y)))
        plt.title("Gain de la réponse en fréquence")
        plt.xlabel("Multiple fréquence gauchie (pi)")
        plt.ylabel("Gain (dB)")
        plt.show()

        print(a)
        print(b)
        zplane.zplane(b, a)
    output = signal.lfilter(b, a, source_image)

    if show:
        plt.figure()
        plt.title('Image débruitée - méthode butterworth')
        plt.imshow(output, cmap='gray')
        plt.show()
    return output
Exemplo n.º 29
0
def lpf(f, cutoff):
    WP = float(cutoff) / float(Fs / 2)
    WS = 1.3 * WP
    N, Wn = buttord(wp=WP, ws=WS, gpass=2, gstop=30, analog=0)
    b, a = butter(N, Wn, btype='low', analog=0, output='ba')
    g = lfilter(b, a, f)
    return g
Exemplo n.º 30
0
def prob3a():
    Fe = 48000
    wp = 2500 / (Fe / 2)
    ws = 3500 / (Fe / 2)
    gpass = 0.2
    gstop = 40

    print(wp, ws)

    order, wn = signal.buttord(wp, ws, gpass, gstop, False, Fe)
    num, denum = signal.butter(order, wn, 'lowpass', False, output='ba')

    print(order)

    w, Hw = signal.freqz(num, denum)

    plt.figure()
    plt.plot(w * Fe / (2 * pi), dB(np.abs(Hw)))  # En frequences
    plt.title('Butter')

    num, denum, k = signal.butter(order, wn, 'lowpass', False)

    plt.figure()
    zplane(num, denum)
    print(k)
Exemplo n.º 31
0
    def _build_lpfilter(self, fs):
        """
        builds low-pass filter with a cutoff frequency of 3/7th the resample
        frequency. The filter should be down 40 dB at 1.5 times the cutoff
        frequency (6/7th) the resample frequency.

        Parameters
        ----------
        fs : the base sampling rate

        Returns
        -------
        b, a : array_like
            Numerator (b) and denominator (a) polynomials of the IIR filter. 
        """
        nyq = fs/2. # nyquist frequency
        cutoff = (3./7.)*self.resample_fs # cutoff freq defined by Boer
        wp = cutoff * nyq # pass edge freq (pi radians / sample)
        ws = wp*2.        # pass edge freq (pi radians / sample)
        gpass = 1.5       # The maximum loss in the passband (dB)
        gstop = 40        # The minimum attenuation in the stopband (dB)
        n, wn = buttord(wp, ws, gpass, gstop)
        #print('n =',n,'wn =',wn)
        b, a = butter(n, wn, analog=True)

        return b, a
Exemplo n.º 32
0
 def test_buttord_2(self):
     # Test case for highpass filter
     self.assertTrue(
         np.all(
             IIRDesign.buttord(self.f2, self.f1, self.Rp, self.Rs) ==
             signal.buttord(
                 self.f2, self.f1, self.Rp, self.Rs, analog=False, fs=2)))
Exemplo n.º 33
0
 def HPmin(self, fil_dict):
     self._get_params(fil_dict)
     self.N, self.F_PBC = buttord(self.F_PB,self.F_SB, self.A_PB,self.A_SB)
     if not self._test_N():
         return -1
     self._save(fil_dict, sig.bessel(self.N, self.F_PBC,
                         btype='highpass', analog=False, output=self.FRMT))
Exemplo n.º 34
0
 def HPmin(self, fil_dict):
     self._get_params(fil_dict)
     self.N, self.F_PBC = buttord(self.F_PB,self.F_SB, self.A_PB,self.A_SB)
     if not self._test_N():
         return -1
     self._save(fil_dict, sig.bessel(self.N, self.F_PBC,
                         btype='highpass', analog=False, output=self.FRMT))
Exemplo n.º 35
0
Arquivo: Linx.py Projeto: 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)
Exemplo n.º 36
0
    def signal(self, fs, atten, caldb, calv):
        npts = self._duration*fs
        # start with full spectrum white noise and band-pass to get desired 
        # frequency range
        signal = self._noise[:npts]
        
        # band frequency cutoffs
        delta = 10**(3./(10.*(2*self._width)))
        low_freq = self._center_frequency / delta
        high_freq = self._center_frequency * delta
        # scipy butter function wants frequencies normalized between 0. and 1.
        nyquist = fs/2.
        low_normed = low_freq / nyquist
        high_normed = high_freq / nyquist

        order, wn = buttord([low_normed, high_normed], [low_normed-0.05, high_normed+0.05], 1, 40)

        # print 'CUTOFFS', low_freq, high_freq
        # print 'ORDER WN', order, wn, low_normed, high_normed

        b, a = butter(order, wn, btype='band')
        signal = lfilter(b, a, signal)

        if self._risefall > 0:
            rf_npts = int(self._risefall * fs) / 2
            wnd = hann(rf_npts*2) # cosine taper
            signal[:rf_npts] = signal[:rf_npts] * wnd[:rf_npts]
            signal[-rf_npts:] = signal[-rf_npts:] * wnd[rf_npts:]

        return signal
Exemplo n.º 37
0
def remove_tides(cube, T=T_M2):
    time_coord = cube.coord('time')
    time_units = time_coord.units
    target_units = cf_units.Unit(
        'seconds since 1970-01-01 00:00:00-00',
        calendar='gregorian'
    )
    time = time_units.convert(time_coord.points, target_units)
    dt = numpy.diff(time)
    # assert (dt.max() - dt.min()) < 1e-3, 'Uneven dt is not supported'
    dt = dt.min()
    # filter design, low-pass butterworth
    T0 = (2 * dt)  # period of Nyquist frequency
    Tpass = 8 * T  # period of pass frequency
    Gpass = 3.0       # max dB loss in pass band
    Tstop = 1 * T  # period of stop frequency
    Gstop = 30.0     # min dB atennuation in stop band
    o, Wn = signal.buttord(T0 / Tpass, T0 / Tstop, Gpass, Gstop)
    if o < 0:
        raise Exception(
            'Cannot create tidal filter. Data sampling frequency may be too low, dt=' +
            str(dt))
    sos = signal.butter(o, Wn, output='sos')
    data_filtered = signal.sosfiltfilt(sos, cube.data)
    new_cube = cube.copy()
    new_cube.data = data_filtered
    return new_cube
Exemplo n.º 38
0
def psd(y):
    # Number of samplepoints
    N = 128
    # sample spacing
    T = 1.0 / 128.0
    # From 0 to N, N*T, 2 points.
    #x = np.linspace(0.0, 1.0, N)
    #y = 1*np.sin(10.0 * 2.0*np.pi*x) + 9*np.sin(20.0 * 2.0*np.pi*x)


    fs = 128.0
    fso2 = fs/2
    Nd,wn = buttord(wp=[9/fso2,11/fso2], ws=[8/fso2,12/fso2],
       gpass=3.0, gstop=40.0)

    b,a = butter(Nd,wn,'band')
    y = filtfilt(b,a,y)


    yf = fft(y)
    #xf = np.linspace(0.0, 1.0/(2.0*T), N/2)
    #import matplotlib.pyplot as plt
    #plt.plot(xf, 2.0/N * np.abs(yf[0:N/2]))
    #plt.axis((0,60,0,1))
    #plt.grid()
    #plt.show()

    return np.sum(np.abs(yf[0:N/2]))
def lpf(m):
    cutoff = 9000
    norm_pass = cutoff/(m.fs/2)
    (N, Wn) = signal.buttord(wp=norm_pass, ws=1.5*norm_pass, gpass=2, gstop=50, analog=0)
    (b, a) = signal.butter(N, Wn, btype='lowpass', analog=0, output='ba')
    m.msg = signal.lfilter(b, a, m.msg)
    m.msg *= 1.0/np.abs(m.msg).max()
    return m
Exemplo n.º 40
0
 def BSmin(self, fil_dict):
     self._get_params(fil_dict)
     self.N, self.F_PBC = buttord([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.butter(self.N, self.F_PBC, btype='bandstop',
                                    analog=self.analog, output=self.FRMT))
Exemplo n.º 41
0
    def set_lowPass_filter(self, wp=20., ws=40., gpass=1., gstop=10.):
        Nq = self.fs / 2.
        wp, ws = float(wp) / Nq, float(ws) / Nq
        gpass, gstop = float(gpass), float(gstop)
        N_filtr, Wn_filtr = buttord(wp, ws, gpass, gstop)
        self.b_L, self.a_L = butter(N_filtr, Wn_filtr, btype='low')

        self.N_L, self.Wn_L = N_filtr, Wn_filtr
 def setOrderAndCritFreq(self, wp, ws, maxBand, minBand):
     self.__orderFiltr, self.__criticalFrequency = signal.buttord(
         wp=wp,
         ws=ws,
         gpass=minBand,
         gstop=maxBand,
         analog=False,
         fs=self.__samplingFrequency)
Exemplo n.º 43
0
    def set_lowPass_filter(self, wp=20., ws=40., gpass=1., gstop=10.):
        Nq = self.fs/2.
        wp, ws = float(wp)/Nq, float(ws)/Nq
        gpass, gstop = float(gpass), float(gstop)
        N_filtr, Wn_filtr = buttord(wp, ws, gpass, gstop)
        self.b_L, self.a_L = butter(N_filtr, Wn_filtr, btype='low')

        self.N_L, self.Wn_L = N_filtr, Wn_filtr
Exemplo n.º 44
0
Arquivo: Linx.py Projeto: 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)
Exemplo n.º 45
0
def smooth(time, vals, dt=None, gapFactor=20, T=T_M2):
    from scipy import signal
    if dt is None:
        dt = np.diff(time).mean()
    ta = timeArray.timeArray(time, 'epoch')
    # try to calculate exact dt by omitting large gaps
    gaps, ranges, t = ta.detectGaps(dt=dt, gapFactor=gapFactor)
    diff = []
    for i in range(ranges.shape[0]):
        twin = time[ranges[i, 0]:ranges[i, 1]]
        diff.append(np.diff(twin))
    diff = np.concatenate(tuple(diff), axis=0)
    dt = diff.mean()
    # filter design, low-pass butterworth
    T0 = (2 * dt)  # period of Nyquist frequency
    Tpass = 8 * T  # period of pass frequency
    Gpass = 3.0       # max dB loss in pass band
    Tstop = 1 * T  # period of stop frequency
    Gstop = 30.0     # min dB atennuation in stop band
    o, Wn = signal.buttord(T0 / Tpass, T0 / Tstop, Gpass, Gstop)
    if o < 0:
        raise Exception(
            'Cannot create tidal filter. Data sampling frequency may be too low, dt=' +
            str(dt))
    b, a = signal.butter(o, Wn, 'low')
    newvals = []
    newtime = []
    # filter each contiquous data range separately
    for i in range(ranges.shape[0]):
        twin = time[ranges[i, 0]:ranges[i, 1]]
        vwin = vals[ranges[i, 0]:ranges[i, 1]]
        if len(vwin) > 3 * len(a):
            try:
                # default forward-backward filter
                # filtered = signal.filtfilt(b, a, vwin, padtype='constant')
                # forward-backward filter with custom boundary conditions
                # pad with mean of 1/2 pass window lenght
                N_init = int(np.ceil(Tpass / dt / 2 / 4))
                # forward filter
                x_init = vwin[:N_init]
                y_init = x_init.mean() * np.ones_like(x_init)
                z_init = signal.lfiltic(b, a, y_init, x_init)
                filtered, _ = signal.lfilter(b, a, vwin, zi=z_init)
                # backward filter
                x_init = vwin[-N_init:][::-1]
                y_init = x_init.mean() * np.ones_like(x_init)
                z_init = signal.lfiltic(b, a, y_init, x_init)
                filtered, _ = signal.lfilter(b, a, filtered[::-1], zi=z_init)
                filtered = filtered[::-1]
                newvals.append(filtered)
                newtime.append(twin)
            except Exception as e:
                print a.shape, vwin.shape
                raise e
    newvals = np.concatenate(tuple(newvals), axis=0)
    newtime = np.concatenate(tuple(newtime), axis=0)
    return newtime, newvals
Exemplo n.º 46
0
def butter_bandpass(filt_freq,fs):
    nyq = 0.5 * fs

    wp=[filt_freq[1]/nyq, filt_freq[2]/nyq, ]
    ws=[filt_freq[0]/nyq, filt_freq[3]/nyq]
    N, wn = buttord(wp, ws, 3, 16)
    print N
    b, a = butter(N, wn, btype='band')
    return b, a
Exemplo n.º 47
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
Exemplo n.º 48
0
def highpass(s,stopBand,fs):
    ''' 
    highpass signal for noise reduction
    finch songdata should be in range 350Hz to 11kHz 
    '''
    N,wn = ss.buttord(wp=2*np.pi*(stopBand+100.)/fs,ws=2*np.pi*stopBand*1.0/fs,gpass=2.0, gstop=30.0,analog=0)
    b, a = ss.butter(N, wn,btype='high',analog=0)  
    filteredsong = ss.lfilter(b, a, s)
    filteredsong = np.round(filteredsong).astype('int16') # scipy wav needs 16 bit depth
    return filteredsong
Exemplo n.º 49
0
def ex4_1():
    wp = 0.2*np.pi
    ws = 0.3*np.pi
    fs = 4000.0
    T = 1/fs
    Wp = wp/T
    Ws = ws/T
    n, x = signal.buttord(Wp, Ws, 2, 40, analog=True)
    b, a = signal.butter(n, x, analog=True)
    z, p, k = signal.tf2zpk(b, a)
    print z, p, k
Exemplo n.º 50
0
 def calculate_bandpass(self):
     # Bandpass filter
     #self.width = 10000.0/self.nyquist_rate
     #self.cutoff = 2000.0/self.nyquist_rate
     self.ripple_db = 60.0
     self.high_pass = (self.tx_freq+1000.0)/self.nyquist_rate
     self.low_pass = (self.tx_freq-1000.0)/self.nyquist_rate
     self.high_cutoff = (self.tx_freq+1500.0)/self.nyquist_rate
     self.low_cutoff = (self.tx_freq-1500.0)/self.nyquist_rate
     ord, wn = signal.buttord([self.low_pass, self.high_pass],[self.low_cutoff,self.high_cutoff],1.0,30.0)
     self.b,self.a = signal.butter(ord,wn, btype="band")
Exemplo n.º 51
0
    def bandpass(self, flow, fhigh, gpass=2, gstop=30, stops=(None, None)):
        """Filter this `TimeSeries` by applying low- and high-pass filters.

        Parameters
        ----------
        flow : `float`
            band-pass lower corner frequency
        fhigh : `float`
            band-pass upper corner frequency
        gpass : `float`
            the maximum loss in the pass band (dB).
        gstop : `float`
            the minimum attenuation in the stop band (dB).
        stops: 2-`tuple` of `float`
            stop-band edge frequencies, defaults to `[flow/2., fhigh*1.5]`

        Returns
        -------
        bpseries : `TimeSeries`
            a band-passed version of the input `TimeSeries`

        See Also
        --------
        scipy.signal.buttord
        scipy.signal.butter
            for details on how the filter is designed
        TimeSeries.filter
            for details on how the filter is applied

        .. note::

           When using `scipy < 0.16.0` some higher-order filters may be
           unstable. With `scipy >= 0.16.0` higher-order filters are
           decomposed into second-order-sections, and so are much more stable.
        """
        nyq = self.sample_rate.value / 2.
        if stops is None:
            stops = [None, None]
        stops = list(stops)
        if stops[0] is None:
            stops[0] = flow * 0.5
        if stops[1] is None:
            stops[1] = fhigh * 1.5
        # make sure all are in Hertz
        low = units.Quantity(flow, 'Hz').value / nyq
        high = units.Quantity(fhigh, 'Hz').value / nyq
        stops = [units.Quantity(s, 'Hz').value / nyq for s in stops]
        # design filter
        order, wn = signal.buttord(wp=[low, high], ws=stops, gpass=gpass,
                                   gstop=gstop, analog=False)
        zpk = signal.butter(order, wn, btype='band',
                            analog=False, output='zpk')
        # apply filter
        return self.filter(*zpk)
Exemplo n.º 52
0
    def __call__(self, t, data):
        dt = t[1]-t[0]
        Fs = 1.0/dt
        Nyq = Fs/2.0

        Wp = self.cf/Nyq
        Ws = self.sf/Nyq
        [n,Wn] = buttord(Wp,Ws,self.rp, self.rs)

        [b,a] = butter(n,Wn)
        data = lfilter(b,a,data)
        return data
Exemplo n.º 53
0
    def lowPass(samp_rate, cutoff, inputArray):

        # design filter
        norm_pass = cutoff/(samp_rate/2)
        norm_stop = 1.5*norm_pass
        (N, Wn) = signal.buttord(wp=norm_pass, ws=norm_stop, gpass=2, gstop=30, analog=0)
        (b, a) = signal.butter(N, Wn, btype='low', analog=0, output='ba')

        # filtered output
        #zi = signal.lfiltic(b, a, x[0:5], x[0:5])
        #(y, zi) = signal.lfilter(b, a, x, zi=zi)
        return signal.lfilter(b, a, inputArray, axis=0)
Exemplo n.º 54
0
def _NOTCH_butter_bandstop(interval, sampling_rate, cutoff, order=5):

    nyq = sampling_rate * 0.5

    stopfreq = float(cutoff) + 300.0
    cornerfreq = float(cutoff) - 300.0
    Ws = stopfreq / nyq
    Wp = cornerfreq / nyq
    N, Wn = buttord(Wp, Ws, 8, 20)  # (?)
    print N, Wn, Wp, Ws, stopfreq, cornerfreq

    b, a = butter(N, [Wp, Ws], btype="bandstop")  # should 'high' be here for bandpass?
    sf = lfilter(b, a, interval)
    return sf, b, a
def main():
    # play with these values
    cutoff = 9000
    norm_pass = cutoff/(44100/2)
    (N, Wn) = signal.buttord(wp=norm_pass, ws=1.5*norm_pass, gpass=2, gstop=50, analog=0)
    (b, a) = signal.butter(N, Wn, btype='lowpass', analog=0, output='ba')

    w, h = signal.freqz(b, a)
    plot.figure()
    plot.title("Digital Filter Frequency Response")
    plot.plot(w/2/np.pi*44100, 20 * np.log10(abs(h)))
    plot.xlabel("Frequency (Hz)")
    plot.ylabel("Gain (dB)")
    plot.show()
Exemplo n.º 56
0
def _HP_Butterworth(interval, sampling_rate, cutoff):

    nyq = sampling_rate * 0.5
    stopfreq = float(cutoff)
    cornerfreq = 0.5 * stopfreq
    Ws = cornerfreq / nyq
    Wp = stopfreq / nyq
    # N, Wn = buttord(Wp, Ws, 3, 20)   # (?)
    # N, Wn = buttord(Wp, Ws, 6, 20)   # (?)
    N, Wn = buttord(Wp, Ws, 10, 27)  # (?)
    print "The oder of HPF is: %f" % N
    b, a = butter(N, Wn, btype="high")  # should 'high' be here for bandpass?
    # b, a = butter(9, float(20.0/nyq) , btype='high')   # should 'high' be here for bandpass?
    sf = lfilter(b, a, interval)
    return sf, b, a
Exemplo n.º 57
0
    def highpass(self, frequency, gpass=2, gstop=30, stop=None):
        """Filter this `TimeSeries` with a Butterworth high-pass filter.

        Parameters
        ----------
        frequency : `float`
            minimum frequency for high-pass
        gpass : `float`
            the maximum loss in the passband (dB).
        gstop : `float`
            the minimum attenuation in the stopband (dB).
        stop : `float`
            stop-band edge frequency, defaults to `frequency/2`

        Returns
        -------
        hpseries : `TimeSeries`
            a high-passed version of the input `TimeSeries`

        See Also
        --------
        scipy.signal.buttord
        scipy.signal.butter
            for details on how the filter is designed
        TimeSeries.filter
            for details on how the filter is applied

        .. note::

           When using `scipy < 0.16.0` some higher-order filters may be
           unstable. With `scipy >= 0.16.0` higher-order filters are
           decomposed into second-order-sections, and so are much more stable.
        """

        nyq = self.sample_rate.value / 2.
        if stop is None:
            stop = .5 * frequency
        # convert to float in Hertz
        cutoff = units.Quantity(frequency, 'Hz').value / nyq
        stop = units.Quantity(stop, 'Hz').value / nyq
        # design filter
        order, wn = signal.buttord(wp=cutoff, ws=stop, gpass=gpass,
                                   gstop=gstop, analog=False)
        zpk = signal.butter(order, wn, btype='high',
                            analog=False, output='zpk')
        # apply filter
        return self.filter(*zpk)
Exemplo n.º 58
0
    def _compute_parameters(self):
        normalized_pb, normalized_sb = self.normalized_pb_sb()
        self.already_normalized_Wn = True
        if self.target == 'passband':
            self.N, self.Wn = signal.buttord(normalized_pb, normalized_sb,
                                             self.filter_parameters['passband_attenuation'],
                                             self.filter_parameters['stopband_attenuation'],
                                             analog=False)
        elif self.target == 'stopband': # Match stopband (like MATLAB)
            self.N, self.Wn = custom.custom_buttord(normalized_pb, normalized_sb,
                                             self.filter_parameters['passband_attenuation'],
                                             self.filter_parameters['stopband_attenuation'],
                                             analog=False)

        else:
            raise ValueError("Butterworth filters must match or the passband\
                              or the stopband.")
Exemplo n.º 59
0
Arquivo: util.py Projeto: wyolum/mmM
def bandpass(data, dt, lo, hi):
    '''
    Filter the data so that energy outside of pass band is attenuated
    data -- real data sampled at dt
    dt -- time between data samples
    lo -- low freq cuttoff
    hi -- hi freq cuttoff
    '''
    BW = 1/(2 * dt)
    wp = (lo / BW, hi/BW)
    ws = (lo * .4/BW, hi * 1.4 / BW)
    gpass = 1
    gstop = 20
    N, Wn = signal.buttord(wp, ws, gpass, gstop)
    # b, a = signal.butter(N, Wn, btype='bandpass')
    b, a = signal.butter(5, Wn, btype='bandpass')
    return signal.lfilter(b, a, data)
Exemplo n.º 60
0
def hilbert_transform(data,bandpass=[25,40],Fs=1000):
	'''data input as time x samples'''
	#bandpass=[25,40]
	#Fs=1000
	upper = bandpass[1]/float(Fs/2)
	lower = bandpass[0]/float(Fs/2)
	order,wn = scisig.buttord([lower, upper],[np.max([0, lower-0.01]), np.min([upper+0.01, 1])],3,20)
	b, a = scisig.butter(np.min([order,9]), wn, btype = 'bandpass')
	
	amp = np.zeros((data.shape[0],data.shape[1]))
	phase = np.zeros((data.shape[0],data.shape[1]))
	for i, d in enumerate(data.T):
		y = scisig.filtfilt(b,a,d)
		z = scisig.hilbert(y)
		amp[:,i] = abs(z)
		phase[:,i] = phz(z)
	return amp, phase