コード例 #1
0
def iir_noise_filter(name, df, current_col):

    #extracting sampling rate from parameter file
    parafile = name + '-parameters.txt'
    try:
        params = read_csv(parafile, delim_whitespace=True, engine='python', names=['0','1','2','3'], index_col=0)
    except:
        print('Cannot find parameter file')
    samplerate = params['2']['Samplerate']
    Samplingrates = {"2.5Hz":2.5, "5Hz":5.0, "10Hz":10.0, "15Hz":15.0,
                         "25Hz":25.0, "30Hz":30.0, "50Hz":50.0, "60Hz":60.0,
                         "100Hz":100.0, "500Hz":500.0, "1KHz":1000.0, "2KHz":2000.0,
                         "3.75KHz":3750.0, "7.5KHz":7500.0, "15KHz":1500.0, "30KHz":30000.0}
    samplerate = Samplingrates[samplerate]

    #constructing IIR notch filters
    fs = samplerate   # Sample frequency (Hz)
    f0 = 60.0  # Frequency to be removed from signal (Hz)
    Q = 2.0  # Quality factor
    # Design notch filter
    b, a = signal.iirnotch(f0, Q, fs)
    c, d = signal.iirnotch(f0*2, Q, fs)
    e, f = signal.iirnotch(f0*4, Q, fs)
    g, h = signal.iirnotch(f0*5, Q, fs)
    i, j = signal.iirnotch(f0*6, Q, fs)
    
    #apply filters
    yf1 = signal.filtfilt(b,a,df[current_col]) #60Hz filter
    yf2 = signal.filtfilt(c,d,yf1) #120Hz filter
    yf3 = signal.filtfilt(e,f,yf2) #240Hz filter
    yf4 = signal.filtfilt(g,h,yf3) #300Hz filter
    yf5 = signal.filtfilt(i,j,yf4) #360Hz filter

    return yf5
コード例 #2
0
def notch(x, Q):

    fs = 10000
    f0 = 50
    w0 = f0 / (fs / 2)
    b, a = scisig.iirnotch(w0, Q)
    y = scisig.filtfilt(b, a, x)

    return y
コード例 #3
0
ファイル: bisijao.py プロジェクト: jakaBlaz/BCI-Robotska-Roka
def notch_filter(data,f0,Q,Fs):
    # f0 = Frequency to be removed from signal (Hz)
    # Q = Quality factor
    w0 = f0/(Fs/2)  # Normalized Frequency
    # Design notch filter
    b, a = signal.iirnotch(w0, Q)
    zi = signal.lfilter_zi(b, a)
    y = signal.filtfilt(b, a, data)
    return y
コード例 #4
0
ファイル: main.py プロジェクト: fMeow/OpenSSVEP
 def refresh_notch_filter(self, f=50, enable=True):
     if enable:
         w0 = f / (self.fs / 2)
         self.bNotch, self.aNotch = signal.iirnotch(w0, 1)
     else:
         self.bNotch = np.array([1])
         self.aNotch = np.array([1])
     self.xbufNotch = [0 for i in range(len(self.bNotch) - 1)]
     self.ybufNotch = [0 for i in range(len(self.aNotch) - 1)]
