Exemple #1
0
def bandPass(x, dt, fl, fh, fs, ap, astop, nzero):
    '''
    band pass fileter, utilize scipy.signal
    x: raw data
    dt: time interval of raw data, sec
    fl: low frequency, Hz
    fh: high frequency, Hz
    fs: stop frequency, Hz
    ap: attenuation amplitude of pass frequency
    astop: attenuation amplitude of stop frequency
    nzero: number of zeros pad before raw data
    '''
    # pad zero before x
    y = np.concatenate((np.zeros((nzero, )), x))
    fn = int(1 / dt / 2)
    if (fl <= 0):
        sos = signal.iirdesign(wp=fh/fn, ws=fs/fn, gpass=ap, gstop=astop, \
                ftype='cheby2', output='sos')
    else:
        wpl = fl / fn
        wph = fh / fn
        wsl = fl * 0.9 / fn
        wsh = fs / fn
        sos = signal.iirdesign(wp=[wpl, wph], ws=[wsl, wsh], gpass=ap, gstop=astop, \
            ftype='cheby2', output='sos')
        # end if
    z = signal.sosfilt(sos, y)
    w = z[nzero:]
    return w
Exemple #2
0
def mgr_filter(mgr, wp, ws, gpass, gstop, analog=0, ftype='ellip', output='ba', unit='hz', use_filtfilt=False, meancorr=1.0):
    if unit == 'radians':
        b,a = signal.iirdesign(wp, ws, gpass, gstop, analog, ftype, output)
    elif unit == 'hz':
        nyquist = float(mgr.get_param('sampling_frequency'))/2.0
        try:
            wp = wp/nyquist
            ws = ws/nyquist
        except TypeError:
            wp = [i/nyquist for i in wp]
            ws = [i/nyquist for i in ws]

        b,a = signal.iirdesign(wp, ws, gpass, gstop, analog, ftype, output)
    if use_filtfilt:    
        from scipy.signal import filtfilt
        #samples_source = read_data_source.MemoryDataSource(mgr.get_samples(), False)
        for i in range(int(mgr.get_param('number_of_channels'))):
            print("FILT FILT CHANNEL "+str(i))
            mgr.get_samples()[i,:] = signal.filtfilt(b, a, mgr.get_samples()[i]-np.mean(mgr.get_samples()[i])*meancorr)
        samples_source = read_data_source.MemoryDataSource(mgr.get_samples(), False)
    else:
        print("FILTER CHANNELs")
        filtered = signal.lfilter(b, a, mgr.get_samples())
        print("FILTER CHANNELs finished")
        samples_source = read_data_source.MemoryDataSource(filtered, True)

    info_source = copy.deepcopy(mgr.info_source)
    tags_source = copy.deepcopy(mgr.tags_source)
    new_mgr = read_manager.ReadManager(info_source, samples_source, tags_source)
    return new_mgr
Exemple #3
0
def IIR_bpf(f_stop1,
            f_pass1,
            f_pass2,
            f_stop2,
            Ripple_pass,
            Atten_stop,
            fs=1.00,
            ftype='butter',
            status=True):
    """
    Design an IIR bandpass filter using scipy.signal.iirdesign. 
    The filter order is determined based on 
    f_pass Hz, f_stop Hz, and the desired stopband attenuation
    d_stop in dB, all relative to a sampling rate of fs Hz.

    Parameters
    ----------
    f_stop1 : ndarray of the numerator coefficients
    f_pass : ndarray of the denominator coefficients
    Ripple_pass : 
    Atten_stop : 
    fs : sampling rate in Hz
    ftype : Analog prototype from 'butter' 'cheby1', 'cheby2',
            'ellip', and 'bessel'

    Returns
    -------
    b : ndarray of the numerator coefficients
    a : ndarray of the denominator coefficients
    sos : 2D ndarray of second-order section coefficients

    Examples
    --------
    >>> fs = 48000
    >>> f_pass = 8000
    >>> f_stop = 5000
    >>> b_but,a_but,sos_but = IIR_hpf(f_stop,f_pass,0.5,60,fs,'butter')
    >>> b_cheb1,a_cheb1,sos_cheb1 = IIR_hpf(f_stop,f_pass,0.5,60,fs,'cheby1')
    >>> b_cheb2,a_cheb2,sos_cheb2 = IIR_hpf(f_stop,f_pass,0.5,60,fs,'cheby2')
    >>> b_elli,a_elli,sos_elli = IIR_hpf(f_stop,f_pass,0.5,60,fs,'ellip')

    Mark Wickert October 2016
    """

    b, a = signal.iirdesign([2 * float(f_pass1) / fs, 2 * float(f_pass2) / fs],
                            [2 * float(f_stop1) / fs, 2 * float(f_stop2) / fs],
                            Ripple_pass,
                            Atten_stop,
                            ftype=ftype,
                            output='ba')
    sos = signal.iirdesign([2 * float(f_pass1) / fs, 2 * float(f_pass2) / fs],
                           [2 * float(f_stop1) / fs, 2 * float(f_stop2) / fs],
                           Ripple_pass,
                           Atten_stop,
                           ftype=ftype,
                           output='sos')
    tag = 'IIR ' + ftype + ' order'
    if status:
        log.info('%s = %d.' % (tag, len(a) - 1))
    return b, a, sos
Exemple #4
0
def IIR_bsf(f_pass1,
            f_stop1,
            f_stop2,
            f_pass2,
            Ripple_pass,
            Atten_stop,
            fs=1.00,
            ftype='butter'):
    """
    Design an IIR bandstop filter using scipy.signal.iirdesign. 
    The filter order is determined based on 
    f_pass Hz, f_stop Hz, and the desired stopband attenuation
    d_stop in dB, all relative to a sampling rate of fs Hz.

    Mark Wickert October 2016
    """

    b, a = signal.iirdesign([2 * float(f_pass1) / fs, 2 * float(f_pass2) / fs],
                            [2 * float(f_stop1) / fs, 2 * float(f_stop2) / fs],
                            Ripple_pass,
                            Atten_stop,
                            ftype=ftype,
                            output='ba')
    sos = signal.iirdesign([2 * float(f_pass1) / fs, 2 * float(f_pass2) / fs],
                           [2 * float(f_stop1) / fs, 2 * float(f_stop2) / fs],
                           Ripple_pass,
                           Atten_stop,
                           ftype=ftype,
                           output='sos')
    tag = 'IIR ' + ftype + ' order'
    print('%s = %d.' % (tag, len(a) - 1))
    return b, a, sos
def desingFilterBands(fBands, fs):
    nyq = fs / 2.0
    trans = 2.0
    coeFil = []
    for freq in fBands:
        # Filter frequency bands
        passCut = freq / nyq
        stopCut = [(freq[0] - trans) / nyq, (freq[1] + trans) / nyq]
        coeFil.append(
            sg.iirdesign(passCut,
                         stopCut,
                         gpass=0.0025,
                         gstop=30.0,
                         analog=False,
                         ftype='cheby2',
                         output='sos'))
    #coeFil = np.dstack(coeFil)
    # Filter envelops
    coeFilEnv = sg.iirdesign(0.5 / nyq, (0.5 + trans) / nyq,
                             gpass=0.0025,
                             gstop=30.0,
                             analog=False,
                             ftype='cheby2',
                             output='sos')
    return coeFil, coeFilEnv
