def algorithm(cls, signal, params): fsamp = signal.get_sampling_freq() fp, fs, loss, att, ftype = params["fp"], params["fs"], params[ "loss"], params["att"], params["ftype"] if isinstance(signal, _UnevenlySignal): cls.warn( 'Filtering Unevenly signal is undefined. Returning original signal.' ) return signal nyq = 0.5 * fsamp fp = _np.array(fp) fs = _np.array(fs) wp = fp / nyq ws = fs / nyq # noinspection PyTupleAssignmentBalance b, a = _filter_design.iirdesign(wp, ws, loss, att, ftype=ftype, output="ba") sig_filtered = signal.clone_properties( _filtfilt(b, a, signal.get_values())) if _np.isnan(sig_filtered[0]): cls.warn( 'Filter parameters allow no solution. Returning original signal.' ) return signal else: return sig_filtered
def __init__(self): print "New classifier" self.dataIndex = 0 #APPLY IIR FILTER TO GET THE GRAVITY COMPONENTS #IIR filter parameters (all frequencies are in Hz) Fs = 32 # sampling frequency Fpass = 0.25 # passband frequency Fstop = 2 # stopband frequency Apass = 0.001 # passband ripple (dB) Astop = 100 # stopband attenuation (dB) match = 'pass' # band to match exactly #Create the IIR filter # iirdesign agruements Wip = (Fpass) / (Fs / 2) Wis = (Fstop + 1e6) / (Fs / 2) Rp = Apass # passband ripple As = Astop # stopband attenuation # The iirdesign takes passband, stopband, passband ripple, # and stop attenuation. self.bb, self.ab = ifd.iirdesign(Wip, Wis, Rp, As, ftype='cheby1')
def generate_filters_params(): import pickle params = {} # generate the low-pass filter for decimation Ndec = 3 fc = 0.5 # other possibilities #(bdec, adec) = ellip(Ndec, 0.05, 30, fc) #print bdec #(bdec, adec) = cheby1(Ndec, 0.05, fc) #(bdec, adec) = butter(Ndec, fc) (bdec, adec) = iirdesign(0.48, 0.50, 0.05, 70, analog=0, ftype='ellip', output='ba') #bdec = firwin(30, fc) #adec = [1.] params['dec'] = [bdec, adec] #generate the octave filters for BandsPerOctave in [1,3,6,12,24]:#,48,96]: Nbands = NOCTAVE*BandsPerOctave [boct, aoct, fi, flow, fhigh] = octave_filters_oneoctave(Nbands, BandsPerOctave) params['%d' %BandsPerOctave] = [boct, aoct, fi, flow, fhigh] #generate the filters for non-decimating filters for BandsPerOctave in [1,3,6,12,24,48,96]: Nbands = NOCTAVE*BandsPerOctave octave_filters(Nbands, BandsPerOctave) [b, a, fi, flow, fhigh] = octave_filters(Nbands, BandsPerOctave) params['nodec %d' %BandsPerOctave] = [b, a, fi, flow, fhigh] with open('generated_filters.pkl', 'wb') as output: # Pickle dictionary using protocol 0. pickle.dump(params, output)
def filtfiltFilter (SIGNAL, F_PASS, F_STOP, F_SAMP, LOSS, ATTENUATION, ftype = 'butter'): ''' Applies the selected filter to a signal (all the types has the same parameter) return: the signal filtered SIGNAL: the signal to filter F_PASS: pass frequency, last frequency kept F_STOP: stop frequency, first frequency removed F_SAMP: smp_fr (sampling frequency) LOSS: index of the max variation of the kept frequency (in [0,1]) ATTENUATION: index of the max variation of the removed frequency from 0 (higher ATTENUATION implies lower variation) ftype: (default 'butter') is the type of filter. Should be "butter", "cheby1", "cheby2", "ellip" notes: F_PASS, F_STOP < smp_fr / 2 F_PASS < F_STOP for a lowpass filter F_PASS > F_STOP for a highpass filter ''' nyq = 0.5 * F_SAMP wp = np.array(F_PASS)/nyq ws = np.array(F_STOP)/nyq b, a = filter_design.iirdesign(wp, ws, LOSS, ATTENUATION, ftype = ftype) plot = False if plot: mfreqz(b,a, wp, ws) for idx in xrange(SIGNAL.shape[1]): filtered_signal = filtfilt(b, a, SIGNAL[:,idx]) return filtered_signal
def filtfiltFilter(SIGNAL, F_PASS, F_STOP, F_SAMP, LOSS, ATTENUATION, ftype='butter'): ''' Applies the selected filter to a signal (all the types has the same parameter) return: the signal filtered SIGNAL: the signal to filter F_PASS: pass frequency, last frequency kept F_STOP: stop frequency, first frequency removed F_SAMP: smp_fr (sampling frequency) LOSS: index of the max variation of the kept frequency (in [0,1]) ATTENUATION: index of the max variation of the removed frequency from 0 (higher ATTENUATION implies lower variation) ftype: (default 'butter') is the type of filter. Should be "butter", "cheby1", "cheby2", "ellip" notes: F_PASS, F_STOP < smp_fr / 2 F_PASS < F_STOP for a lowpass filter F_PASS > F_STOP for a highpass filter ''' nyq = 0.5 * F_SAMP wp = np.array(F_PASS) / nyq ws = np.array(F_STOP) / nyq b, a = filter_design.iirdesign(wp, ws, LOSS, ATTENUATION, ftype=ftype) plot = False if plot: mfreqz(b, a, wp, ws) for idx in xrange(SIGNAL.shape[1]): filtered_signal = filtfilt(b, a, SIGNAL[:, idx]) return filtered_signal
def __init__(self, bpass, bstop, ftype='butter'): self.b, self.a = fd.iirdesign(bpass, bstop, 1, 100, ftype=ftype, output='ba') self.ic = st.lfiltic(self.b, self.a, (0.0, ))
def envelope(x, fs, hp=100, axis=-1): Wp = 2 * float(hp) / fs Ws = 3 * float(hp) / fs Rp = 1 As = 50 b, a = fd.iirdesign(Wp, Ws, Rp, As, ftype='ellip') env = sp.signal.filtfilt(b, a, np.abs(x), axis=axis) return env
def GetComponents(self, x_axis, y_axis, z_axis): """ GetComponents discriminates between gravity and body acceleration by applying an infinite impulse response (IIR) filter to the raw acceleration data (one trial) given in input. :param x_axis: acceleration data in the axis x :param y_axis: acceleration data in the axis y :param z_axis: acceleration data in the axis z :return gravity: gravity component of the acceleration data :return body: body component of the acceleration data """ #APPLY IIR FILTER TO GET THE GRAVITY COMPONENTS #IIR filter parameters (all frequencies are in Hz) Fs = 32; # sampling frequency Fpass = 0.25; # passband frequency Fstop = 2; # stopband frequency Apass = 0.001; # passband ripple (dB) Astop = 100; # stopband attenuation (dB) match = 'pass'; # band to match exactly delay = 64; # delay (# samples) introduced by filtering #Create the IIR filter # iirdesign agruements Wip = (Fpass)/(Fs/2) Wis = (Fstop+1e6)/(Fs/2) Rp = Apass # passband ripple As = Astop # stopband attenuation # The iirdesign takes passband, stopband, passband ripple, # and stop attenuation. bb, ab = ifd.iirdesign(Wip, Wis, Rp, As, ftype='cheby1') g1 = lfilter(bb,ab,x_axis) g2 = lfilter(bb,ab,y_axis) g3 = lfilter(bb,ab,z_axis) #COMPUTE THE BODY-ACCELERATION COMPONENTS BY SUBTRACTION (PREGUNTA) gravity = zeros((self.numSamples -delay,3)); body = zeros((self.numSamples -delay,3)); i = 0 while(i < self.numSamples-delay): #shift & reshape gravity to reduce the delaying effect of filtering gravity[i,0] = g1[i+delay]; gravity[i,1] = g2[i+delay]; gravity[i,2] = g3[i+delay]; body[i,0] = x_axis[i] - gravity[i,0]; body[i,1] = y_axis[i] - gravity[i,1]; body[i,2] = z_axis[i] - gravity[i,2]; i = i + 1 #COMPUTE THE BODY-ACCELERATION COMPONENTS BY SUBTRACTION return gravity, body
def analyzeActualWindow(self,window,numSamples): """ function [gravity body] = AnalyzeActualWindow(window,numSamples) % % AnalyzeActualWindow separates the gravity and body acceleration features % contained in the window of real-time acceleration data, by first reducing % the noise on the raw data with a median filter and then discriminating % between the features with a low-pass IIR filter.""" #REDUCE THE NOISE ON THE SIGNALS BY MEDIAN FILTERING n = 3 #order of the median filter x_axis = medfilt(window[:,0],n) y_axis = medfilt(window[:,1],n) z_axis = medfilt(window[:,2],n) #APPLY IIR FILTER TO GET THE GRAVITY COMPONENTS #IIR filter parameters (all frequencies are in Hz) Fs = 32; # sampling frequency Fpass = 0.25; # passband frequency Fstop = 2; # stopband frequency Apass = 0.001; # passband ripple (dB) Astop = 100; # stopband attenuation (dB) match = 'pass'; # band to match exactly #Create the IIR filter # iirdesign agruements Wip = (Fpass)/(Fs/2) Wis = (Fstop+1e6)/(Fs/2) Rp = Apass # passband ripple As = Astop # stopband attenuation # The iirdesign takes passband, stopband, passband ripple, # and stop attenuation. bb, ab = ifd.iirdesign(Wip, Wis, Rp, As, ftype='cheby1') #Gravity components g1 = lfilter(bb,ab,x_axis) g2 = lfilter(bb,ab,y_axis) g3 = lfilter(bb,ab,z_axis) #COMPUTE THE BODY-ACCELERATION COMPONENTS BY SUBTRACTION (PREGUNTA) gravity = zeros((numSamples,3)); body = zeros((numSamples,3)); i=0 while(i < numSamples): gravity[i,0] = g1[i]; gravity[i,1] = g2[i]; gravity[i,2] = g3[i]; body[i,0] = x_axis[i] - g1[i]; body[i,1] = y_axis[i] - g2[i]; body[i,2] = z_axis[i] - g3[i]; i = i + 1 #COMPUTE THE BODY-ACCELERATION COMPONENTS BY SUBTRACTION return gravity, body
def __init__(self, bpass, bstop, ftype='butter'): import scipy.signal.filter_design as fd import scipy.signal.signaltools as st self.b, self.a = fd.iirdesign(bpass, bstop, 1, 100, ftype=ftype, output='ba') self.ic = st.lfiltic(self.b, self.a, (0.0, ))
def generate_filters_params(): import os import json params = {} # generate the low-pass filter for decimation Ndec = 3 fc = 0.5 # other possibilities # (bdec, adec) = ellip(Ndec, 0.05, 30, fc) # print(bdec) # (bdec, adec) = cheby1(Ndec, 0.05, fc) # (bdec, adec) = butter(Ndec, fc) (bdec, adec) = iirdesign(0.48, 0.50, 0.05, 70, analog=0, ftype='ellip', output='ba') # bdec = firwin(30, fc) # adec = [1.] # set_printoptions(precision=24) params['dec'] = [bdec.tolist(), adec.tolist()] # generate the octave filters for bands_per_octave in [1, 3, 6, 12, 24]: total_band_count = NOCTAVE * bands_per_octave [boct, aoct, fi, flow, fhigh] = octave_filters_oneoctave(total_band_count, bands_per_octave) params['%d' % bands_per_octave] = [ boct, aoct, fi.tolist(), flow.tolist(), fhigh.tolist() ] out = """\ # Filters parameters generated from filter_design.py import json JSON_PARAMS = \"\"\" %s \"\"\" PARAMS = json.loads(JSON_PARAMS) """ % json.dumps(params, indent=4, sort_keys=True) # repr(params) path = os.path.dirname(__file__) fname = os.path.join(path, 'generated_filters.py') with open(fname, 'w') as output: output.write(out)
def cheby2_low_pass_coefficients(cut_off, rate, ripple=0.5, attenuation=60): """ Generate low pass filter coefficients. :param rate: sampling rate of speech waveform(Hz). :param cut_off: cut off frequency (Hz) :param ripple: pass band maximum loss :param attenuation: stop band min attenuation :return: a tuple of ba coefficients of low pass filter. """ nyq = 0.5 * rate # Nyquist frequency, half of sampling frequency(Hz). normal_cut_off = round(cut_off / nyq, 3) wp = normal_cut_off - 0.01 # end of pass band, normalized frequency ws = normal_cut_off + 0.01 # start of the stop band, normalized frequency b, a = fd.iirdesign(wp, ws, ripple, attenuation, ftype='cheby2') return b, a
def generate_filters_params(): import os params = {} # generate the low-pass filter for decimation Ndec = 3 fc = 0.5 # other possibilities #(bdec, adec) = ellip(Ndec, 0.05, 30, fc) #print bdec #(bdec, adec) = cheby1(Ndec, 0.05, fc) #(bdec, adec) = butter(Ndec, fc) (bdec, adec) = iirdesign(0.48, 0.50, 0.05, 70, analog=0, ftype='ellip', output='ba') #bdec = firwin(30, fc) #adec = [1.] set_printoptions(precision=24) params['dec'] = [bdec, adec] #generate the octave filters for BandsPerOctave in [1, 3, 6, 12, 24]: Nbands = NOCTAVE * BandsPerOctave [boct, aoct, fi, flow, fhigh] = octave_filters_oneoctave(Nbands, BandsPerOctave) params['%d' % BandsPerOctave] = [boct, aoct, fi, flow, fhigh] out = """\ # Filters parameters generated from filter_design.py from numpy import array params = %s """ % repr(params) path = os.path.dirname(__file__) fname = os.path.join(path, 'generated_filters.py') output = open(fname, 'w') output.write(out) output.close()
def main(): N = 2048 * 2 * 2 * 2 * 2 * 2 fs = 44100. Nchannels = 20 low_freq = 20. impulse = zeros(N) impulse[N / 2] = 1 f = 1000. #impulse = sin(2*pi*f*arange(0, N/fs, 1./fs)) #[ERBforward, ERBfeedback] = MakeERBFilters(fs, Nchannels, low_freq) #y = ERBFilterBank(ERBforward, ERBfeedback, impulse) BandsPerOctave = 6 Nbands = NOCTAVE * BandsPerOctave [B, A, fi, fl, fh] = octave_filters(Nbands, BandsPerOctave) y2, zfs2 = octave_filter_bank(B, A, impulse, None, default_filt) #octave_filter_bank_decimation(blow, alow, forward, feedback, x, zis, filter_func) (bdec, adec) = iirdesign(0.48, 0.50, 0.05, 70, analog=0, ftype='ellip', output='ba') print(len(bdec), len(adec)) for i in range(0, len(B)): B[i], A[i] = prepare_coefficients(B[i], A[i]) #y, zfs = octave_filter_bank(B, A, impulse, None, double_filt) y, zfs = octave_filter_bank(B, A, impulse, None, pyx_double_filt) if False: from matplotlib.pyplot import semilogx, plot, show, xlim, ylim, figure, legend, subplot, bar figure() for i in range(0, len(y)): plot(y[i]) plot(y2[i]) show()
def generate_filters_params(): import os import json params = {} # generate the low-pass filter for decimation Ndec = 3 fc = 0.5 # other possibilities # (bdec, adec) = ellip(Ndec, 0.05, 30, fc) # print(bdec) # (bdec, adec) = cheby1(Ndec, 0.05, fc) # (bdec, adec) = butter(Ndec, fc) (bdec, adec) = iirdesign(0.48, 0.50, 0.05, 70, analog=0, ftype='ellip', output='ba') # bdec = firwin(30, fc) # adec = [1.] # set_printoptions(precision=24) params['dec'] = [bdec.tolist(), adec.tolist()] # generate the octave filters for bands_per_octave in [1, 3, 6, 12, 24]: total_band_count = NOCTAVE * bands_per_octave [boct, aoct, fi, flow, fhigh] = octave_filters_oneoctave(total_band_count, bands_per_octave) params['%d' % bands_per_octave] = [boct, aoct, fi.tolist(), flow.tolist(), fhigh.tolist()] out = """\ # Filters parameters generated from filter_design.py import json JSON_PARAMS = \"\"\" %s \"\"\" PARAMS = json.loads(JSON_PARAMS) """ % json.dumps(params, indent=4, sort_keys=True) # repr(params) path = os.path.dirname(__file__) fname = os.path.join(path, 'generated_filters.py') output = open(fname, 'w') with open(fname, 'w') as output: output.write(out)
def getHPF(n, datas, ftype='cheby2'): # iir filter parameter Wp = 0.1 Ws = 0.01 Rp = 1 As = 3 # filters ellip cheby2 cheby1 butter bessel b, a = fd.iirdesign(Wp, Ws, Rp, As, ftype=ftype) r = [] for i in range(0, n): t = signal.filtfilt(b, a, datas[i]) r.append(t.tolist()) # fir filter parameter # f = 0.2 # cutoff = f * nyq # for i in range(0, n): # b = signal.firwin(3, f, pass_zero=False, window='hamming') # b = signal.firwin(7, f, pass_zero=False, window='blackman') # b = signal.firwin(9, f, pass_zero=False, window='hann') # t = signal.filtfilt(b, [1], datas[i]) # r.append(t.tolist()) return r
def main(): N = 2048*2*2*2*2*2 fs = 44100. Nchannels = 20 low_freq = 20. impulse = zeros(N) impulse[N/2] = 1 f = 1000. #impulse = sin(2*pi*f*arange(0, N/fs, 1./fs)) #[ERBforward, ERBfeedback] = MakeERBFilters(fs, Nchannels, low_freq) #y = ERBFilterBank(ERBforward, ERBfeedback, impulse) BandsPerOctave = 6 Nbands = NOCTAVE*BandsPerOctave [B, A, fi, fl, fh] = octave_filters(Nbands, BandsPerOctave) y2, zfs2 = octave_filter_bank(B, A, impulse, None, default_filt) #octave_filter_bank_decimation(blow, alow, forward, feedback, x, zis, filter_func) (bdec, adec) = iirdesign(0.48, 0.50, 0.05, 70, analog=0, ftype='ellip', output='ba') print(len(bdec), len(adec)) for i in range(0, len(B)): B[i], A[i] = prepare_coefficients(B[i], A[i]) #y, zfs = octave_filter_bank(B, A, impulse, None, double_filt) y, zfs = octave_filter_bank(B, A, impulse, None, pyx_double_filt) if False: from matplotlib.pyplot import semilogx, plot, show, xlim, ylim, figure, legend, subplot, bar figure() for i in range(0, len(y)): plot(y[i]) plot(y2[i]) show()
def generate_filters_params(): import os params = {} # generate the low-pass filter for decimation Ndec = 3 fc = 0.5 # other possibilities #(bdec, adec) = ellip(Ndec, 0.05, 30, fc) #print bdec #(bdec, adec) = cheby1(Ndec, 0.05, fc) #(bdec, adec) = butter(Ndec, fc) (bdec, adec) = iirdesign(0.48, 0.50, 0.05, 70, analog=0, ftype='ellip', output='ba') #bdec = firwin(30, fc) #adec = [1.] set_printoptions(precision=24) params['dec'] = [bdec, adec] #generate the octave filters for BandsPerOctave in [1,3,6,12,24]: Nbands = NOCTAVE*BandsPerOctave [boct, aoct, fi, flow, fhigh] = octave_filters_oneoctave(Nbands, BandsPerOctave) params['%d' %BandsPerOctave] = [boct, aoct, fi, flow, fhigh] out = """\ # Filters parameters generated from filter_design.py from numpy import array params = %s """ %repr(params) path = os.path.dirname(__file__) fname = os.path.join(path, 'generated_filters.py') output = open(fname,'w') output.write(out) output.close()
def generate_filters_params(): import pickle params = {} # generate the low-pass filter for decimation Ndec = 3 fc = 0.5 # other possibilities #(bdec, adec) = ellip(Ndec, 0.05, 30, fc) #print bdec #(bdec, adec) = cheby1(Ndec, 0.05, fc) #(bdec, adec) = butter(Ndec, fc) (bdec, adec) = iirdesign(0.48, 0.50, 0.05, 70, analog=0, ftype='ellip', output='ba') #bdec = firwin(30, fc) #adec = [1.] params['dec'] = [bdec, adec] #generate the octave filters for BandsPerOctave in [1,3,6,12,24]:#,48,96]: Nbands = NOCTAVE*BandsPerOctave [boct, aoct, fi, flow, fhigh] = octave_filters_oneoctave(Nbands, BandsPerOctave) params['%d' %BandsPerOctave] = [boct, aoct, fi, flow, fhigh] #generate the filters for non-decimating filters for BandsPerOctave in [1,3,6,12,24,48,96]: Nbands = NOCTAVE*BandsPerOctave octave_filters(Nbands, BandsPerOctave) [b, a, fi, flow, fhigh] = octave_filters(Nbands, BandsPerOctave) params['nodec %d' %BandsPerOctave] = [b, a, fi, flow, fhigh] output = open('generated_filters.pkl', 'wb') # Pickle dictionary using protocol 0. pickle.dump(params, output) # Pickle the list using the highest protocol available. #pickle.dump(selfref_list, output, -1) output.close()
def filter2(band_start,band_end,y): # setup some of the required parameters Fs = 256 # sample-rate defined in the question, down-sampled # remez (fir) design arguements Fpass1 = band_end # passband edge Fstop1 = band_end + 1. # stopband edge Fpass2 = band_start Fstop2 = band_start -1. # Wp = Fpass/(Fs) # pass normalized frequency # Ws = Fstop/(Fs) # stop normalized frequency # iirdesign agruements Wip = [(Fpass2)/(Fs/2),(Fpass1)/(Fs/2)] #[8./(128),14./(128)] Wis = [(Fstop2)/(Fs/2),(Fstop2)/(Fs/2)] #[7./128,15./128] Rp = 1 # passband ripple As = 42 # stopband attenuation # The iirdesign takes passband, stopband, passband ripple, # and stop attenuation. bc, ac = ifd.iirdesign(Wip, Wis, Rp, As, ftype='ellip') # bb, ab = ifd.iirdesign(Wip, Wis, Rp, As, ftype='cheby2') return lfilter(bc,ac,y)
def algorithm(cls, signal, params): fsamp = signal.get_sampling_freq() fp, fs, loss, att, ftype = params["fp"], params["fs"], params["loss"], params["att"], params["ftype"] if isinstance(signal, _UnevenlySignal): cls.warn('Filtering Unevenly signal is undefined. Returning original signal.') return signal nyq = 0.5 * fsamp fp = _np.array(fp) fs = _np.array(fs) wp = fp / nyq ws = fs / nyq # noinspection PyTupleAssignmentBalance b, a = _filter_design.iirdesign(wp, ws, loss, att, ftype=ftype, output="ba") sig_filtered = signal.clone_properties(_filtfilt(b, a, signal.get_values())) if _np.isnan(sig_filtered[0]): cls.warn('Filter parameters allow no solution. Returning original signal.') return signal else: return sig_filtered
def __init__(self, bpass, bstop, ftype='butter'): import scipy.signal.filter_design as fd import scipy.signal.signaltools as st self.b, self.a = fd.iirdesign(bpass, bstop, 1, 100, ftype=ftype, output='ba') self.ic = st.lfiltic(self.b, self.a, (0.0,))
#signal y = np.sin(2 * np.pi * x * f) #window window = np.hanning(N) # windowed signal #y *= window w1 = 0.49 w2 = 0.51 gpass = 0.05 gstop = 70. #(b_full, a_full) = iirdesign(0.49, 0.51, 0.05, 70, analog=0, ftype='ellip', output='ba') (b, a) = iirdesign(w1, w2, gpass, gstop, analog=0, ftype='ellip', output='ba') #Nfilt = 13 #w = 0.5 #pbrip = 0.05 #sbatt = 70. #(b_full, a_full) = iirfilter(Nfilt, w, pbrip, sbatt, analog=0, btype='lowpass', ftype='ellip', output='ba') #print "IIR coeff created", len(b_full), len(a_full) #print "b", b_full #print "a", a_full z = np.zeros(b.shape[0] - 1) impulse = np.zeros(N) impulse[N / 2] = 1.
def main(): from matplotlib.pyplot import semilogx, plot, show, xlim, ylim, figure, legend, subplot, bar from numpy.fft import fft, fftfreq, fftshift, ifft from numpy import log10, linspace, interp, angle, array, concatenate, hamming N = 2**12 fs = 44100. Nchannels = 20 low_freq = 20. #impulse = zeros(N) #impulse[N/2] = 1 f = 70. impulse = sin(2*pi*f*arange(0, N/fs, 1./fs))*hamming(N) #[ERBforward, ERBfeedback] = MakeERBFilters(fs, Nchannels, low_freq) #y = ERBFilterBank(ERBforward, ERBfeedback, impulse) BandsPerOctave = 24 Nbands = NOCTAVE*BandsPerOctave [B, A, fi, fl, fh] = octave_filters(Nbands, BandsPerOctave) y, zfs = octave_filter_bank(B, A, impulse) print "Filter lengths without decimation" for b, a in zip(B, A): print len(b), len(a) response = 20.*log10(abs(fft(y))) freqScale = fftfreq(N, 1./fs) figure() subplot(211) for i in range(0, response.shape[0]): semilogx(freqScale[0:N/2],response[i, 0:N/2]) xlim(fs/2000, fs) ylim(-70, 10) subplot(212) m = 0 for f in fi: p = 10.*log10((y[m]**2).mean()) m += 1 semilogx(f, p, 'ko') Ndec = 3 fc = 0.5 # other possibilities #(bdec, adec) = ellip(Ndec, 0.05, 30, fc) #print bdec #(bdec, adec) = cheby1(Ndec, 0.05, fc) #(bdec, adec) = butter(Ndec, fc) (bdec, adec) = iirdesign(0.48, 0.50, 0.05, 70, analog=0, ftype='ellip', output='ba') #bdec = firwin(30, fc) #adec = [1.] figure() subplot(211) response = 20.*log10(abs(fft(impulse))) plot(fftshift(freqScale), fftshift(response), label="impulse") y = lfilter(bdec, adec, impulse) response = 20.*log10(abs(fft(y))) plot(fftshift(freqScale), fftshift(response), label="lowpass") ydec = y[::2].repeat(2) response = 20.*log10(abs(fft(ydec))) plot(fftshift(freqScale), fftshift(response), label="lowpass + dec2 + repeat2") ydec2 = interp(range(0, len(y)), range(0, len(y), 2), y[::2]) response = 20.*log10(abs(fft(ydec2))) plot(fftshift(freqScale), fftshift(response), label="lowpass + dec2 + interp2") ydec3 = y[::2] response = 20.*log10(abs(fft(ydec3))) freqScale2 = fftfreq(N/2, 2./fs) plot(fftshift(freqScale2),fftshift(response), label="lowpass + dec2") legend(loc="lower left") subplot(212) plot(range(0, len(impulse)), impulse, label="impulse") plot(range(0, len(impulse)), y, label="lowpass") plot(range(0, len(impulse)), ydec, label="lowpass + dec2 + repeat2") plot(range(0, len(impulse)), ydec2, label="lowpass + dec2 + interp2") plot(range(0, len(impulse), 2), ydec3, label="lowpass + dec2") legend() [boct, aoct, fi, flow, fhigh] = octave_filters_oneoctave(Nbands, BandsPerOctave) y, dec, zfs = octave_filter_bank_decimation(bdec, adec, boct, aoct, impulse) print "Filter lengths with decimation" print len(bdec), len(adec) for b, a in zip(boct, aoct): print len(b), len(a) figure() subplot(211) for yone, d in zip(y, dec): response = 20.*log10(abs(fft(yone))*d) freqScale = fftfreq(N/d, 1./(fs/d)) semilogx(freqScale[0:N/(2*d)],response[0:N/(2*d)]) xlim(fs/2000, fs) ylim(-70, 10) subplot(212) m = 0 for i in range(0, NOCTAVE): for f in fi: p = 10.*log10((y[m]**2).mean()) semilogx(f/dec[m], p, 'ko') m += 1 [B, A, fi, fl, fh] = octave_filters(Nbands, BandsPerOctave) y1, zfs = octave_filter_bank(B, A, impulse[0:N/2]) y2, zfs = octave_filter_bank(B, A, impulse[N/2:], zis=zfs) #[boct, aoct, fi, flow, fhigh] = octave_filters_oneoctave(Nbands, BandsPerOctave) #y1, dec, zfs = octave_filter_bank(bdec, adec, boct, aoct, impulse[0:N/2]) #y2, dec, zfs = octave_filter_bank(bdec, adec, boct, aoct, impulse) y = [] for y1one, y2one in zip(y1,y2): y += [concatenate((y1one,y2one))] figure() plot(impulse[0:N/2]) #for y0 in y1: #plot(y0) plot(y1[-1]) figure() subplot(211) for yone in y: response = 20.*log10(abs(fft(yone))) freqScale = fftfreq(N, 1./fs) semilogx(freqScale[0:N/2],response[0:N/2]) xlim(fs/2000, fs) ylim(-70, 10) subplot(212) m = 0 for f in fi: p = 10.*log10((y[m]**2).mean()) semilogx(f, p, 'ko') m += 1 generate_filters_params() show()
#signal y = np.sin(2*np.pi*x*f) #window window = np.hanning(N) # windowed signal #y *= window w1 = 0.49 w2 = 0.51 gpass = 0.05 gstop = 70. #(b_full, a_full) = iirdesign(0.49, 0.51, 0.05, 70, analog=0, ftype='ellip', output='ba') (b, a) = iirdesign(w1, w2, gpass, gstop, analog=0, ftype='ellip', output='ba') #Nfilt = 13 #w = 0.5 #pbrip = 0.05 #sbatt = 70. #(b_full, a_full) = iirfilter(Nfilt, w, pbrip, sbatt, analog=0, btype='lowpass', ftype='ellip', output='ba') #print "IIR coeff created", len(b_full), len(a_full) #print "b", b_full #print "a", a_full z = np.zeros(b.shape[0]-1) impulse = np.zeros(N); impulse[N/2] = 1. t0 = time.time()
def high_pass(series,cutoff=100,delta=1,plot=False,filt_type='ellip',variable='signal',color='blue'): """ Purpose: High-pass filter a single array series using fourrier transforms. Inputs: {series} -an array of observations to filter (i.e) lots of angle measurements {cutoff} -(optional) *if 'brick' Specify cutoff frequency [HZ] *if 'ellip' Specify fraction of frequency spectrum to lose. (cutoff > 1.1) {delta} -(optional) time between observations [s] {plot} -(optional) Plot the results of this op in an awesome way {filt_type} -(optional) Specify filter type. Either: * 'ellip' - try a scipy elliptical filter * 'brick' - try a simple brick wall filter Outputs:{new_series} -the new series, with low frequency changes filtered out **NOTE** "CUTOFF" KEYWORD MUST BE GREATER THAN 1 FOR ELLIPTICAL FILTER. It is an inverse ratio of the full spectrum that we wish to cut off. So a '4' will cutoff (1/4) of the frequency spectrum. """ # power = power_spectrum(series,sampling_frequency=sampling_frequency) ## Convert to Frequency Domain #--------------------------------------------------------- series = np.array(series) # Convert to Array ns =len(series) # number of samples cutoff_freq=cutoff*(ns*delta) # Index of cutoff frequency in this new awesome frequency domain #--------------------------------------------------------- ## Construct Frequency Filter #--------------------------------------------------------- Nyquist_freq = 1/delta/2 # Nyquist frequency. Highest freq we can detect Wp = cutoff/Nyquist_freq # Proportion of Full spectrum to filter if Wp > 1: print "Hey douche, your cutoff frequency is higher than your Nyquist frequency." print "You can't filter this way" # Wp = cutoff_freq/(ns/math.pi) #(ns*delta)/cutoff_freq # Cutoff frequency, normalized to 1 Ws = Wp-0.1*Wp # Stop frequency Rp = 0.01 # passband maximum loss (gpass) As = 90 # stoppand min attenuation (gstop) if filt_type.lower() == 'ellip': try: # Must 'try' this because wrong cutoff can spawn an error really easily b,a = fd.iirdesign(Wp, Ws, Rp, As, ftype='ellip') new_series = signal.lfilter(b,a,series) except: print "Something went wrong with the Fourier Filter, possibly the cutoff frequency wrong" print "Cutoff freq is : %s" % cutoff_freq print "Just doing a dumb brick wall filter" # cutoff_freq=(ns/cutoff*delta) fft_series = np.fft.rfft(series) fft_filt = np.array(fft_series.copy()) for ii in range(0, len(fft_filt)): if ii == cutoff_freq: fft_filt[ii] = 0.5 if ii <cutoff_freq: fft_filt[ii] = 0.0 # Inverse fourrier. Get new filtered signal back new_series = np.array(np.fft.irfft(fft_filt)) # fft_filt[len(fft_filt) - ii -1] = 0.0 elif filt_type.lower() == 'brick': fft_series = np.fft.rfft(series) fft_filt = np.array(fft_series.copy()) for ii in range(0, len(fft_filt)): if ii == cutoff_freq: fft_filt[ii] = 0.5 if ii <cutoff_freq: fft_filt[ii] = 0.0 # Inverse fourrier. Get new filtered signal back new_series = np.array(np.fft.irfft(fft_filt)) else: fft_series = np.fft.rfft(series) fft_filt = np.array(fft_series.copy()) for ii in range(0, len(fft_filt)): if ii == cutoff_freq: fft_filt[ii] = 0.5 if ii <cutoff_freq: fft_filt[ii] = 0.0 # Inverse fourrier. Get new filtered signal back new_series = np.array(np.fft.irfft(fft_filt)) # Try a linear regression. See which is better (ar,br)=polyfit(np.arange(0,len(series)),series,1) lin_series=polyval([ar,br],np.arange(0,len(series))) - series res_filt = np.std(new_series) res_lin = np.std(lin_series) if res_filt > res_lin: if variable != 'signal': print variable print "Frequency filter is way worse than a simple linear one" print "Freq filter gives resulting std of : %s " % res_filt print "Linear regression gives resulting std of : %s " % res_lin new_series = lin_series if plot: pylab.figure(num=None, figsize=(13, 7), dpi=80, facecolor='w', edgecolor='k') # Signal pylab.subplot(2,2,1) pylab.plot(np.arange(0,len(series)*delta,delta)[0:len(series)],series*180/math.pi*3600,color=color) # pylab.plot(series*180/math.pi*3600) pylab.xlabel('Time') pylab.ylabel(variable + " [arcseconds]") pylab.subplot(2,2,3) # pylab.plot(new_series*180/math.pi*3600) pylab.plot(np.arange(0,len(new_series)*delta,delta)[0:len(new_series)],new_series*180/math.pi*3600,color=color) pylab.xlabel('Time') pylab.ylabel('Filtered ' + variable + " [arcseconds]") #fourrier signal pylab.subplot(2,2,2) # pylab.plot(np.fft.rfft(series)) power_axis = np.fft.fftfreq(len(series),0.1) power_axis=power_axis[power_axis>0] power_axis=np.append(power_axis,1/delta/2) # power_axis=sp.fftpack.rfftfreq(len(series),0.1) pylab.plot(power_axis, power_spectrum(series,sampling_frequency=1/delta),color=color) pylab.xlabel('Freq (Hz)') pylab.ylabel('Original Power (log10 Scale)') pylab.subplot(2,2,4) # pylab.plot(power_axis,np.fft.rfft(new_series)) # pylab.plot(np.fft.rfft(new_series)) pylab.plot(power_axis,power_spectrum(new_series,sampling_frequency=1/delta),color=color) pylab.xlabel('Freq (Hz)') pylab.ylabel('Filtered Power (log10 Scale)') # Motion and Correlated Standard Deviation moving_width = 16 # Do even numbers stdseries=np.zeros(len(series)) for ii in np.arange(moving_width/2,len(series)-moving_width/2): stdseries[ii]=np.std(new_series[ii-moving_width/2:ii+moving_width/2]) pylab.figure(num=None, figsize=(13, 7), dpi=80, facecolor='w', edgecolor='k') pylab.title('Gondola Motion and Corresponding Signal Standard Deviation') pylab.subplot(2,1,1) pylab.grid() pylab.plot(np.arange(0,len(series)*delta,delta)[0:len(series)],series*180/math.pi*3600,color=color) # pylab.plot(np.arange(0,len(stdseries)*delta,delta)[0:len(stdseries)],series*180/math.pi*3600 + 10*stdseries*180/math.pi*3600,color='red') # pylab.plot(np.arange(0,len(stdseries)*delta,delta)[0:len(stdseries)],series*180/math.pi*3600-10*stdseries*180/math.pi*3600,color='red') pylab.xlabel('Time') pylab.ylabel(variable + " [arcseconds]") pylab.subplot(2,1,2) pylab.grid() pylab.plot(np.arange(0,len(new_series)*delta,delta)[0:len(new_series)],new_series*180/math.pi*3600,color=color) #3 Standard Deviation Envelope pylab.plot(np.arange(0,len(stdseries)*delta,delta)[0:len(stdseries)],3*stdseries*180/math.pi*3600,color='red',linewidth=2) pylab.plot(np.arange(0,len(stdseries)*delta,delta)[0:len(stdseries)],-3*stdseries*180/math.pi*3600,color='red',linewidth=2) pylab.xlabel('Time') pylab.ylabel(variable + " Moving STD [arcseconds]") pylab.legend(['High Frequency Motion','+3 Sigma','-3 Sigma']) return new_series
from numpy.fft import fft, fftshift, fftfreq N = 2**13 fs = 44100. x = np.arange(0,N)/fs f = 1800. #signal y = np.sin(2*np.pi*x*f) #window window = np.hanning(N) # windowed signal y *= window (b_iir, a_iir) = iirdesign(0.49, 0.51, 0.05, 70, analog=0, ftype='ellip', output='ba') print("IIR coeff created", len(b_iir), len(a_iir)) Ntaps = 512 b_fir = remez(numtaps=Ntaps, bands=[0., 0.49/2., 0.51/2., 1./2.], desired=[1.,0.])#, maxiter=250, grid_density=64) a_fir = [1.] print("FIR coeff created", len(b_fir), len(a_fir)) import time t0 = time.time() yf_fir, zf = lfilter(b_fir, a_fir, y, zi=np.zeros(max(len(a_fir),len(b_fir))-1)) t1 = time.time() yf_iir, zf = lfilter(b_iir, a_iir, y, zi=np.zeros(max(len(a_iir),len(b_iir))-1)) t2 = time.time() tfir = t1 - t0 tiir = t2 - t1
# if (i + 882) < len(wavfiles[1][1]): # # create a bandstop filter # Wp = [bot, top] # Cutoff frequency # Ws = [bot + 0.001, top - 0.001] # Stop frequency # Rp = 1 # passband maximum loss (gpass) # As = automation[i / 441] # stoppand min attenuation (gstop) # b, a = fd.iirdesign(Wp, Ws, Rp, As, ftype='ellip') # f = lfilter(b, a, wavfiles[1][1][i:i+441]) # for sample in f: # filtered.append(sample) Wp = [bot, top] # Cutoff frequency Ws = [bot + 0.001, top - 0.001] # Stop frequency Rp = 1 # passband maximum loss (gpass) As = 10 # stoppand min attenuation (gstop) b, a = fd.iirdesign(Wp, Ws, Rp, As, ftype='ellip') filtered = lfilter(b, a, wavfiles[1][1]) # print len(wavfiles[1][1]) # print len(filtered) # print len(automation) # print filtered output = asarray(filtered, 'int16') scipy.io.wavfile.write('output.wav', sample_rate, output)
def main(): from matplotlib.pyplot import semilogx, plot, show, xlim, ylim, figure, legend, subplot, bar from numpy.fft import fft, fftfreq, fftshift, ifft from numpy import log10, linspace, interp, angle, array, concatenate N = 2048 * 2 * 2 fs = float(SAMPLING_RATE) channel_count = 20 low_freq = 20. impulse = zeros(N) impulse[N / 2] = 1 f = 1000. # impulse = sin(2*pi*f*arange(0, N/fs, 1./fs)) # [ERBforward, ERBfeedback] = MakeERBFilters(fs, channel_count, low_freq) # y = ERBFilterBank(ERBforward, ERBfeedback, impulse) bands_per_octave = 3 total_band_count = NOCTAVE * bands_per_octave [B, A, fi, fl, fh] = octave_filters(total_band_count, bands_per_octave) y, zfs = octave_filter_bank(B, A, impulse) # print "Filter lengths without decimation" # for b, a in zip(B, A): # print len(b), len(a) response = 20. * log10(abs(fft(y))) freqScale = fftfreq(N, 1. / fs) figure() subplot(211) for i in range(0, response.shape[0]): semilogx(freqScale[0:int(N / 2)], response[i, 0:int(N / 2)]) xlim(fs / 2000, fs) ylim(-70, 10) subplot(212) m = 0 for f in fi: p = 10. * log10((y[m]**2).mean()) m += 1 semilogx(f, p, 'ko') Ndec = 3 fc = 0.5 # other possibilities # (bdec, adec) = ellip(Ndec, 0.05, 30, fc) # print bdec # (bdec, adec) = cheby1(Ndec, 0.05, fc) # (bdec, adec) = butter(Ndec, fc) (bdec, adec) = iirdesign(0.48, 0.50, 0.05, 70, analog=0, ftype='ellip', output='ba') # bdec = firwin(30, fc) # adec = [1.] figure() subplot(211) response = 20. * log10(abs(fft(impulse))) plot(fftshift(freqScale), fftshift(response), label="impulse") y = lfilter(bdec, adec, impulse) response = 20. * log10(abs(fft(y))) plot(fftshift(freqScale), fftshift(response), label="lowpass") ydec = y[::2].repeat(2) response = 20. * log10(abs(fft(ydec))) plot(fftshift(freqScale), fftshift(response), label="lowpass + dec2 + repeat2") ydec2 = interp(list(range(0, len(y))), list(range(0, len(y), 2)), y[::2]) response = 20. * log10(abs(fft(ydec2))) plot(fftshift(freqScale), fftshift(response), label="lowpass + dec2 + interp2") ydec3 = y[::2] response = 20. * log10(abs(fft(ydec3))) freqScale2 = fftfreq(int(N / 2), 2. / fs) plot(freqScale2, fftshift(response), label="lowpass + dec2") legend(loc="lower left") subplot(212) plot(list(range(0, len(impulse))), impulse, label="impulse") plot(list(range(0, len(impulse))), y, label="lowpass") plot(list(range(0, len(impulse))), ydec, label="lowpass + dec2 + repeat2") plot(list(range(0, len(impulse))), ydec2, label="lowpass + dec2 + interp2") plot(list(range(0, len(impulse), 2)), ydec3, label="lowpass + dec2") legend() [boct, aoct, fi, flow, fhigh] = octave_filters_oneoctave(total_band_count, bands_per_octave) y, dec, zfs = octave_filter_bank_decimation(bdec, adec, boct, aoct, impulse) # print "Filter lengths with decimation" # print len(bdec), len(adec) # for b, a in zip(boct, aoct): # print len(b), len(a) figure() subplot(211) for yone, d in zip(y, dec): response = 20. * log10(abs(fft(yone)) * d) freqScale = fftfreq(int(N / d), 1. / (fs / d)) semilogx(freqScale[0:int(N / (2 * d))], response[0:int(N / (2 * d))]) xlim(fs / 2000, fs) ylim(-70, 10) subplot(212) m = 0 for i in range(0, NOCTAVE): for f in fi: p = 10. * log10((y[m]**2).mean()) semilogx(f / dec[m], p, 'ko') m += 1 [boct, aoct, fi, flow, fhigh] = octave_filters_oneoctave(total_band_count, bands_per_octave) y1, dec, zfs = octave_filter_bank_decimation(bdec, adec, boct, aoct, impulse[0:int(N / 2)]) y2, dec, zfs = octave_filter_bank_decimation(bdec, adec, boct, aoct, impulse[int(N / 2):], zis=zfs) y = [] for y1one, y2one in zip(y1, y2): y += [concatenate((y1one, y2one))] figure() subplot(211) for yone, d in zip(y, dec): response = 20. * log10(abs(fft(yone)) * d) freqScale = fftfreq(int(N / d), 1. / (fs / d)) semilogx(freqScale[0:int(N / (2 * d))], response[0:int(N / (2 * d))]) xlim(fs / 2000, fs) ylim(-70, 10) subplot(212) m = 0 for i in range(0, NOCTAVE): for f in fi: p = 10. * log10((y[m]**2).mean()) semilogx(f / dec[m], p, 'ko') m += 1 generate_filters_params() show()
def GetComponents(self, x_axis, y_axis, z_axis): """ GetComponents discriminates between gravity and body acceleration by applying an infinite impulse response (IIR) filter to the raw acceleration data (one trial) given in input. :param x_axis: acceleration data in the axis x :param y_axis: acceleration data in the axis y :param z_axis: acceleration data in the axis z :return gravity: gravity component of the acceleration data :return body: body component of the acceleration data """ #APPLY IIR FILTER TO GET THE GRAVITY COMPONENTS #IIR filter parameters (all frequencies are in Hz) Fs = 32 # sampling frequency Fpass = 0.25 # passband frequency Fstop = 2 # stopband frequency Apass = 0.001 # passband ripple (dB) Astop = 100 # stopband attenuation (dB) match = 'pass' # band to match exactly delay = 64 # delay (# samples) introduced by filtering #Create the IIR filter # iirdesign agruements Wip = (Fpass) / (Fs / 2) Wis = (Fstop + 1e6) / (Fs / 2) Rp = Apass # passband ripple As = Astop # stopband attenuation # The iirdesign takes passband, stopband, passband ripple, # and stop attenuation. bb, ab = ifd.iirdesign(Wip, Wis, Rp, As, ftype='cheby1') g1 = lfilter(bb, ab, x_axis) g2 = lfilter(bb, ab, y_axis) g3 = lfilter(bb, ab, z_axis) #COMPUTE THE BODY-ACCELERATION COMPONENTS BY SUBTRACTION (PREGUNTA) gravity = zeros((self.numSamples - delay, 3)) body = zeros((self.numSamples - delay, 3)) i = 0 while (i < self.numSamples - delay): #shift & reshape gravity to reduce the delaying effect of filtering gravity[i, 0] = g1[i + delay] gravity[i, 1] = g2[i + delay] gravity[i, 2] = g3[i + delay] body[i, 0] = x_axis[i] - gravity[i, 0] body[i, 1] = y_axis[i] - gravity[i, 1] body[i, 2] = z_axis[i] - gravity[i, 2] i = i + 1 #COMPUTE THE BODY-ACCELERATION COMPONENTS BY SUBTRACTION return gravity, body
def __init__(self, bpass, bstop, ftype='butter'): self.b, self.a = fd.iirdesign( bpass, bstop, 1, 100, ftype=ftype, output='ba') self.ic = st.lfiltic(self.b, self.a, (0.0,))
numtaps = 4 ################### ### IIR FILTER ### ################### # Specification for our filter Wp = cutoff_hz/nyq_rate # Cutoff frequency Ws = (cutoff_hz+1.5)/nyq_rate # Stop frequency Rp = 1 # Ripple in the passband maximum loss (gpass) As = 42 # Min Attenuation in the stoppand (gstop) Filters = {'ellip' : (), 'cheby2' : (), 'butter' : (), 'cheby1' : (), 'bessel' : ()} # The ellip and cheby2 filter design Filters['ellip'] = fd.iirdesign(Wp, Ws, Rp, As, ftype='ellip') Filters['cheby2'] = fd.iirdesign(Wp, Ws, Rp, As, ftype='cheby2') Filters['butter'] = fd.iirdesign(Wp, Ws, Rp, As, ftype='butter') Filters['cheby1'] = fd.iirdesign(Wp, Ws, Rp, As, ftype='cheby1') # The bessel max order of 8 for this cutoff, can't use # iirdesign have to use iirfilter. Filters['bessel'] = fd.iirfilter(8, Wp, btype='lowpass', ftype='bessel') ## Pass the signal though the filter velocity = reference_velocity.getAxis(0) velocityfilter = {'ellip' : (), 'cheby2' : (), 'butter' : (), 'cheby1' : (), 'bessel' : ()} velocityfilter['ellip'] = sig.lfilter(Filters['ellip'][0], Filters['ellip'][1], velocity) velocityfilter['cheby2'] = sig.lfilter(Filters['cheby2'][0], Filters['cheby2'][1], velocity) velocityfilter['butter'] = sig.lfilter(Filters['butter'][0], Filters['butter'][1], velocity)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Apr 23 17:44:21 2017 @author: egor """ from scipy.signal import filter_design as fd # Specification for our filter F_NY = 44100 / 2 Fp = 82 Fs = 50 Wp = Fp / F_NY # end of passband, normalized frequency Ws = Fs / F_NY # start of the stopband, normalized frequency Rp = 1 # passband maximum loss (gpass) As = 120 # stoppand min attenuation (gstop) # The ellip filter design M = fd.iirdesign(Wp, Ws, Rp, As, ftype='ellip', output='sos') k = len(M) # Print coef to file f = open("coef", "w") f.write("{}\n".format(k)) for coef in M: b0, b1, b2, a0, a1, a2 = coef s = "{} {} {} {} {} {}\n".format(b0, b1, b2, a0, a1, a2) f.write(s) f.close()