コード例 #5
0
def read_data(data,
              dataset_path,
              M=25,
              each_lead_time=2.5,
              num_samples=10000,
              num_leads=12,
              images_per_record=10,
              power_line_freq=50,
              bandwidth=10):
    '''
    num_samples = 10000     # no of samples to read from each  record
    num_leads = 12         # 12 leads out of given 15 to be choosen
    sampling_freq = 1000   # 1000 Hz
    each_lead_time = 2.5   # 2.5 seconds
    M = 25                 # mov avg filter
    images_per_record = 10
    power_line_freq = 50
    
    '''

    fields = []
    signals = []
    Q = power_line_freq / bandwidth

    for i in data:
        sig, f = wfdb.rdsamp(dataset_path + i[:-1],
                             channels=[x for x in range(num_leads)],
                             sampfrom=0,
                             sampto=num_samples)
        sampling_freq = f['fs']

        b, a = iirnotch(power_line_freq, Q, sampling_freq)

        s = np.zeros((num_samples - M + 1, num_leads))
        for leads in range(num_leads):
            sig[:, leads] = lfilter(b, a, sig[:, leads])
            s[:, leads] = np.convolve(sig[:, leads],
                                      np.ones((M, )) / M,
                                      mode='valid')

        if (f['comments'][4] == 'Reason for admission: Myocardial infarction'
                or f['comments'][4]
                == 'Reason for admission: Healthy control'):
            for copies in range(images_per_record):
                if (each_lead_time * sampling_freq * (copies + 1)) < len(s):
                    s_temp = s[int(each_lead_time * sampling_freq * copies):
                               int(each_lead_time * sampling_freq *
                                   (copies +
                                    1))]  # 2.5 sec interval is selected
                    s_temp = s_temp - s_temp.mean(
                        axis=0)  # remove baseline drift
                    signals += [s_temp]
                    fields += [f]

    print("Dataset Read!!!")
    return signals, fields
コード例 #6
0
def notch_pass_filter(
    data,
    center,
    interval=2,
    fs=1000
):  # interval = 대역폭 (좌우로 얼마나 지울지) sharp 하게 적용하자, 차라리 for 문으로 49,50,51을 모두 sharp하게 지우자
    b, a = signal.iirnotch(center, center / interval, fs)
    filtered_data = signal.lfilter(b, a, data)

    return filtered_data
コード例 #7
0
def notch(data, notch_Hz, bandwidth):
    nyquist_Hz = data.samplerate_Hz / 2
    w0 = notch_Hz / nyquist_Hz
    quality = w0 / bandwidth
    b, a = signal.iirnotch(w0, quality)
    filtereddata = signal.lfilter(b, a, data.values)
    return Timeseries(filtereddata,
                      timestamps=data.times,
                      samplerate_Hz=data.samplerate_Hz,
                      units=data.units)
コード例 #8
0
def notch_filter(y, fs):
    f0 = random.uniform(30.0, 2000)
    print(f0)
    w0 = f0 / (fs / 2)
    Q = 0.01
    b, a = signal.iirnotch(w0, Q)
    # y = signal.filtfilt(b, a, y)
    y = signal.lfilter(b, a, y)

    return y
コード例 #9
0
def notch_filter(data, cutoff, fs):
    '''
    陷波滤波器,cutoff为被限制频率,值为0 < cutoff < (fs/2)
    '''
    w0 = cutoff / (fs / 2)
    Q = min(3 / w0, 3)  # 质量系数
    assert w0 > 0 and w0 <= 1
    b, a = iirnotch(w0, Q)
    y = lfilter(b, a, data)
    return y
コード例 #10
0
ファイル: Filtering.py プロジェクト: MoonRiyadh/CoCoRo
    def check_bpmd(data, sfreq):
        """
        The standard bandpass median difference check as described in 18.8.2 in the manual.
        :param data: the data matrix
        :return: a boolean array indicating good(True) and bad(False) signal quality for each channel
        """

        # Apply Notch filters
        fif_num, fif_dem = signal.iirnotch(50,
                                           50 / Filtering.BANDWITH,
                                           fs=sfreq)
        six_num, six_dem = signal.iirnotch(60,
                                           60 / Filtering.BANDWITH,
                                           fs=sfreq)
        notch_data = [
            signal.lfilter(six_num, six_dem,
                           signal.lfilter(fif_num, fif_dem, row))
            for row in data
        ]
        notch_freqs = [fftpack.rfft(row) for row in notch_data]
        notch_mean = [
            sum(row[51 - 2:51 + 2]) / len(row[51 - 2:51 + 2]) +
            sum(row[61 - 2:61 + 2]) / len(row[61 - 2:61 + 2])
            for row in notch_freqs
        ]
        notch_mean = [val / 2 for val in notch_mean]

        # Apply Band Pass
        band_num, band_dem = signal.butter(
            2, [0.1 / (sfreq / 2), 30 / (sfreq / 2)],
            output='ba',
            btype="bandpass")
        band_data = [
            signal.lfilter(band_num, band_dem,
                           signal.lfilter(band_num, band_dem, row))
            for row in data
        ]
        band_freqs = [fftpack.rfft(row) for row in band_data]
        band_mean = [sum(row[1:30]) / len(row[1:30]) for row in band_freqs]

        return [
            band_mean[i] - notch_mean[i] > 0.1 for i in range(len(band_mean))
        ]