Exemple #6
0
def IIR_lpf(f_pass, f_stop, Ripple_pass, Atten_stop, fs=1.00, ftype='butter'):
    """
    Design an IIR lowpass filter using scipy.signal.iirdesign. 
    The filter order is determined based on 
    f_pass Hz, f_stop Hz, and the desired stopband attenuation
    d_stop in dB, all relative to a sampling rate of fs Hz.

    Parameters
    ----------
    f_pass : Passband critical frequency in Hz
    f_stop : Stopband critical frequency in Hz
    Ripple_pass : Filter gain in dB at f_pass
    Atten_stop : Filter attenuation in dB at f_stop
    fs : Sampling rate in Hz
    ftype : Analog prototype from 'butter' 'cheby1', 'cheby2',
            'ellip', and 'bessel'

    Returns
    -------
    b : ndarray of the numerator coefficients
    a : ndarray of the denominator coefficients
    sos : 2D ndarray of second-order section coefficients

    Notes
    -----
    Additionally a text string telling the user the filter order is
    written to the console, e.g., IIR cheby1 order = 8.

    Examples
    --------
    >>> fs = 48000
    >>> f_pass = 5000
    >>> f_stop = 8000
    >>> b_but,a_but,sos_but = IIR_lpf(f_pass,f_stop,0.5,60,fs,'butter')
    >>> b_cheb1,a_cheb1,sos_cheb1 = IIR_lpf(f_pass,f_stop,0.5,60,fs,'cheby1')
    >>> b_cheb2,a_cheb2,sos_cheb2 = IIR_lpf(f_pass,f_stop,0.5,60,fs,'cheby2')
    >>> b_elli,a_elli,sos_elli = IIR_lpf(f_pass,f_stop,0.5,60,fs,'ellip')


    Mark Wickert October 2016
    """

    b, a = signal.iirdesign(2 * float(f_pass) / fs,
                            2 * float(f_stop) / fs,
                            Ripple_pass,
                            Atten_stop,
                            ftype=ftype,
                            output='ba')
    sos = signal.iirdesign(2 * float(f_pass) / fs,
                           2 * float(f_stop) / fs,
                           Ripple_pass,
                           Atten_stop,
                           ftype=ftype,
                           output='sos')
    tag = 'IIR ' + ftype + ' order'
    print('%s = %d.' % (tag, len(a) - 1))
    return b, a, sos
Exemple #7
0
def get_a_b(bandtype, Fs, Wp, Ws, order=3, Rp=3, As=60, analog_val=False, filttype='butter', automatic=0):

    stop_amp = 1.5
    stop_amp2 = 1.4

    if not analog_val:  # need to convert the Ws and Wp to have the units of pi radians/sample
        # this is for digital filters
        if bandtype in ['low', 'high']:
            Wp = Wp / (Fs / 2)  # converting to fraction of nyquist frequency

            Ws = Wp * stop_amp

        elif bandtype == 'band':
            Wp = Wp / (Fs / 2)  # converting to fraction of nyquist frequency
            Wp2 = Wp / stop_amp2

            Ws = Ws / (Fs / 2)  # converting to fraction of nyquist frequency
            Ws2 = Ws * stop_amp2

    else:  # need to convert the Ws and Wp to have the units of radians/sec
        # this is for analog filters
        if bandtype in ['low', 'high']:
            Wp = 2 * np.pi * Wp

            Ws = Wp * stop_amp

        elif bandtype == 'band':
            Wp = 2 * np.pi * Wp
            Wp2 = Wp / stop_amp2

            Ws = 2 * np.pi * Ws
            Ws2 = Ws * stop_amp2

    if automatic == 1:
        if bandtype in ['low', 'high']:
            b, a = signal.iirdesign(wp=Wp, ws=Ws, gpass=Rp, gstop=As, analog=analog_val, ftype=filttype)
        elif bandtype == 'band':
            b, a = signal.iirdesign(wp=[Wp, Ws], ws=[Wp2, Ws2], gpass=Rp, gstop=As, analog=analog_val, ftype=filttype)
    else:
        if bandtype in ['low', 'high']:
            if filttype == 'cheby1' or 'cheby2' or 'ellip':
                b, a = signal.iirfilter(order, Wp, rp=Rp, rs=As, btype=bandtype, analog=analog_val, ftype=filttype)
            else:
                b, a = signal.iirfilter(order, Wp, btype=bandtype, analog=analog_val, ftype=filttype)
        elif bandtype == 'band':
            if filttype == 'cheby1' or 'cheby2' or 'ellip':
                b, a = signal.iirfilter(order, [Wp, Ws], rp=Rp, rs=As, btype=bandtype, analog=analog_val,
                                        ftype=filttype)
            else:
                b, a = signal.iirfilter(order, [Wp, Ws], btype=bandtype, analog=analog_val, ftype=filttype)

    return b, a
Exemple #8
0
 def _desingFilterBands(self):
     nyq   = self.fs / 2.0
     trans = 2.0
     self.coeFil = []
     for freq in self.fBands:
         # Filter frequency bands
         passCut = freq / nyq
         stopCut = [(freq[0] - trans) / nyq, (freq[1] + trans) / nyq]
         self.coeFil.append(sg.iirdesign(passCut, stopCut, gpass=0.0025, gstop=30.0,
                                         analog=False, ftype='cheby2', output='sos'))
     # Filter envelops
     self.coeFilEnv = sg.iirdesign(0.5 / nyq, (0.5+trans)/nyq , gpass=0.0025, gstop=30.0,
                                         analog=False, ftype='cheby2', output='sos')
Exemple #9
0
    def updateFilter(self, freq):
        #recalculate filter coeffs based on new frequency
        freq *= 2**self.octave
        w = 2*np.pi*freq/SAMPLE_RATE

        if w<10*self.bdw:
            b, a = signal.iirdesign(w, w+10*self.bdw, 3, 80, False, 'cheby1')

        elif w>1-10*self.bdw:
            b, a = signal.iirdesign(w, w-10*self.bdw, 3, 80, False, 'cheby1')

        else:
            b, a = signal.iirdesign([w-10*self.bdw,w+10*self.bdw], [w-20**self.bdw,w+20**self.bdw], 3, 80, False, 'cheby1')

        self.filter.updatecoef(a,b)
Exemple #10
0
    def __init__(self, wp, ws, gpass, gstop):

        b,a = iirdesign(wp, ws, gpass, gstop)
        print b,a
        input_weights = b[::-1]
        feedback_weights = a[::-1]
        LinearFilter.__init__(self, input_weights=input_weights, feedback_weights=feedback_weights)
Exemple #11
0
    def __init__(self,
                 fs=1.0,
                 passfreqs=[1.0, 10.0],
                 stopfreqs=[],
                 gstop=60,
                 gpass=1,
                 order=0,
                 ftype='ellip',
                 window='hamming'):
        #b,a = signal.iirdesign(wp = [0.05, 0.3], ws= [0.02, 0.35], gstop= 60, gpass=1,
        #                   ftype='ellip')
        # wp=[0.1,0.4],ws=[0.05,0.45], gstop=60, gpass=1, ftype='bessel'):
        self.ftype = ftype  # options are 'ellip', 'butter', 'cheby1', 'cheby2', 'bessel'
        nyquist = fs / 2.0
        wp = [ff / nyquist for ff in passfreqs]
        if not stopfreqs:  # then give some naive defaults
            ws = [wp[0] / 2.0, (wp[1] + nyquist) / 2.0]
        else:
            ws = [ff / nyquist for ff in stopfreqs]

        self.ba = signal.iirdesign(wp=wp,
                                   ws=ws,
                                   gstop=gstop,
                                   gpass=gpass,
                                   ftype=ftype)