コード例 #11
0
ファイル: cage_utils.py プロジェクト: wisecg/CAGE
def notchFilter(waveform, f_notch, Q):
    """
    apply notch filter of some frequency f_notch (Hz) with some quality factor Q
    """
    wf = waveform
    clk = 100e6  # 100 MHz sampling frequency of SIS 3302

    b_notch, a_notch = signal.iirnotch(f_notch, Q, clk)
    wf_notch = signal.filtfilt(b_notch, a_notch, wf)
    return wf_notch
コード例 #12
0
def get_filter(Fs, power_line_fr):

    fs = Fs  # Sample frequency (Hz)
    f0 = power_line_fr  # Frequency to be removed from signal (Hz)
    Q = 20.0  # Quality factor
    w0 = f0 / (fs / 2)  # Normalized Frequency
    # Design notch filter
    b, a = signal.iirnotch(w0, Q)

    return b, a
コード例 #13
0
def notch_iir(fs,f0,data):
    '''
    fs: Sample frequency (Hz)
    f0: Frequency to be removed from signal (Hz)
    '''
 
    Q = 10.# 30.0  # Quality factor
    w0 = float(f0)/(fs/2)  # Normalized Frequency
    b, a = signal.iirnotch(w0, Q)
    return lfilter(b, a, data)
コード例 #14
0
def iir_band_filter(ite_data,
                    fs,
                    btype,
                    ftype,
                    order=None,
                    Quality=None,
                    window=None,
                    lowcut=None,
                    highcut=None,
                    zerophase=None,
                    rps=None):
    fe = fs / 2.0
    if not lowcut == '' and not highcut == '':
        wn = [lowcut / fe, highcut / fe]
    elif not lowcut == '':
        wn = lowcut / fe
    elif not highcut == '':
        wn = highcut / fe

    if rps[0] == '':
        rps[0] = 10
    if rps[1] == '':
        rps[1] = 10

    if btype in ["butter", "bessel", "cheby1", "cheby2", "ellip"]:
        z, p, k = signal.iirfilter(order,
                                   wn,
                                   btype=ftype,
                                   ftype=btype,
                                   output="zpk",
                                   rp=rps[0],
                                   rs=rps[1])
        try:
            sos = signal.zpk2sos(z, p, k)
            ite_data = signal.sosfilt(sos, ite_data)
            if zerophase:
                ite_data = signal.sosfilt(sos, ite_data[::-1])[::-1]
        except:
            print('A filter had an issue: ', 'btype', btype, 'ftype', ftype,
                  'order', order, 'Quality', Quality, 'window', window,
                  'lowcut', lowcut, 'highcut', highcut, 'rps', rps)
    elif btype == "iirnotch":
        b, a = signal.iirnotch(lowcut, Quality, fs)
        y = signal.filtfilt(b, a, ite_data)
    elif btype == "Moving average":
        z2 = np.cumsum(np.pad(ite_data, ((window, 0)),
                              'constant',
                              constant_values=0),
                       axis=0)
        z1 = np.cumsum(np.pad(ite_data, ((0, window)),
                              'constant',
                              constant_values=ite_data[-1]),
                       axis=0)
        ite_data = (z1 - z2)[(window - 1):-1] / window
    return ite_data
コード例 #15
0
    def __init__(self, recording, freq=3000, q=30, chunk_size=30000, cache_chunks=False):
        assert HAVE_NFR, "To use the NotchFilterRecording, install scipy: \n\n pip install scipy\n\n"
        self._freq = freq
        self._q = q
        fn = 0.5 * float(recording.get_sampling_frequency())
        self._b, self._a = ss.iirnotch(self._freq / fn, self._q)

        if not np.all(np.abs(np.roots(self._a)) < 1):
            raise ValueError('Filter is not stable')
        FilterRecording.__init__(self, recording=recording, chunk_size=chunk_size, cache_chunks=cache_chunks)
        self.copy_channel_properties(recording)
コード例 #16
0
    def __init__(self, recording, freq=3000, q=30, chunk_size=30000, cache_chunks=False):
        self._freq = freq
        self._q = q
        fn = 0.5 * float(recording.get_sampling_frequency())
        self._b, self._a = ss.iirnotch(self._freq / fn, self._q)

        if not np.all(np.abs(np.roots(self._a)) < 1):
            raise ValueError('Filter is not stable')
        FilterRecording.__init__(self, recording=recording, chunk_size=chunk_size, cache_chunks=cache_chunks)
        self._kwargs = {'recording': recording.make_serialized_dict(), 'freq': freq,
                        'q': q, 'chunk_size': chunk_size, 'cache_chunks': cache_chunks}
コード例 #17
0
def all(order=1, ts=0.001, Q=10):
    x = range(0, 20000)
    y = range(0, 20000)
    yy = range(0, 20000)
    y_sqrt = range(0, 20000)
    i = 0
    while i < 4000:
        y[i] = 220.0 * m.sqrt(2) * m.sin(i / 100.0)
        y_sqrt[i] = m.sqrt(y[i] * y[i])
        yy[i] = calc_rms(y[i])
        i += 1
    while i < 8000:
        y[i] = 180.0 * m.sqrt(2) * m.sin(i / 100.0)
        y_sqrt[i] = m.sqrt(y[i] * y[i])
        yy[i] = calc_rms(y[i])
        i += 1
    while i < 14000:
        y[i] = 260.0 * m.sqrt(2) * m.sin(i / 100.0)
        y_sqrt[i] = m.sqrt(y[i] * y[i])
        yy[i] = calc_rms(y[i])
        i += 1
    while i < len(x):
        y[i] = 230.0 * m.sqrt(2) * m.sin(i / 100.0)
        y_sqrt[i] = m.sqrt(y[i] * y[i])
        yy[i] = calc_rms(y[i])
        i += 1


#LPF filter
    b, a = butter(order, ts, 'low', False)
    yy_lpf100 = lfilter(b, a, yy)

    #resample and second lpf
    yy_lpf100_1KHz = yy_lpf100[0::20]  # 20KHz->1kHz
    b2, a2 = butter(1, 7.0 / 1000, 'low', False)  # Fc=7Hz at Fs=1Khz
    yy_lpf7_1KHz = lfilter(b2, a2, yy_lpf100_1KHz)
    yy_lpf7 = signal.resample(yy_lpf7_1KHz, 20000)  #1KHz->20kHz

    #notch filter
    w0 = 2 / 314.15926
    b_notch, a_notch = signal.iirnotch(w0, Q)
    yy_notch = lfilter(b_notch, a_notch, yy)

    #plt.plot (yy_lpf,yy_notch)
    print "size is "
    print len(yy_lpf7)
    #	plt.plot (range(0,1000),yy_lpf100_1KHz,yy_lpf7_1KHz)

    plt.plot(x, yy_lpf7, yy_notch)
    #	plt.plot (x,yy_lpf100,yy_lpf7)
    plt.legend(('Old', 'New'), loc='upper-right')
    plt.title('Exisiting implementation vs New /notch filter 50Hz q=5/')

    plt.show()