Exemple #12
0
    def __init__(self, band_start, band_stop):
        nyquist_frequency = float(SAMPLES_PER_SECOND) / 2.0

        band_start /= nyquist_frequency
        band_stop /= nyquist_frequency

        assert (band_start >= 0 and band_start <= 1)
        assert (band_stop >= 0 and band_stop <= 1)
        assert (band_stop >= band_start)

        passband_edges = []
        stopband_edges = []

        if band_start >= 0.05:  # if not, make LPF only
            passband_edges.append(band_start * 1.025)
            stopband_edges.append(band_start * 0.975)

        if band_stop <= 0.95:  # if not, make HPF only
            passband_edges.append(band_stop * 0.975)
            stopband_edges.append(band_stop * 1.025)

        (self.feedforward_taps, self.feedback_taps) = iirdesign(
            passband_edges,
            stopband_edges,
            0.1,  # max attenuation (dB) in passband
            30)  # min attenuation (dB) in stopband

        self.filter_state = lfiltic(self.feedforward_taps, self.feedback_taps,
                                    [])
Exemple #13
0
def iir_bp(fstops, fs, order=4):
    """
    the opposite of a notch filter: return coefficients to add a spectral line
    """
    nyq = 0.5 * fs

    # Zeros zd, poles pd, and gain kd for the digital filter
    zd = np.array([])
    pd = np.array([])

    # Lines
    for fstopData in fstops:
        fstop = fstopData[0]
        df = fstopData[1]
        df2 = fstopData[2]
        low = (fstop - df) / nyq
        high = (fstop + df) / nyq
        low2 = (fstop - df2) / nyq
        high2 = (fstop + df2) / nyq
        z, p, k = sig.iirdesign([low2, high2], [low, high],
                                gpass=1,
                                gstop=6,
                                ftype='ellip',
                                output='zpk')
        zd = np.append(zd, z)
        pd = np.append(pd, p)

    # Return the numerator and denominator of the digital filter
    b, a = sig.zpk2tf(zd, pd, k)
    return b, a
Exemple #14
0
    def iir(self):
        """
        Filter the time-series using an IIR filter. Filtering is done back and
        forth (using scipy.signal.filtfilt) to achieve zero phase delay

        """

        #Passband and stop-band are expressed as fraction of the Nyquist
        #frequency:
        if self.ub is not None:
            ub_frac = self.ub / (self.sampling_rate / 2.)
        else:
            ub_frac = 1.0

        lb_frac = self.lb / (self.sampling_rate / 2.)

        wp = [lb_frac, ub_frac]

        #Make sure to not exceed the interval 0-1:
        ws = [np.max([lb_frac - 0.1, 0]),
              np.min([ub_frac + 0.1, 1.0])]

        b, a = signal.iirdesign(wp, ws, self._gpass, self._gstop,
                                ftype=self._ftype)

        return self.filtfilt(b, a)
Exemple #15
0
def _design_iir(wp, ws, sample_rate, gpass, gstop,
                analog=False, ftype='cheby1', output='zpk'):
    # pylint: disable=invalid-name
    nyq = sample_rate / 2.
    wp = numpy.atleast_1d(wp)
    ws = numpy.atleast_1d(ws)
    if analog:  # convert Hz to rad/s
        wp *= TWO_PI
        ws *= TWO_PI
    else:  # convert Hz to half-cycles / sample
        wp /= nyq
        ws /= nyq
    z, p, k = signal.iirdesign(wp, ws, gpass, gstop, analog=analog,
                               ftype=ftype, output='zpk')
    if analog:  # convert back to Hz
        z /= -TWO_PI
        p /= -TWO_PI
        k *= TWO_PI ** z.size / -TWO_PI ** p.size
    if output == 'zpk':
        return z, p, k
    elif output == 'ba':
        return signal.zpk2tf(z, p, k)
    elif output == 'sos':
        return signal.zpk2sos(z, p, k)
    else:
        raise ValueError("'%s' is not a valid output form." % output)
def lab6_ex4():
    # set parameters of system    
    fs = 2000 #sampling frequency (Hz)
    fn = fs/2.0 #nyqvist frequency
    wp = array([200/fn,400/fn]) #band-pass in normalized corner frequencies
    ws = array([1/fn,100/fn,500/fn,5000/fn]) #band-stop in normalized corner frequencies
    gstop = 40 #minimum attenuation in stopband
    gpass = 1 #maximum loss in passband
    
    # create remez filter, frequency response, and plot
    b,a = iirdesign(wp,ws,gpass,gstop,analog=0)
    w,h = freqz(b,a)
    plot(w/pi, 20*log10(abs(h)),'b-')
    title('IIR of given frequency response')
    xlabel('normalized frequency (1 = fn)')
    ylabel('magnitude (dB scale)')
    grid()
    show()

    print("\nBoth designs achieve the desired response at the desired attenuation, but the IIR design's response attenuates and gains more quickly than the 46th-order remez FIR design.")

    z,p,k = tf2zpk(b,a)
    zplane(z,p)
    title('zplane of IIR of given frequency response')
    show()

    print('\nZ-plane analysis shows that the IIR design uses an 8th degree polynomial, while the remez FIR uses a 46th order polynomial (and thus far more components) to achieve the same desired response. This is because the IIR filter is able to use both zeros and poles (i.e. feedback) to achieve the desired frequency response at the desired attenuation and loss, whereas the remez FIR must use only zeros (no feedback).')
Exemple #17
0
def SignalFilter(signal, LPF, HPF, samplefreq):
    if debugFlag:
        print "sfreq: %f LPF: %f HPF: %f" % (samplefreq, LPF, HPF)
    flpf = float(LPF)
    fhpf = float(HPF)
    sf = float(samplefreq)
    sf2 = sf / 2
    wp = [fhpf / sf2, flpf / sf2]
    ws = [0.5 * fhpf / sf2, 2 * flpf / sf2]
    if debugFlag:
        print "signalfilter: samplef: %f  wp: %f, %f  ws: %f, %f lpf: %f  hpf: %f" % (
            sf, wp[0], wp[1], ws[0], ws[1], flpf, fhpf)
    filter_b, filter_a = spSignal.iirdesign(wp,
                                            ws,
                                            gpass=1.0,
                                            gstop=60.0,
                                            ftype="ellip")
    msig = numpy.mean(signal)
    signal = signal - msig
    w = spSignal.lfilter(filter_b, filter_a,
                         signal)  # filter the incoming signal
    signal = signal + msig
    if debugFlag:
        print "sig: %f-%f w: %f-%f" % (numpy.amin(signal), numpy.amax(signal),
                                       numpy.amin(w), numpy.amax(w))
    return (w)
Exemple #18
0
def iir_bandstops(fstops, fs, order=4):
    import numpy as np
    from scipy.signal import iirdesign, zpk2tf, freqz
    nyq = 0.5 * fs
    # Zeros zd, poles pd, and gain kd for the digital filter
    zd = np.array([])
    pd = np.array([])
    kd = 1

    # Notches
    for fstopData in fstops:
        fstop = fstopData[0]
        df = fstopData[1]
        df2 = fstopData[2]
        low = (fstop - df) / nyq
        high = (fstop + df) / nyq
        low2 = (fstop - df2) / nyq
        high2 = (fstop + df2) / nyq
        z, p, k = iirdesign([low,high], [low2,high2], gpass=1, gstop=6,
                            ftype='ellip', output='zpk')
        zd = np.append(zd,z)
        pd = np.append(pd,p)

    # Set gain to one at 100 Hz...better not notch there
    bPrelim,aPrelim = zpk2tf(zd, pd, 1)
    outFreq, outg0 = freqz(bPrelim, aPrelim, 100/nyq)

    # Return the numerator and denominator of the digital filter
    b,a = zpk2tf(zd,pd,k)
    return b, a
Exemple #19
0
 def set_params(self, **kwargs):
     f = kwargs['cut_off_freq']
     normalized_pass = f / (RATE * .5)
     normalized_stop = (f + .3 * f) / (RATE * .5)
     (self.b, self.a) = signal.iirdesign(normalized_pass, normalized_stop,
                                         LowpassFilter.pass_band_loss,
                                         LowpassFilter.stop_band_loss)