コード例 #18
0
ファイル: filtering.py プロジェクト: JamesTev/EEG-decoding
def iir_notch(y, f0, fs, Q=30):
    w0 = f0 / (fs / 2)
    Q = 30
    b, a = iirnotch(w0, Q)

    # filter response
    w, h = freqz(b, a)
    filt_freq = w * fs / (2 * np.pi)
    y_filt = filtfilt(b, a, y)

    return y_filt
コード例 #19
0
    def __init__(self):
        # microphone setup
        self.chunk = 1024 * 2
        self.format = pyaudio.paInt16
        self.channels = 1
        self.rate = 44100

        # set up graph
        pg.setConfigOptions(antialias=True)
        self.win = pg.GraphicsWindow()
        self.win.setWindowTitle("Spectrum Analyzer")

        self.waveform = self.win.addPlot(title="Waveform", )

        self.spectrum = self.win.addPlot(title="Spectrum", )

        # make window for spectrogram plot
        self.win.nextRow()
        self.spectrogram = self.win.addPlot()
        self.img = pg.ImageItem()
        self.spectrogram.addItem(self.img)
        self.data = np.zeros((500, int(self.chunk / 10)))
        #        self.data = np.random.rand(500 ,int(self.chunk/4))
        self.img.setImage(self.data)
        self.spectrogram.hideAxis('bottom')
        self.spectrogram.hideAxis('left')

        self.traces = dict()  # to hold the data we will plot

        # set up audio stream
        self.p = pyaudio.PyAudio()
        self.stream = self.p.open(format=self.format,
                                  channels=self.channels,
                                  rate=self.rate,
                                  input=True,
                                  output=True,
                                  frames_per_buffer=self.chunk)

        self.t = np.linspace(0, self.chunk / self.rate,
                             self.chunk)  # dt is just 1/(sample rate)
        self.f = np.linspace(
            0, self.rate, self.chunk
        )  # We can only go up to half of the sample frequency to satisfy NYQUIST sampling condition

        # set up notch filter for middle c (261.63 hz)
        self.b_notch, self.a_notch = signal.iirnotch(261.63, 1.0, self.rate)

        nyq = self.rate / 2
        self.max_freq = 1000 / nyq
        self.min_freq = 100 / nyq
        # use fifth order butterworth band-pass filter
        self.b_band, self.a_band = signal.butter(
            5, [self.min_freq, self.max_freq], btype='band')
        self.filteredWaveform = self.win.addPlot(title="Filtered Waveform")
コード例 #20
0
ファイル: data.py プロジェクト: tom-pelsmaeker/Project-AI
 def _line_notch(self):
     """notch filter at specified frequency hz (standard = 50)"""
     fs = self.sampl_rate
     f0 = self.notch_freq / globals.FREQ_CORRECTION  # correct the frequency against scipy failure
     Q = self.quality
     w0 = f0 / (fs / 2)
     b, a = iirnotch(w0, Q)
     for j, data in enumerate(self.channels):
         for i in range(data.shape[1]):
             data[:, i] = filtfilt(b, a, data[:, i])
         self.channels[j] = data
コード例 #21
0
def notch_filter(freq=60.0, fs=250, Q=60):
    """
        Design notch filter. Outputs numerator and denominator polynomials of iir filter.
        inputs:
            freq  (float)
            order (int)
            fs    (int)
        outputs:
            (ndarray), (ndarray)
    """
    return signal.iirnotch(freq, freq / Q, fs=fs)
コード例 #22
0
 def notch_filter(self,data,f0,Q,fs):
     n, m = data.shape
     b, a = signal.iirnotch(f0*2/fs, Q)
     for i in range(m):
         filtedData = signal.lfilter(b, a, (data[:, i]))
         if i == 0:
             alldata = filtedData
         else:
             alldata = np.vstack((alldata, filtedData))
     alldata = alldata.T
     return alldata