def iir_bandstops(fstops, fs, order=4):
    """ellip notch filter
    fstops is a list of entries of the form [frequency (Hz), df, df2]                           
    where df is the pass width and df2 is the stop width (narrower                              
    than the pass width). Use caution if passing more than one freq at a time,                  
    because the filter response might behave in ways you don't expect.
    """
    nyq = 0.5 * fs

    # Zeros zd, poles pd, and gain kd for the digital filter
    zd = np.array([])
    pd = np.array([])
    kd = 1

    # Notches
    for fstopData in fstops:
        fstop = fstopData[0]
        df = fstopData[1]
        df2 = fstopData[2]
        low = (fstop - df) / nyq
        high = (fstop + df) / nyq
        low2 = (fstop - df2) / nyq
        high2 = (fstop + df2) / nyq
        z, p, k = iirdesign([low,high], [low2,high2], gpass=1, gstop=6,
                            ftype='ellip', output='zpk')
        zd = np.append(zd,z)
        pd = np.append(pd,p)

    # Set gain to one at 100 Hz...better not notch there                                        
    bPrelim,aPrelim = zpk2tf(zd, pd, 1)
    outFreq, outg0 = freqz(bPrelim, aPrelim, 100/nyq)

    # Return the numerator and denominator of the digital filter                                
    b,a = zpk2tf(zd,pd,k)
    return b, a
Exemple #21
0
    def __init__( self, band_start, band_stop ):
        nyquist_frequency = float(SAMPLES_PER_SECOND) / 2.0
        
        band_start /= nyquist_frequency
        band_stop /= nyquist_frequency

        assert( band_start >= 0 and band_start <= 1 )
        assert( band_stop >= 0 and band_stop <= 1 )
        assert( band_stop >= band_start )

        passband_edges = []
        stopband_edges = []

        if band_start >= 0.05: # if not, make LPF only
            passband_edges.append( band_start * 1.025 )
            stopband_edges.append( band_start * 0.975 )

        if band_stop <= 0.95: # if not, make HPF only
            passband_edges.append( band_stop * 0.975 )
            stopband_edges.append( band_stop * 1.025 )

        (self.feedforward_taps,
         self.feedback_taps) = iirdesign( passband_edges,
                                          stopband_edges,
                                          0.1,               # max attenuation (dB) in passband
                                          30 )               # min attenuation (dB) in stopband

        self.filter_state = lfiltic( self.feedforward_taps, self.feedback_taps, [] )
Exemple #22
0
    def ellip_bp(self, wp, ws, gpass=0.5, gstop=20):
        """ Elliptic Bandpath filter

        Parameters
        ----------

        wp :
        ws :
        gpass
        gstop :

        See Also
        --------

        iirdesign

        """
        (b, a) = si.iirdesign(wp,
                              ws,
                              gpass,
                              gstop,
                              analog=0,
                              ftype='ellip',
                              output='ba')
        self.b = b
        self.a = a
Exemple #23
0
    def test_filter(self):
        if not self.TEST_FILTER:
            return


        def getSin(hz, sampling, data):
            return sin(hz*2*pi*data/sampling)
        mgr = get_fake_manager(3, 1000)
        x=r_[0:1000]
        y1 = getSin(2, 128.0, x)
        y2 = getSin(15, 128.0, x)
        y3 = getSin(30, 128.0, x)
        mgr.get_samples()[0,:] = y1
        mgr.get_samples()[1,:] = y2
        mgr.get_samples()[2,:] = y3

        b,a = signal.iirdesign([9/128.0, 16/128.0], [4/128.0, 25/128.0],0.2, 70.0, ftype='cheby2')
        y = signal.lfilter(b, a, mgr.get_samples())


        e = ch.Filter([9/128.0, 16/128.0], [4/128.0, 25/128.0], 0.2, 70.0, ftype='cheby2')
        new_mgr = e.process([mgr])[0]
        ch.Plot('CH1').process([new_mgr])

        self.assertAlmostEqual(y[2,5], new_mgr.get_samples()[2,5])
        self.assertAlmostEqual(y[0,100], new_mgr.get_samples()[0,100])
        self.assertNotAlmostEqual(mgr.get_samples()[0,100], new_mgr.get_samples()[0,100])
        LOGGER.info("FILTER tested!")
Exemple #24
0
    def signal_divide(self, signal_data):
        #简单利用带通滤波器来对信号进行分离
        fl, fh = 0.1, 0.5
        fll, fhh = 0.05, 0.55
        pass_band = [2 * fl / self.fps, 2 * fh / self.fps]
        stop_band = [2 * fll / self.fps, 2 * fhh / self.fps]
        b, a = signal.iirdesign(pass_band, stop_band, 2, 40)
        r_signal = signal.lfilter(b, a, signal_data)

        fl_h, fh_h = 0.8, 1.9
        fll_h, fhh_h = 0.7, 2.0
        pass_band_h = [2 * fl_h / self.fps, 2 * fh_h / self.fps]
        stop_band_h = [2 * fll_h / self.fps, 2 * fhh_h / self.fps]
        b_h, a_h = signal.iirdesign(pass_band_h, stop_band_h, 2, 40)
        h_signal = signal.lfilter(b_h, a_h, signal_data)
        return r_signal, h_signal
	def set_params(self, **kwargs):
		f = kwargs['cut_off_freq']
		normalized_pass = f/(RATE*.5)
		normalized_stop = (f+.3*f)/(RATE*.5)
		(self.b, self.a) = signal.iirdesign(normalized_pass, normalized_stop, 
											LowpassFilter.pass_band_loss, 
											LowpassFilter.stop_band_loss)
Exemple #26
0
  def update_design(self):
    ax = self.ax
    ax.cla()
    ax2 = self.ax2
    ax2.cla()

    wp = self.wp
    ws = self.ws
    gpass = self.gpass
    gstop = self.gstop
    b, a = ss.iirdesign(wp, ws, gpass, gstop, ftype=self.ftype, output='ba')
    self.a = a
    self.b = b
    #b = [1,2]; a = [1,2]
    #Print this on command line so we can use it in our programs
    print 'b = ', pylab.array_repr(b)
    print 'a = ', pylab.array_repr(a)

    my_w = pylab.logspace(pylab.log10(.1*self.ws[0]), 0.0, num=512)
    #import pdb;pdb.set_trace()
    w, h = freqz(b, a, worN=my_w*pylab.pi)
    gp = 10**(-gpass/20.)#Go from db to regular
    gs = 10**(-gstop/20.)
    self.design_line, = ax.plot([.1*self.ws[0], self.ws[0], wp[0], wp[1], ws[1], 1.0], [gs, gs, gp, gp, gs, gs], 'ko:', lw=2, picker=5)
    ax.semilogx(w/pylab.pi, pylab.absolute(h),lw=2)
    ax.text(.5,1.0, '{:d}/{:d}'.format(len(b), len(a)))
    pylab.setp(ax, 'xlim', [.1*self.ws[0], 1.2], 'ylim', [-.1, max(1.1,1.1*pylab.absolute(h).max())], 'xticklabels', [])

    ax2.semilogx(w/pylab.pi, pylab.unwrap(pylab.angle(h)),lw=2)
    pylab.setp(ax2, 'xlim', [.1*self.ws[0], 1.2])
    ax2.set_xlabel('Normalized frequency')

    pylab.draw()