コード例 #23
0
 def initialize_filters(self):
     #Set up the filters
     self.notch_b, self.notch_a = signal.iirnotch(self.notch_freq, self.notch_freq / 6, fs=self.sampling_freq)
     self.butter_b, self.butter_a = signal.butter(self.order, 
                                                  [self.low_pass / (self.sampling_freq / 2), self.high_pass / (self.sampling_freq / 2)], 
                                                  'bandpass')
     nz = signal.lfilter_zi(self.notch_b, self.notch_a)
     bz = signal.lfilter_zi(self.butter_b, self.butter_a)
     self.notch_z = [nz for i in range(self.num_channels)]
     self.butter_z = [bz for i in range(self.num_channels)]
     return
コード例 #24
0
def filtering(channel):
    from scipy import signal
    import numpy as np
    import matplotlib.pyplot as plt

    fs = 128.0  # Sample frequency (Hz)
    f0 = 50  # Frequency to be removed from signal (Hz)
    w0 = f0 / (fs / 2)  # Normalized Frequency
    Q = 30
    b, a = signal.iirnotch(w0, Q)
    channel = signal.filtfilt(b, a, channel)
    return (channel)
コード例 #25
0
 def NotchFilter(self, data, fc=60, fs=1024, order=5, Q=1):
     # Frequência normalizada:
     notch = []
     for i in data:
         wn = fc / (fs / 2)  # Para o filtro NOTCH 60 Hz
         b11, a11 = signal.iirnotch(wn,
                                    Q)  # Design notch filter - Fc = 60Hz
         filtradoRede = signal.filtfilt(
             b11, a11,
             i)  # Passa um filtro NOTCH no SINAL para remover 60Hz
         notch.append(filtradoRede)
     return np.array(notch)
コード例 #26
0
ファイル: digital_filters.py プロジェクト: pbmanis/pylibrary
def NotchFilter(signal, notchf=[60.], Q=90., QScale=True, samplefreq=None):
    assert samplefreq is not None
    w0 = np.array(notchf)/(float(samplefreq)/2.0)  # all W0 for the notch frequency
    if QScale:
        bw = w0[0]/Q
        Qf = (w0/bw)**np.sqrt(2)  # Bandwidth is constant, Qf varies
    else:
        Qf = Q * np.ones(len(notchf))  # all Qf are the same (so bandwidth varies)
    for i, f0 in enumerate(notchf):
        b, a = spSignal.iirnotch(w0[i], Qf[i])
        signal = spSignal.lfilter(b, a, signal, axis=-1, zi=None)
    return signal
コード例 #27
0
def bandstop_filter(data, w0, Q):
    """
    data:   (n_samples, n_channels)
    """
    b, a = iirnotch(w0, Q)
    try:
        raw_filt = np.zeros(data.shape)
        for i in range(data.shape[1]):  # iterate over number of channels
            raw_filt[:, i] = lfilter(b, a, data[:, i])
        return raw_filt
    except:  # if 1D array
        return lfilter(b, a, data)
コード例 #28
0
def filter(ephys,freq_range,filt_order = 2,ripple = 0.2,attenuation = 40,filt_type='bandpass',fs=30e3):

    ## notch filter first:

    [b,a] = signal.iirnotch(60/(fs/2),Q=30)
    ephys = signal.filtfilt(b,a,ephys,axis=0)

    # design Elliptic filter:
    [b,a] = signal.ellip(filt_order,ripple,attenuation,[x/(fs/2) for x in freq_range],btype=filt_type)

    filtered_trace = signal.filtfilt(b,a,ephys,axis=0)
    return filtered_trace