Exemple #27
0
def iir_bandstops(fstops, fs, order=4):
    """ellip notch filter
    fstops is a list of entries of the form [frequency (Hz), df, df2]                           
    where df is the pass width and df2 is the stop width (narrower                              
    than the pass width). Use caution if passing more than one freq at a time,                  
    because the filter response might behave in ways you don't expect.
    """
    nyq = 0.5 * fs

    # Zeros zd, poles pd, and gain kd for the digital filter
    zd = np.array([])
    pd = np.array([])
    kd = 1

    # Notches
    for fstopData in fstops:
        fstop = fstopData[0]
        df = fstopData[1]
        df2 = fstopData[2]
        low = (fstop - df) / nyq
        high = (fstop + df) / nyq
        low2 = (fstop - df2) / nyq
        high2 = (fstop + df2) / nyq
        z, p, k = iirdesign([low,high], [low2,high2], gpass=1, gstop=6,
                            ftype='ellip', output='zpk')
        zd = np.append(zd,z)
        pd = np.append(pd,p)

    # Set gain to one at 100 Hz...better not notch there                                        
    bPrelim,aPrelim = zpk2tf(zd, pd, 1)
    outFreq, outg0 = freqz(bPrelim, aPrelim, 100/nyq)

    # Return the numerator and denominator of the digital filter                                
    b,a = zpk2tf(zd,pd,k)
    return b, a
 def generateLowpass(self, cut, transition, minAtt, maxAtt):
     print(
         "generating lowpass: cut={0} Hz; transition={1} Hz; min att={2} dB; max att={3} dB"
         .format(cut, transition, minAtt, maxAtt))
     return signal.iirdesign((cut - transition * 0.5) / self.nyquist,
                             (cut + transition * 0.5) / self.nyquist,
                             maxAtt, minAtt)
def butterfilt(finname,
               foutname,
               fmt,
               fs,
               fl=5.0,
               fh=100.0,
               gpass=1.0,
               gstop=30.0,
               ftype='butter',
               buffer_len=100000,
               overlap_len=100,
               max_len=-1):
    """Given sampling frequency, low and high pass frequencies design a butterworth filter and filter our data with it."""
    fso2 = fs / 2.0
    wp = [fl / fso2, fh / fso2]
    ws = [0.8 * fl / fso2, 1.4 * fh / fso2]
    import pdb
    pdb.set_trace()
    b, a = iirdesign(wp,
                     ws,
                     gpass=gpass,
                     gstop=gstop,
                     ftype=ftype,
                     output='ba')
    y = filtfiltlong(finname, foutname, fmt, b, a, buffer_len, overlap_len,
                     max_len)
    return y, b, a
Exemple #30
0
def filtersong(a):
    """highpass iir filter for song."""
    out = []
    b = signal.iirdesign(wp=0.04, ws=0.02, gpass=1, gstop=60, ftype='ellip')
    out.append(signal.filtfilt(b[0], b[1], a[0]))
    out.append(a[1])
    return out
Exemple #31
0
def _design_iir(wp,
                ws,
                sample_rate,
                gpass,
                gstop,
                analog=False,
                ftype='cheby1',
                output='zpk'):
    nyq = sample_rate / 2.
    wp = atleast_1d(wp)
    ws = atleast_1d(ws)
    if analog:
        wp *= TWO_PI
        ws *= TWO_PI
    else:
        wp /= nyq
        ws /= nyq
    z, p, k = signal.iirdesign(wp,
                               ws,
                               gpass,
                               gstop,
                               analog=analog,
                               ftype=ftype,
                               output='zpk')
    if analog:
        z /= -TWO_PI
        p /= -TWO_PI
    if output == 'zpk':
        return z, p, k
    elif output == 'ba':
        return signal.zpk2tf(z, p, k)
    elif output == 'sos':
        return signal.zpk2sos(z, p, k)
    else:
        raise ValueError("'%s' is not a valid output form." % output)
Exemple #32
0
 def _design_filter(self, FS):
     if not FS in self._coefs_cache:
         wp, ws = self.fp*2/FS, self.fs*2/FS
         b,a = signal.iirdesign(wp=wp, ws=ws, gstop=self.gstop, gpass=self.gpass, ftype=self.ftype)
         self._coefs_cache[FS]=(b,a)
     else:
         b,a = self._coefs_cache[FS]
     return b, a  
Exemple #33
0
def filter_acc(x, gpass=0.1, gstop=50., sf=2000.):

    wp = 0.5 / (sf / 2.0)
    ws = 0.01 / (sf / 2.0)

    b, a = spsi.iirdesign(wp, ws, gpass, gstop)

    return spsi.filtfilt(b, a, x)
 def designIIR(self):
     """Design an iir filter with a passband from .3 to .35 using iirdesign from scipy
     """
     #note - the default filter returned with the default ftype for these
     #parameters was UNSTABLE leading to random unit test failures with nans 
     #cheby2 returns a stable filter
     b, a = iirdesign([.3, .35], [.1, .5],.1,20, ftype='cheby2')
     return b.tolist(), a.tolist()
Exemple #35
0
 def getFilter(self):
     if self.__filter__ == None:
         passband = [calcFreq(self.A, -10)/sampleRate,
                     calcFreq(self.A, 1)/sampleRate]
         stopband = [calcFreq(self.A, -11)/sampleRate,
                     calcFreq(self.A, 2)/sampleRate]
         self.__filter__ = iirdesign(passband, stopband, 5, 10, ftype="cheby1")
     return self.__filter__
Exemple #36
0
 def _desingFilterBands(self):
     nyq   = self.fs / 2.0
     trans = 2.0
     self.coeFil = []
     for freq in self.fBands:
         # Filter frequency bands
         passCut = freq / nyq
         stopCut = [(freq[0] - trans) / nyq, (freq[1] + trans) / nyq]
         self.coeFil.append(sg.iirdesign(passCut, stopCut, gpass=0.0025, gstop=30.0,
                                         analog=False, ftype='cheby2', output='sos'))
     # Filter envelops
     self.coeFilEnv = sg.iirdesign(0.5 / nyq, (0.5+trans)/nyq , gpass=0.0025, gstop=30.0,
                                         analog=False, ftype='cheby2', output='sos')
     # get edges of each frequency band to cut self.empiProfile
     nBands          = self.fBands.shape[0]
     lenBand         = self.empiProfile.shape[0] / self.fBands.shape[0]
     self.edgesBand  = np.array([np.arange(0,nBands)*lenBand, np.arange(1,nBands+1)*lenBand], dtype=np.int32)
Exemple #37
0
def get_timefilter():
    samp = Sampling(0.25)  # sampling period is 0.25 days
    wp = samp.normalize(1. /
                        (365 * 4))  # cutoff freq is time period of 4 years
    ws = samp.normalize(
        1. / (365 * 2.5))  # time periods of 2.5 years should be rejected
    b, a = s.iirdesign(wp, ws, 0.5, 6, ftype='butter')
    return FrequencyFilter(b, a, samp)
Exemple #38
0
 def band_pass(self, x, fc_low, fc_high):
     b, a = iirdesign(wp=(fc_low, fc_high),
                      ws=(fc_low - 50, fc_high + 50),
                      gpass=1,
                      gstop=60,
                      fs=self.sr)
     a = self.fix_poles(a)
     return lfilter(b, a, x)