コード例 #29
0
def notch_filter(waveform, notch_freq, qual_factor=10, f_dig=1E8):
    """
    apply notch filter with some quality factor Q
    """
    nyquist = 0.5 * f_dig
    w0 = notch_freq / nyquist

    # "quality factor" which determines width of notch
    Q = qual_factor

    num, den = signal.iirnotch(w0, Q)
    return signal.lfilter(num, den, waveform)
    def applyFilterNotch50Hz(self, input_sensor_array, design_filter=False):

        if design_filter == True:
            # From: AlterEgo Paper
            #
            # A notch filter is applied at 60 Hz to
            # nullify line interference in hardware. The notch filter is
            # applied, despite the butterworth filter, because of the gentle
            # roll-off attenuation of the latter.

            fs = self._sampleRate  # Sample frequency (Hz)
            f0 = 50.0  # Frequency to be removed from signal (Hz)
            Q = 30.0  # Quality factor
            w0 = f0 / (fs / 2)  # Normalized Frequency
            # Design notch filter
            b, a = signal.iirnotch(w0, Q)

            # Frequency response
            w, h = signal.freqz(b, a)
            # Generate frequency axis
            freq = w * fs / (2 * np.pi)
            # Plot
            fig, ax = plt.subplots(2, 1, figsize=(8, 6))
            ax[0].plot(freq, 20 * np.log10(abs(h)), color='blue')
            ax[0].set_title("Frequency Response")
            ax[0].set_ylabel("Amplitude (dB)", color='blue')
            ax[0].set_xlim([0, 100])
            ax[0].set_ylim([-25, 10])
            ax[0].grid()
            ax[1].plot(freq,
                       np.unwrap(np.angle(h)) * 180 / np.pi,
                       color='green')
            ax[1].set_ylabel("Angle (degrees)", color='green')
            ax[1].set_xlabel("Frequency (Hz)")
            ax[1].set_xlim([0, 100])
            ax[1].set_yticks([-90, -60, -30, 0, 30, 60, 90])
            ax[1].set_ylim([-90, 90])
            ax[1].grid()
            plt.show()

            self._iirNotch50Hz__a = a
            self._iirNotch50Hz__b = b

        # Applies the filter to the buffer, goind forward and backwords,
        # this will remove phase changes and makes the filter more linear in phase.
        #
        # filtered_buter_array_0 = signal.filtfilt(b, a, input_sensor_array)
        filtered_buter_array = signal.filtfilt(self._iirNotch50Hz__b,
                                               self._iirNotch50Hz__a,
                                               input_sensor_array)

        return filtered_buter_array
コード例 #31
0
 def update_filter(self, init=False):
     # Ensure that the lower frequency is first
     f_crit = np.sort(
         self.f_crit) if np.ndim(self.f_crit) > 0 else self.f_crit
     # Constructing the filter
     if self.filter == 'notch':
         b, a = signal.iirnotch(w0=f_crit, Q=30, fs=self.SF)
     else:
         if self.filter_method == 'ellip':
             # Elliptic
             b, a = signal.ellip(N=5,
                                 rp=0.01,
                                 rs=100,
                                 Wn=f_crit,
                                 btype=self.filter,
                                 fs=self.SF)
         elif self.filter_method == 'cheby':
             # Chebychev
             b, a = signal.cheby1(N=5,
                                  rp=0.01,
                                  Wn=f_crit,
                                  btype=self.filter,
                                  fs=self.SF)
         else:
             # Butterworth
             b, a = signal.butter(N=5,
                                  Wn=f_crit,
                                  btype=self.filter,
                                  fs=self.SF)
     # Frequency response
     w, h = signal.freqz(b, a, whole=True, fs=self.SF)
     self.h = np.abs(np.fft.fftshift(h))
     self.w = w - self.SF // 2
     # Filtering
     self.s_filtered = signal.lfilter(b, a, self.s)
     if not init:
         self.axs[0].lines[1].set_data(self.w, self.h)
         x_lim = self.axs[0].get_xlim()
         y_lim = self.axs[0].get_ylim()
         # Clear the fill by over-filling with white
         self.axs[0].fill([-self.SF, -self.SF + 1, self.SF - 1, self.SF],
                          [-1, 2, 2, -1],
                          facecolor='white')
         # Create new fill
         if self.filter_idx % 2 == 1 or self.filter_idx == 4:
             self.axs[0].fill(self.w,
                              np.concatenate([[0], self.h[1:-1], [0]]),
                              facecolor=self.fill_color)
         else:
             self.axs[0].fill(self.w, self.h, facecolor=self.fill_color)
         self.axs[0].set_xlim(x_lim)
         self.axs[0].set_ylim(y_lim)