def band_iir_filter(data,
                    Fsampling,
                    stopband=[49, 51],
                    passband=[47, 53],
                    gpass=1,
                    gstop=20,
                    filterType='butter',
                    filterDirection='twopass',
                    pad_samples=None,
                    pad_type=None,
                    **pad_kwargs):
    """
    High passes the data at the Fcutoff frequency.
    stopband = the inside corner points in Hz
    passband = the outside corner points in Hz
    If the stopband encompasses the passband the filter is a passband filter, otherwise it is a stopband
    gpass = the minimum power (in possitive dB) of the pass band
    gstop = the maximum power (in possitive dB) of the stop band
    filterType = 'butter' (default), 'cheby1', 'cheby2', 'ellip', 'bessel'
    filterDirection = FilterDirection which defines whether the filter is passed over the data once (and how) or twice
    pad_samples = the number of samples to pad with at each side (if None and pad_type is not None then default pad_samples = np.shape(data)[-1])
    pad_type = the type of paddding (see numpy.pad's mode for more info)
    pad_kwargs = extra padding arguments (see numpy.pad for more info
    """
    ws = [np.float(x / (Fsampling / 2.0)) for x in stopband]
    wp = [np.float(x / (Fsampling / 2.0)) for x in passband]

    (b, a) = signal.iirdesign(ws=ws,
                              wp=wp,
                              gpass=gpass,
                              gstop=gstop,
                              ftype=filterType,
                              output='ba')

    dims = data.ndim
    axis = 0
    if dims == 2:
        axis = 1

    if pad_type:
        data = np.pad(data, pad_samples, pad_type, pad_kwargs)

    if filterDirection == ct.FilterDirection.TWO_PASS:
        filteredData = signal.filtfilt(b, a, data, axis)
    elif filterDirection == ct.FilterDirection.ONE_PASS:
        filteredData = signal.lfilter(b, a, data, axis, zi=None)
    elif filterDirection == ct.FilterDirection.ONE_PASS_REVERSE:
        data = np.fliplr(data)
        filteredData = signal.lfilter(b, a, data, axis, zi=None)
        filteredData = np.fliplr(filteredData)

    if pad_type:
        if dims == 1:
            filteredData = filteredData[pad_samples:-pad_samples]
        if dims == 2:
            filteredData = filteredData[:, pad_samples:-pad_samples]

    return filteredData
Exemple #40
0
def chebyBandpassFilter(data, cutoff, gstop=40, gpass=1, fs=2048.):
    """
    Design a filter with scipy functions avoiding unstable results (when using
    ab output and filtfilt(), lfilter()...).
    Cf. ()[]

    Parameters
    ----------
    data : instance of numpy.array | instance of pandas.core.DataFrame
        Data to be filtered. Each column will be filtered if data is a
        dataframe.
    cutoff : array-like of float
        Pass and stop frequencies in order:
            - the first element is the stop limit in the lower bound
            - the second element is the lower bound of the pass-band
            - the third element is the upper bound of the pass-band
            - the fourth element is the stop limit in the upper bound
        For instance, [0.9, 1, 45, 48] will create a band-pass filter between
        1 Hz and 45 Hz.
    gstop : int
        The minimum attenuation in the stopband (dB).
    gpass : int
        The maximum loss in the passband (dB).

    Returns:

    zpk :

    filteredData : instance of numpy.array | instance of pandas.core.DataFrame
        The filtered data.
    """

    wp = [cutoff[1] / (fs / 2), cutoff[2] / (fs / 2)]
    ws = [cutoff[0] / (fs / 2), cutoff[3] / (fs / 2)]

    z, p, k = iirdesign(wp=wp,
                        ws=ws,
                        gstop=gstop,
                        gpass=gpass,
                        ftype='cheby2',
                        output='zpk')
    zpk = [z, p, k]
    sos = zpk2sos(z, p, k)

    order, Wn = cheb2ord(wp=wp, ws=ws, gstop=gstop, gpass=gpass, analog=False)
    print 'Creating cheby filter of order %d...' % order

    if (data.ndim == 2):
        print 'Data contain multiple columns. Apply filter on each columns.'
        filteredData = np.zeros(data.shape)
        for electrode in range(data.shape[1]):
            # print 'Filtering electrode %s...' % electrode
            filteredData[:, electrode] = sosfiltfilt(sos, data[:, electrode])
    else:
        # Use sosfiltfilt instead of filtfilt fixed the artifacts at the beggining
        # of the signal
        filteredData = sosfiltfilt(sos, data)
    return zpk, filteredData
Exemple #41
0
def mgr_filter(mgr,
               wp,
               ws,
               gpass,
               gstop,
               analog=0,
               ftype='ellip',
               output='ba',
               unit='hz',
               use_filtfilt=False,
               meancorr=1.0):
    if unit == 'radians':
        b, a = signal.iirdesign(wp, ws, gpass, gstop, analog, ftype, output)
    elif unit == 'hz':
        nyquist = float(mgr.get_param('sampling_frequency')) / 2.0
        try:
            wp = wp / nyquist
            ws = ws / nyquist
        except TypeError:
            wp = [i / nyquist for i in wp]
            ws = [i / nyquist for i in ws]

        b, a = signal.iirdesign(wp, ws, gpass, gstop, analog, ftype, output)
    if use_filtfilt:
        from scipy.signal import filtfilt
        #samples_source = read_data_source.MemoryDataSource(mgr.get_samples(), False)
        for i in range(int(mgr.get_param('number_of_channels'))):
            print("FILT FILT CHANNEL " + str(i))
            mgr.get_samples()[i, :] = signal.filtfilt(
                b, a,
                mgr.get_samples()[i] -
                np.mean(mgr.get_samples()[i]) * meancorr)
        samples_source = read_data_source.MemoryDataSource(
            mgr.get_samples(), False)
    else:
        print("FILTER CHANNELs")
        filtered = signal.lfilter(b, a, mgr.get_samples())
        print("FILTER CHANNELs finished")
        samples_source = read_data_source.MemoryDataSource(filtered, True)

    info_source = copy.deepcopy(mgr.info_source)
    tags_source = copy.deepcopy(mgr.tags_source)
    new_mgr = read_manager.ReadManager(info_source, samples_source,
                                       tags_source)
    return new_mgr
Exemple #42
0
def butterfilt(finname, foutname, fmt, fs, fl=5.0, fh=100.0, gpass=1.0, gstop=30.0, ftype='butter', buffer_len=100000, overlap_len=100, max_len=-1):
  """Given sampling frequency, low and high pass frequencies design a butterworth filter and filter our data with it."""
  fso2 = fs/2.0
  wp = [fl/fso2, fh/fso2]
  ws = [0.8*fl/fso2,1.4*fh/fso2]
  import pdb; pdb.set_trace()
  b, a = iirdesign(wp, ws, gpass=gpass, gstop=gstop, ftype=ftype, output='ba')
  y = filtfiltlong(finname, foutname, fmt, b, a, buffer_len, overlap_len, max_len)
  return y, b, a
def continuous_bandpass_filter(left, right, freq_low, freq_high, framerate):
	pass_region = [0.075, 0.2]
	stop_region = [0.05, 0.8]
	pass_max_damp = 1
	stop_min_damp = 80
	b, a = signal.iirdesign(pass_region, stop_region, pass_max_damp, stop_min_damp)
	w, h = signal.freqz(b, a)
	new_left = signal.lfilter(b, a, left)
	new_right = signal.lfilter(b, a, right)
	return new_left, new_right
	def get_effected_signal(self, sig):
		if self.it >= 1000:
			self.it = 0
		freq = self.f + self.sin_wave[self.it]
		self.it += 1
		normalized_pass = freq/(RATE*.5)
		normalized_stop = (freq+.3*freq)/(RATE*.5)
		(a, b) = signal.iirdesign(normalized_pass, normalized_stop, 1, 30)
		out = signal.lfilter(b, a, sig)
		return out / np.max(out)
Exemple #45
0
def butterworth_bandpass_filter(left_channel, right_channel, pass_region, stop_region, framerate):
	pass_region = 2*pass_region/framerate
	stop_region = 2*stop_region/framerate
	#print(pass_region, stop_region)
	pass_max_damp = 2
	stop_min_damp = 20
	b, a = signal.iirdesign(pass_region, stop_region, pass_max_damp, stop_min_damp)
	new_left_channel = signal.lfilter(b, a, left_channel)
	new_right_channel = signal.lfilter(b, a, right_channel)
	return new_left_channel, new_right_channel
Exemple #46
0
	def getFramePitchAdvanced(self):
		if len(self.speechSegment)==0 or self.isBlank==True:
			return
		
		self.p = []
		b, a = signal.iirdesign([60.0*2/self.sampleRate,950.0*2/self.sampleRate],[50.0*2/self.sampleRate,1000.0*2/self.sampleRate],2,40)
		for frame in self.frame:
			filt = signal.lfilter(b,a,frame)
			minAMDF = utils.AMDF(filt)
			pitch = self.sampleRate/minAMDF
			self.p.append(pitch)
Exemple #47
0
 def _design_filter(self, FS):
     
     if not FS in self._coefs_cache:
         wp = np.array(self.fband)
         ws = wp + np.array([-self.tw, self.tw])
         wp, ws = wp*2./FS, ws*2./FS
         b,a = signal.iirdesign(wp=wp, ws=ws, gstop=self.gstop, gpass=self.gpass, ftype=self.ftype)
         self._coefs_cache[FS]=(b,a)
     else:
         b,a = self._coefs_cache[FS]
     return b, a  
def naive_dsp(left, right, freq_low, freq_high, framerate):
	low_pass = 0.05
	low_stop = 0.1
	high_pass = low_stop
	high_stop = low_pass
	pass_max_damp = 2
	stop_min_damp = 40

	b1, a1 = signal.iirdesign(low_pass, low_stop, pass_max_damp, stop_min_damp)
	b2, a2 = signal.iirdesign(high_pass, high_stop, pass_max_damp, stop_min_damp)

	left = signal.lfilter(b1, a1, left)
	right = signal.lfilter(b1, a1, right)

	new_left = left - right
	new_right = left - right

	left = signal.lfilter(b2, a2, new_left)
	right = signal.lfilter(b2, a2, new_right)

	return left, right
def makeFIRCoefs(samplingFreq, IFFreq, bandwidth, numPoints, numTaps):
    IFFreq = IFFreq * 1e06
    (b, a) = signal.iirdesign(IFFreq / 2, IFFreq, 3, 30, ftype="butter")
    timeStep = 1.0 / samplingFreq
    timePts = np.arange(0, numPoints * timeStep, timeStep)
    stepImpulse = [0 if i < len(timePts) / 2 else 1 for i in range(len(timePts))]
    unitImpulse = [1 if i == 0 else 0 for i in range(len(timePts))]
    nIFFreq = IFFreq / (samplingFreq / 2)
    nbandwidth = bandwidth / (samplingFreq / 2)
    print "Cuttoff frequency: ", nIFFreq, "Hz\n"
    print "building FIR coefficients with {} taps...\n".format(numTaps)
    firCoefs = signal.firwin(
        float(numTaps),
        0.09 * samplingFreq,
        width=None,
        window="hamming",
        pass_zero=True,
        scale=True,
        nyq=samplingFreq / 2,
    )

    # step impulse for polyphase filter input test:
    with open("/home/nick/firFilter/stepFunction" + str(numPoints) + ".txt", "w") as stepfid:
        stepfid.write("signal myStepImpulse : vector_array :=(")
        stepfid.write(",".join(['x"{0:04X}"'.format(x) for x in stepImpulse]) + ");")
    with open("/home/nick/firFilter/unitImpulse" + str(numPoints) + ".txt", "w") as impfid:
        impfid.write("signal myUnitImpulse : vector_array :=(")
        impfid.write(",".join(['x"{0:04X}"'.format(x) for x in unitImpulse]) + ");")

        # for i in range(len(firCoefs)):
        # 	print 'Reload index {} = {number:.{width}f}'.format(i,number=firCoefs[i],width=32)

        # two's complement filter coefficients for VHDL:
    with open("/home/nick/firFilter/firCoefs" + str(int(numTaps)) + "taps.coe", "w") as fid:
        fid.write("radix=10;\ncoefdata=")
        fid.write(",".join(["{number:.{width}f}".format(number=f, width=32) for f in firCoefs]) + ";")
    with open("/home/nick/firFilter/firCoefs" + str(IFFreq / 1.0e06) + "MHzVHDL.txt", "w") as fid2:
        fid2.write(
            "type vector_arrayTaps is array ("
            + str(numTaps - 1)
            + " downto 0) of std_logic_vector(15 downto 0);\nsignal myReload : vector_arrayTaps:=("
        )
        fid2.write(
            ",".join(['x"{0:04X}"'.format((~int(np.abs(x * pow(2, 16 - 1))) & 0xFFF) + 1) for x in firCoefs]) + ");"
        )

        # IIR filter coefficients written to VHDL:
    with open("/home/nick/firFilter/iirCoefs" + str(int(IFFreq / 1.0e06)) + "MHzVHDL.txt", "w") as iirfid:
        iirfid.write("signal loadIIRCoefsA : vector_array :=(")
        iirfid.write(",".join(['x"{0:04X}"'.format((~int(np.abs(x * pow(2, 64 - 1))) & 0xFFFF) + 1) for x in a]) + ");")
        iirfid.write("\nsignal loadIIRCoefsB : vector_array :=(")
        iirfid.write(",".join(['x"{0:04X}"'.format((~int(np.abs(x * pow(2, 64 - 1))) & 0xFFFF) + 1) for x in b]) + ");")
Exemple #50
0
def generateBandpass(nyquist, stopBefore, stopAfter, transition, minAtt, maxAtt):
    return signal.iirdesign(
        (
            stopBefore + transition / 2.,
            stopAfter - transition / 2.
        ),
        (
            stopBefore - transition / 2.,
            stopAfter + transition / 2.
        ),
        maxAtt,
        minAtt
    )
Exemple #51
0
def build_butterworth_filter(passband_frequency, stopband_frequency):
	"""Builds a butterworth filter and returns the paramters needed to use the
	filter on a signal."""
	# filter_b and filter_a are numerator and denominator of the low-pass filter
	# original: gpass=5 gstop=60
	filter_b, filter_a = iirdesign(
		passband_frequency, stopband_frequency,
		gpass=5, gstop=20, analog=0, ftype="butter"
	)
	
	w, h = scipy.signal.freqz(filter_b, filter_a)
	response_magnitude = abs(h)
	sample_frequencies = w / pi
	
	return (filter_b, filter_a, response_magnitude, sample_frequencies)
Exemple #52
0
def filter_waveforms(waveform, 
                     Fstop_lo = 800, Fpass_lo = 1000,
                     Fpass_hi = 3000, Fstop_hi = 3500, Fs = 30000.):
  """
  waveform - m x n array. m waveforms each of n samples
  Fstop - stop band for high pass filter
  Fpass - pass band for high pass filter
  Fs - sampling frequency of spike waveform."""
  ws = [2*Fstop_lo/Fs, 2*Fstop_hi/Fs]#2* because ws is in terms of nyquist freq which is .5*Fs
  wp = [2*Fpass_lo/Fs, 2*Fpass_hi/Fs]
  b,a = ss.iirdesign(wp, ws, gpass=1, gstop=10)
  for n in range(waveform.shape[0]):
    waveform[n,:] = filtfilt(b,a,waveform[n,:])#ss.lfilter(b,a, waveform[n,:])
  
  return waveform
Exemple #53
0
def calPitch(maxData,frames,fs):
	'''Calculate the signal pitch, regardless vowel or not

	'''
	
	pitch = []
	acf = []
	b, a = iirdesign([60.0*2/fs,950.0*2/fs],[50.0*2/fs,1000.0*2/fs],2,40)
	for frame in frames:
		#cur = lfilter(b,a,frame)
		cur = frame
		curPitch, curAcf = ACF(maxData,cur,fs)
		pitch.append(curPitch)
		acf.append(curAcf)
	return pitch,acf