def notch_filtering(wav, fs, w0, Q):#陷波滤波器
    """ Apply a notch (band-stop) filter to the audio signal.
    Args:
        wav: Waveform.
        fs: Sampling frequency of the waveform.
        w0: See scipy.signal.iirnotch.
        Q: See scipy.signal.iirnotch.
    Returns:
        wav: Filtered waveform.
    """
    b, a = iirnotch(2 * w0/fs, Q)
    wav = lfilter(b, a, wav)
    return wav
コード例 #33
0
ファイル: gtec2wav.py プロジェクト: neuroidss/eegsynth
for ch in range(channels):
    data = Samples[:, ch]
    t = np.arange(0, len(data))
    p = np.polynomial.polynomial.polyfit(t, data, 3)
    data = data - np.polynomial.polynomial.polyval(t, p)
    Samples[:, ch] = data

sig = Samples.T
b, a = signal.butter(4, 45 / fsample, 'low', analog=True)
sig = signal.filtfilt(b, a, sig, axis=1)
b, a = signal.butter(4, 2 / fsample, 'high', analog=True)
sig = signal.filtfilt(b, a, sig, axis=1)
Q = 30.0  # Quality factor
w0 = 50/(fsample/2)  # Normalized Frequency
b, a = signal.iirnotch(w0, Q)
sig = signal.filtfilt(b, a, sig)
Samples = sig.T

# plt.figure()
# # plt.plot(Samples)
# plt.plot(Samples[int(time_point*fsample):int((time_point+22)*fsample), :])
# plt.legend(layout.label.tolist())
# plt.show()


f_min = 1
f_max = 45

chan_tmp = []
scaling = 0.1
コード例 #34
0
    #extracting sampling rate from parameter file
    parafile = name + '-parameters.txt'
    params = pd.read_csv(parafile, delim_whitespace=True, engine='python', names=['0','1','2','3'], index_col=0)
    samplerate = params['2']['Samplerate']
    Samplingrates = {"2.5Hz":2.5, "5Hz":5.0, "10Hz":10.0, "15Hz":15.0,
                         "25Hz":25.0, "30Hz":30.0, "50Hz":50.0, "60Hz":60.0,
                         "100Hz":100.0, "500Hz":500.0, "1KHz":1000.0, "2KHz":2000.0,
                         "3.75KHz":3750.0, "7.5KHz":7500.0, "15KHz":1500.0, "30KHz":30000.0}
    samplerate = Samplingrates[samplerate]

    #constructing IIR notch filters
    fs = samplerate   # Sample frequency (Hz)
    f0 = 60.0  # Frequency to be removed from signal (Hz)
    Q = 2.0  # Quality factor
    # Design notch filter
    b, a = signal.iirnotch(f0, Q, fs)
    c, d = signal.iirnotch(f0*2, Q, fs)
    e, f = signal.iirnotch(f0*4, Q, fs)
    g, h = signal.iirnotch(f0*5, Q, fs)
    i, j = signal.iirnotch(f0*6, Q, fs)
    
    #apply filters
    yf1 = signal.filtfilt(b,a,dat.current) #60Hz filter
    yf2 = signal.filtfilt(c,d,yf1) #120Hz filter
    yf3 = signal.filtfilt(e,f,yf2) #240Hz filter
    yf4 = signal.filtfilt(g,h,yf3) #300Hz filter
    yf5 = signal.filtfilt(i,j,yf4) #360Hz filter

    #generate output plots
    fig = plt.figure(figsize=(6,4))
    plt.plot(dat.potential, yf5*-1000000000,'b')