Exemple #54
0
def SignalFilter(signal, LPF, HPF, samplefreq):
    """Filter signal within a bandpass with elliptical filter

    Digitally filter a signal with an elliptical filter; handles
    bandpass filtering between two frequencies. 

    Parameters
    ----------
    signal : array
        The signal to be filtered.
    LPF : float
        The low-pass frequency of the filter (Hz)
    HPF : float
        The high-pass frequency of the filter (Hz)
    samplefreq : float
        The uniform sampling rate for the signal (in seconds)

    Returns
    -------
    w : array
        filtered version of the input signal
    """
    if debugFlag:
        print "sfreq: %f LPF: %f HPF: %f" % (samplefreq, LPF, HPF)
    flpf = float(LPF)
    fhpf = float(HPF)
    sf = float(samplefreq)
    sf2 = sf / 2
    wp = [fhpf / sf2, flpf / sf2]
    ws = [0.5 * fhpf / sf2, 2 * flpf / sf2]
    if debugFlag:
        print "signalfilter: samplef: %f  wp: %f, %f  ws: %f, %f lpf: %f  hpf: %f" % (
            sf,
            wp[0],
            wp[1],
            ws[0],
            ws[1],
            flpf,
            fhpf,
        )
    filter_b, filter_a = spSignal.iirdesign(wp, ws, gpass=1.0, gstop=60.0, ftype="ellip")
    msig = np.mean(signal)
    signal = signal - msig
    w = spSignal.lfilter(filter_b, filter_a, signal)  # filter the incoming signal
    signal = signal + msig
    if debugFlag:
        print "sig: %f-%f w: %f-%f" % (np.amin(signal), np.amax(signal), np.amin(w), np.amax(w))
    return w
Exemple #55
0
def simple_filt(input_signal,passband,prf,ps='pass'):
    """
    A simple filter creator that creates an iirfilter based on the passband given by passband and the prf, and filters the input signal.
    @param input_signal: The signal to be filtered.
    @param passband: The pass band list [low, high]. If low=0, the filter will be a lowpass filter, if high=0, the filter is a highpass filter.
    @param prf: The prf.
    """
    gpass=4
    gstop=40
    if ps=='pass':
        if passband[0]==0:
            #Lowpassfilter
            wp=passband[1]/(prf/2.0)
            ws=min(wp*1.5,1)
        elif passband[1]==0:
            #Highpassfilter
            wp=passband[0]/(prf/2.0)
            ws=wp*0.5
        else:
            #Bandpassfilter
            wp=[passband[0]/(prf/2.0) , passband[1]/(prf/2.0)]
            #ws=[wp[0]-min(wp[0],.25),wp[1]+.25]
            ws=[wp[0]*0.5 , min(wp[1]*1.5,1)]
    elif ps=='stop':
        ws=[passband[0]/(prf/2.0) , passband[1]/(prf/2.0)]
        wp = [ws[0]*0.8 , min(ws[1]*1.25,1)]
        
    b,a=signal.iirdesign(wp,ws,gpass,gstop,ftype='cheby2')#Design of the filter
    heartbeats=signal.lfilter(b,a,input_signal.conj().T)
    #The time reversed signal is run through the same filter to correct phase distortion:
    if len(heartbeats.shape)>1:
        heartbeats=signal.lfilter(b,a,heartbeats[:,::-1])
        heartbeats=heartbeats[:,::-1]
    else:
        heartbeats=signal.lfilter(b,a,heartbeats[::-1])
        heartbeats=heartbeats[::-1]

    print 'Filter order: ',len(b)

    ## import pylab
##    w,h=signal.freqz(b,a)
    ## pylab.figure()
##     pylab.title('Filter frequency response for '+str(passband)+' Hz filter')
##     pylab.plot(w*prf/(2*numpy.pi),20*numpy.log10(abs(h)))
##     pylab.ylim( (-60,1) )
    #print 'Largest filter freqeuncy response value: '+str(max(h))
    return heartbeats.conj().T
 def __init__(
         self, name, passband_end_frequency, stopband_start_frequency,
         input_sample_rate):
     
     # Design filter.
     fs2 = input_sample_rate / 2
     f_pass = passband_end_frequency / fs2
     f_stop = stopband_start_frequency / fs2
     b, a = signal.iirdesign(f_pass, f_stop, 1, 30, ftype='butter')
     
     super().__init__(name, len(b), 1, input_sample_rate)
     
     # Initialize filter coefficients.
     self._a = a
     self._b = b
     
     # Initialize filter state.
     self._state = np.zeros(max(len(a), len(b)) - 1)
Exemple #57
0
def iir_basic(a):
  
        filt_type = a["Response Type"]
        
        print('filt_type', filt_type)
        design_method = a["Design_Methode"]
        if design_method == 'Elliptic':
            ftype = 'ellip'
        elif design_method == 'Chebychev 1':
            ftype = 'cheby1'
        elif design_method == 'Chebychev 2':
            ftype = 'cheby2'
        elif design_method == 'Butterworth':
            ftype = 'butter'
#        else: raise_exception
            
        print('design_method', design_method)
        N = a['Order']
        print('order',N)
        fs = a["Fs"]
        F_pass = 2 * a["Fpass"]/fs
#        F_stop = 2 * a[3][2][2]/fs
        F_stop = 0.8
        print('fs','fpass','fstop',fs, F_pass, F_stop)
        A_pass = a["Apass"]
        A_stop = a["Astop"]
#        A_stop = a[4][2][2]
        print('A_pass', 'A_stop', A_pass, A_stop)
#        W = a[5]
#        print('W',W)
        
        if N == 'min':
            b,a = sig.iirdesign(F_pass, F_stop, A_pass, A_stop, analog = False, 
                                ftype = ftype, output = 'ba')            
        else:
            if ftype == 'ellip':
                b,a = sig.ellip(N, A_pass, A_stop, [F_pass, F_stop], btype ='low' )
            elif ftype == 'cheby1':
                b,a = sig.cheby1(N, A_pass, [F_pass, F_stop], btype ='low' )
            elif ftype == 'cheby2':
                b,a = sig.cheby2(N, A_stop, [F_pass, F_stop], btype ='low' )
            elif ftype == 'butter':
                b,a = sig.butter(N, (2 * a["Fc"]/fs), btype ='low' )
        return b, a
Exemple #58
0
def create_notch(frequency, sample_rate, type='iir', **kwargs):
    """Design a ZPK notch filter for the given frequency and sampling rate

    Parameters
    ----------
    frequency : `float`, `~astropy.units.Quantity`
        frequency (default in Hertz) at which to apply the notch
    sample_rate : `float`, `~astropy.units.Quantity`
        number of samples per second for `TimeSeries` to which this notch
        filter will be applied
    type : `str`, optional, default: 'iir'
        type of filter to apply, currently only 'iir' is supported
    **kwargs
        other keyword arguments to pass to `scipy.signal.iirdesign`

    Returns
    -------
    zpk : `tuple` of `complex` or `float`
       the filter components in digital zero-pole-gain format

    See Also
    --------
    scipy.signal.iirdesign
        for details on the IIR filter design method
    """
    frequency = Quantity(frequency, 'Hz').value
    sample_rate = Quantity(sample_rate, 'Hz').value
    nyq = 0.5 * sample_rate
    df = 1.0
    df2 = 0.1
    low1 = (frequency - df)/nyq
    high1 = (frequency + df)/nyq
    low2 = (frequency - df2)/nyq
    high2 = (frequency + df2)/nyq
    if type == 'iir':
        kwargs.setdefault('gpass', 1)
        kwargs.setdefault('gstop', 10)
        kwargs.setdefault('ftype', 'ellip')
        return signal.iirdesign([low1, high1], [low2, high2], output='zpk',
                                **kwargs)
    else:
        raise NotImplementedError("Generating %r notch filters has not been "
                                  "implemented yet" % type)