def genFilters(): bp = [ ] bp.append(ss.remez(50, [0, 0.02, 0.05, 0.5], [1,0])) bp.append(ss.remez(50, [0, 0.02, 0.05, 0.20, 0.25, 0.5], [0, 1, 0])) bp.append(ss.remez(50, [0, 0.20, 0.25, 0.5], [0, 1], type = "hilbert")) return bp
def HPman(self, fil_dict): self._get_params(fil_dict) if (self.N % 2 == 0): # even order, use odd symmetry (type III) self._save(fil_dict, sig.remez(self.N,[0, self.F_SB, self.F_PB, 0.5], [0, 1], weight = [fil_dict['W_SB'],fil_dict['W_PB']], Hz = 1, type = 'hilbert', grid_density = self.grid_density)) else: # odd order, self._save(fil_dict, sig.remez(self.N,[0, self.F_SB, self.F_PB, 0.5], [0, 1], weight = [fil_dict['W_SB'],fil_dict['W_PB']], Hz = 1, type = 'bandpass', grid_density = self.grid_density))
def filter_design(): if not glob.glob('ECoG_filter.h5'): from scipy.signal import remez f1 = remez(121, [0, 8, 12, 20, 24, 500], [0, 1, 0], Hz=1000) f2 = remez(121, [0, 50, 60, 100, 110, 500], [0, 1, 0], Hz=1000) f3 = remez(121, [0, 90, 100, 200, 210, 500], [0, 1, 0], Hz=1000) filters = [f1, f2, f3] with h5py.File('ECoG_filter.h5', 'w') as f: f.create_dataset('filters', data=filters) else: with h5py.File('ECoG_filter.h5', 'r') as f: filters = f['filters'][:] return filters
def HPmin(self, fil_dict): self._get_params(fil_dict) (self.N, F, A, W) = remezord([self.F_SB, self.F_PB], [0, 1], [self.A_SB, self.A_PB], Hz = 1, alg = self.alg) # self.N = ceil_odd(N) # enforce odd order fil_dict['W_SB'] = W[0] fil_dict['W_PB'] = W[1] if (self.N % 2 == 0): # even order self._save(fil_dict, sig.remez(self.N, F,[0, 1], weight = W, Hz = 1, type = 'hilbert', grid_density = self.grid_density)) else: self._save(fil_dict, sig.remez(self.N, F,[0, 1], weight = W, Hz = 1, type = 'bandpass', grid_density = self.grid_density))
def HPmin(self, fil_dict): self._get_params(fil_dict) (self.N, F, A, W) = remezord([self.F_SB, self.F_PB], [0, 1], [self.A_SB, self.A_PB], fs = 1, alg = self.alg) if not self._test_N(): return -1 # self.N = ceil_odd(N) # enforce odd order fil_dict['W_SB'] = W[0] fil_dict['W_PB'] = W[1] if (self.N % 2 == 0): # even order self._save(fil_dict, sig.remez(self.N, F,[0, 1], weight = W, fs = 1, type = 'hilbert', grid_density = self.grid_density)) else: self._save(fil_dict, sig.remez(self.N, F,[0, 1], weight = W, fs = 1, type = 'bandpass', grid_density = self.grid_density))
def fir_remez_bpf(f_stop1, f_pass1, f_pass2, f_stop2, d_pass, d_stop, fs=1.0, n_bump=5, status=True): """ Design an FIR bandpass filter using remez with order determination. The filter order is determined based on f_stop1 Hz, f_pass1 Hz, f_pass2 Hz, f_stop2 Hz, and the desired passband ripple d_pass dB and stopband attenuation d_stop dB all relative to a sampling rate of fs Hz. Mark Wickert October 2016, updated October 2018 """ n, ff, aa, wts = bandpass_order(f_stop1, f_pass1, f_pass2, f_stop2, d_pass, d_stop, fsamp=fs) # Bump up the order by N_bump to bring down the final d_pass & d_stop N_taps = n N_taps += n_bump b = signal.remez(N_taps, ff, aa[0::2], wts, Hz=2) if status: log.info('Remez filter taps = %d.' % N_taps) return b
def high_pass_filter(signal_input, cut_off_freq, sampling_freq, filter_order=2): """Applying high-pass filter Args: signal_input: the input data (1d-array). cut_off_freq: frequency below which the signals are attenuated. sampling_freq: the sampling frequency of the recorded data. filter_order: a number showing the complexity of the filter structure `remez` function get the number of taps as input. The number of taps is the number of terms in the filter, or the filter order plus one. Returns: filtered_signal: the filtered signal (1d-array) filter_coefficients: the coefficients of the optimal filter for the high pass filter """ filter_coefficients = remez( filter_order + 1, [0, 0.9 * cut_off_freq, 1.1 * cut_off_freq, 0.5 * sampling_freq], [0, 1.0], Hz=sampling_freq) filtered_signal = lfilter(filter_coefficients, 1, signal_input) return filtered_signal, filter_coefficients
def coeffbandpass_filter(lcut1, lcut2, hcut1, hcut2, fs, n): """ Method used to design a bandpass filter Parameters: data : eeg signal to filter *__________* /| |\ / | | \ / | | \ ___*/ | | \*____ lcut1 lcut2 hcut1 hcut2 lowcut1, lowcut2, highcut1, highcut2 : frequency band of the fir filter fs : sampling frequency n : number of iteration for the Remez algorithm """ low1 = lcut1 / fs low2 = lcut2 / fs high1 = hcut1 / fs high2 = hcut2 / fs b = signal.remez(n, [0, low1, low2, high1, high2, 0.5], [0, 1, 0]) #print(b) """freq, response = signal.freqz(b) ampl = np.abs(response) fig1 = plt.figure() ax1 = fig1.add_subplot(111) ax1.semilogy(fs*freq/(2*np.pi), ampl, 'b-') # freq in Hz""" return b
def bpf_design(fs: int, fcutoff: float, flow: float=300., L: int=256): """ Design FIR bandpass filter coefficients "b" fcutoff: cutoff frequency [Hz] fs: sampling frequency [Hz] flow: low cutoff freq [Hz] to eliminate rumble or beating carriers L: number of taps (more taps->narrower transition band->more CPU) https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.remez.html """ firtype = 'firwin' if firtype == 'remez': # 0.8*fc is arbitrary, for finite transition width b = signal.remez(L, [0, 0.8*flow, flow, 0.8*fcutoff, fcutoff, 0.5*fs], [0., 1., 0.], Hz=fs) elif firtype == 'firwin': b = signal.firwin(L, [flow, fcutoff], pass_zero=False, width=100, nyq=0.5*fs, window='kaiser', scale=True) elif firtype == 'matlab': assert L % 2 != 0, 'must have odd number of taps' from oct2py import Oct2Py with Oct2Py() as oc: oc.eval('pkg load signal') b = oc.fir1(L+1, [0.03, 0.35], 'bandpass') return b
def Bandpass(lowcut, highcut, trans_width, fs): numtaps = 100 edges = [0, lowcut - trans_width, lowcut, highcut, highcut + trans_width, 0.5*fs] taps = sig.remez(numtaps, edges, [0, 1, 0], Hz=fs) return taps
def lowpass_remez(fl1, fl2, x, map=2, mas=40, Fs=1000.0): """Simple interface for lowpass-filter using Parks-McClellan algorithm. :Parameters: fl1: float, lower edge-frequency for transition band fl2: float, upper edge-frequency for transition band x: array, data to filter. Can be array of arbitrary dimension. The first index must be the time index. map: float, maximum attenuation in pass band mas: float, minimum attenuation in stop band Fs: float, Sampling-frequency of the data :Returns: y: array, The filtered data """ map = float(-abs(map)) mas = float(-abs(mas)) n, f, a, w = remezord([fl1, fl2], [1, 0], [1 - (10**(map / 10)), 10**(mas / 10)], Hz=Fs) b = remez(n, f, a, w) #z=lfilter(b,a,xn) y = filtfilt(b, [1], x) return y
def test_firpm_1(self): x = [i for i in range(len(self.f1))] ipf = ip.interp1d(x, self.f1) f1_new = ipf(np.linspace(x[0], x[-1], 2 * len(x))) FIR = FIRDesign.firpm(self.n1, self.f1, self.a1) fir = signal.remez(self.n1 + 1, f1_new, self.a1, fs=2) self.assertTrue(np.all(FIR[0] == fir))
def FilterAndDownSample(x, fs): """ Parametros: x: Señal a filtrar y fs: Frecuencia de muestreo """ # traps es el número de términos en el filtro, o el orden de filtro más uno. n_taps = 50 # Calcule el filtro óptimo minimax utilizando el algoritmo de intercambio Remez. coef = remez(n_taps, [0, F_BW, F_BW * 1.4, fs / 2], [1, 0], Hz=fs) # (*@ \label{code:remezFunction} @*) x_filter = lfilter(coef, 1.0, x) if PLOT: PlotFilterCharacteristic(coef, fs) dec_rate = int(fs / F_BW) x_downsample = x_filter[0::dec_rate] # Se calcula la nueva frecuencia de muestreo fs_y = fs / dec_rate if PLOT: PlotSpectrum(x_downsample, "x downsample", "x_downsample_spectrum.pdf", fs_y) PlotConstelation(x_downsample, "x downsample", "x_downsample_constelation.pdf") return x_downsample, fs_y
def design(self, params): coeffs = signal.remez(**params) den = np.zeros_like(coeffs) den[0] = 1 return coeffs, den
def example_hilbert_robust_remez(): ''' 1. use the Remez exchange algorithm to design a lowpass filter 2. modulation thee lowpass impulse-response by a complex sinusoid at frequency fs/4 ''' count = 257 fs = 22050 fn = fs / 2 # nyquest f1 = 530 # transition bandwidth f2 = fn - f1 # upper transition bandwidth count = 257 bands = [0, f2 - fs / 4, fs / 4, fn] lpfir = signal.remez(count, bands, [1, 0], [1, 10], fs=fs) # modulate lowpass to single-sideband #csin = np.array([1j]) modsin = np.power(np.full((count), 1j), np.arange(count)) fir = lpfir * modsin response = np.fft.fft(fir, 4096) gain = np.abs(response) gain_db = 20 * np.log10(gain) gain_db = gain_db - np.nanmax(gain_db) plt.plot(np.fft.fftshift(gain_db)) plt.show()
def filter_examples(): ''' Plots some example bandpass filters with different numbers of taps ''' bands = [0, .19, .21, .29, .31, .5] gains = [0, 1, 0] # bands = [0, .19, .2, .3, .31, .5] # gains = [0, 0, 1, 1, 0, 0] B = [] a = 1 taps = range(10, 131, 30) for t in taps: B.append(remez(t, bands, gains, type = 'bandpass', maxiter = 1000, grid_density = 32)) # B.append(firwin2(t, bands, gains, nyq = 0.5)) fig = plt.figure() ax1 = fig.add_subplot(1,1,1) ax1.set_title('Frequency Responses for Various FIR lengths') ax1.set_ylabel('Amplitude [dBV]') ax1.set_xlabel('Frequency [Rad/Sample]') for i, b in enumerate(B): w, h = freqz(b, a) ax1.plot(w, 20*log10(abs(h)), label = '%d taps' % taps[i]) ax1.legend() fig.show() raw_input('Continue?...') return
def fir_optim(Fp, ap, Fa, aa, graf=False): """ Donats una serie de paràmetres, retorna un array de coeficients b que formen el filtre amb les especificacions donades. \t Fp: frequencia discreta limit de la banda de pas \t ap: arrissat en dB de la banda de pas \t Fa: frequencia discreta limit de la banda de rebuig \t aa: minima atenuacio en dB de la banda de rebuig respecte de la de pas \t graf: representació del filtre creat. El seu valor pot ser True o False.[argument opcional] \n """ dp = (10**(ap / 10) - 1) / (10**(ap / 20) + 1) da = 10**(-aa / 20) L = 2 while True: b = scs.remez( L, [0, Fp, Fa, 0.5], [1, 0], [da, dp] ) # Anem calculant conjunts de coeficients de ordre creixent fins a retornar. if compleix( b, Fp, dp, Fa, da ): # Comprovem si aquells coeficients compleixen els requisits especificats per el filtre. if graf == True: representa_FIR( b, Fp, ap, Fa, aa) # Si es compleix, retornem i el bucle acaba. return b L += 1
def do_plot(self): recv_f0 = self.params.get('recv_f0', 2250) recv_f1 = self.params.get('recv_f1', 3150) recv_f = [recv_f0, recv_f1] sample_f = 48000 # sampling rate, Hz, must be integer plt.figure() plt.ylim(-60, 5) plt.xlim(0, 5500) plt.grid(True) plt.xlabel('Frequency (Hz)') plt.ylabel('Gain (dB)') plt.title('{}Hz, {}Hz'.format(recv_f[0], recv_f[1])) filters = [] fbw = [(recv_f[1] - recv_f[0]) * 0.85, (recv_f[1] - recv_f[0]) * 0.8] for i in range(2): f = recv_f[i] filter_bp = signal.remez( 80, [0, f - fbw[i], f, f, f + fbw[i], sample_f / 2], [0, 1, 0], fs=sample_f, maxiter=100) filters.append(filter_bp) w, h = signal.freqz(filters[i], [1], worN=2500) plt.plot(0.5 * sample_f * w / np.pi, 20 * np.log10(np.abs(h))) plt.plot((f, f), (10, -60), color='red', linestyle='dashed') plt.plot((500, 500), (10, -60), color='blue', linestyle='dashed') plt.plot((700, 700), (10, -60), color='blue', linestyle='dashed') plt.show()
def band_pass_filter(signal_input, lower_bound_freq, higher_bound_freq, sampling_freq, filter_order=2): """Applying band-pass filter Args: signal_input: the input data (1d-array). lower_bound_freq: the lower bound frequency below which the signal must be completely attenuated. higher_bound_freq: the higher bound frequency above which the signal must be completely attenuated. sampling_freq: the sampling frequency of the recorded data. filter_order: a number showing the complexity of the filter structure `remez` function get the number of taps as input. The number of taps is the number of terms in the filter, or the filter order plus one. Returns: filtered_signal: the filtered signal (1d-array) filter_coefficients: the coefficients of the optimal filter for the band pass filter """ filter_coefficients = remez(filter_order + 1, [ 0, 0.9 * lower_bound_freq, lower_bound_freq, higher_bound_freq, 1.1 * higher_bound_freq, 0.5 * sampling_freq ], [0, 1.0, 0], Hz=sampling_freq) filtered_signal = lfilter(filter_coefficients, 1, signal_input) return filtered_signal, filter_coefficients
def _design_remez(self, maxiter=25): print("Taps = ", self.taps) print("Freqs = ", self.freqs) print("Gains = ", self.gains) self.B = signal.remez(self.taps, self.freqs, self.gains, maxiter=maxiter, Hz=self.sample_rate)
def lab6_ex3(): # set parameters of system fs = 2000 #sampling frequency (Hz) fn = fs/2 #nyqvist frequency fc = array([0,100,200,400,500,1000]) #corner frequencies fb = array([0,1.0,0]) #desired band gains for each pair of corner frequencies deg = 46 #degree of polynomial nt = deg + 1 #number of taps = degree + 1 a = array([1.0,0]) #(no feedback (FIR), poles at origin reduced to 1 for simplification) # create remez filter, frequency response, and plot b = remez(nt,fc,fb,Hz=fs) w,h = freqz(b,a) plot(w/pi*fn, 20*log10(abs(h)),'b-') title('FIR of given frequency response using remez algo') xlabel('frequency') ylabel('magnitude (dB scale)') grid() show() print('\nFilter requires 47 taps for stop-band attenuation of at least -40 dB') z,p,k = tf2zpk(b,a) zplane(z,p) title('zplane of remez-FIR of given frequency response (47 taps)') show()
def filter_data(self): '''Creates a low pass filter to filter out high frequency noise''' lpf = remez(self.bin_numbers, [0, 0.1, 0.25, 0.5], [1.0, 0.0]) filt_data = np.zeros(self.num_sensors+self.num_sharp_sensors) for i in range(self.num_sensors+self.num_sharp_sensors): filt_data[i] = np.dot(lpf, self.raw_dat_array[:,i]) return filt_data
def lowpass_remez(fl1,fl2,x,map=2,mas=40,Fs=1000.0): """Simple interface for lowpass-filter using Parks-McClellan algorithm. :Parameters: fl1: float, lower edge-frequency for transition band fl2: float, upper edge-frequency for transition band x: array, data to filter. Can be array of arbitrary dimension. The first index must be the time index. map: float, maximum attenuation in pass band mas: float, minimum attenuation in stop band Fs: float, Sampling-frequency of the data :Returns: y: array, The filtered data """ map = float(-abs(map)) mas = float(-abs(mas)) n,f,a,w = remezord([fl1,fl2],[1,0],[1-(10**(map/10)),10**(mas/10)],Hz=Fs) b=remez(n,f,a,w) #z=lfilter(b,a,xn) y=filtfilt(b,[1],x) return y
def get_filtered(self, array, band): processed = np.array(array) processed = signal.detrend(processed) processed = utils.butter_bandpass_filter(processed, 0.3, 2.5, self.fps, order=3) signal_line = processed - smooth(processed, 5) signal_line = utils.butter_bandpass_filter(signal_line, 0.05, 0.15, self.fps, order=9) analytic_signal = signal.hilbert(signal_line) high = np.mean(np.abs(analytic_signal)) low = np.mean(low_envelope(signal_line)) d_signal = signal.detrend(signal_line) removed = filter(lambda x: low < x < high, d_signal) edges = [0, band[0], band[1], band[2], band[3], 0.5 * self.fps] taps = signal.remez(3, edges, [0, 1, 0], Hz=self.fps, grid_density=20) filttered_color = np.convolve(taps, removed)[len(taps) // 2:] return filttered_color
def generate_lowpass(self, fs, cutoff, trans_width, numtaps): taps = signal.remez(numtaps, [0, cutoff, cutoff + trans_width, 0.5 * fs], [1, 0], Hz=fs) w, h = signal.freqz(taps, [1], worN=2000) return w, h, taps
def __init__(self, fir_len, fir_bits, tb_width): tb_ctr = 1/(2*4) pass_corner = tb_ctr - (tb_ctr*tb_width/2) stop_corner = tb_ctr + (tb_ctr*tb_width/2) fir_bands = [0, pass_corner, stop_corner, 0.5] b = signal.remez(fir_len, fir_bands, [1, 0]) coeff_scl = 2**(fir_bits-1) self.fir_coeff = np.floor(b*coeff_scl + 0.5) # Dump Coefficients? if 1: write_meminit("fir4dec_coeff.v", self.fir_coeff) self.fir_coeff = self.fir_coeff/coeff_scl; # plot FIR response? if 1: W, H = signal.freqz(self.fir_coeff) plt.figure() plt.plot(W/(2*np.pi), 20*np.log10(np.abs(H))) plt.grid() plt.xlabel("Freq (normalized)") plt.ylabel("dB") plt.title("fir4dec response (close to continue sim)") plt.show()
def prototype_filter_remez(): """ ASSIGNMENT 2 Compute the prototype filter used in subband coding. The filter is a 512-point lowpass FIR h[n] with bandwidth pi/64 and stopband starting at pi/32 You should use the remez routine (signal.remez()). See http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.remez.html """ from scipy import signal M = 512 Fs = 44100 F_nyquist = Fs // 2 Fpass = F_nyquist * (1 / 128) Fstop = F_nyquist * (1 / 32) bpass = signal.remez(numtaps=M, bands=[0, Fpass, Fstop, F_nyquist], desired=[2, 0], Hz=Fs) return bpass
def __init__(self, *args, **kwargs): Modulator.__init__(self, *args, **kwargs) self.taps = 81 self.kernel = remez(self.taps, [0.1, 0.4], [1.0], type='hilbert') self.zi = np.zeros(len(self.kernel) - 1) G = self.taps / 2 self.overlap = np.zeros(G)
def __init__(self, stationMHz): self.sdr = rtlsdr.RtlSdr() self.validsGains = self.sdr.get_gains() self.indexGain = 10 self.f_offset = 250000 # Desplazamiento para capturar self.f_station = stationMHz # Frecuencia de radio self.dec_rate = int(FS / F_BW) self.fs_y = FS / (self.dec_rate) self.coef = remez(N_TRAPS, [0, F_BW, F_BW * 1.4, FS / 2], [1, 0], Hz=FS) self.expShift = (-1.0j * 2.0 * np.pi * self.f_offset / FS) # Se configura los parametros self.dec_audio = int(self.fs_y / AUDIO_FREC) self.stream = sd.OutputStream(device='default', samplerate=int(self.fs_y / self.dec_audio), channels=1, dtype='float32') self.beginListening = 0 self.soundQueue = queue.Queue() self.samplesQueue = queue.Queue()
def fir_remez_bsf(f_pass1, f_stop1, f_stop2, f_pass2, d_pass, d_stop, fs=1.0, N_bump=5): """ Design an FIR bandstop filter using remez with order determination. The filter order is determined based on f_pass1 Hz, f_stop1 Hz, f_stop2 Hz, f_pass2 Hz, and the desired passband ripple d_pass dB and stopband attenuation d_stop dB all relative to a sampling rate of fs Hz. Mark Wickert October 2016 """ n, ff, aa, wts = optfir.remezord([f_pass1, f_stop1, f_stop2, f_pass2], [ 1, 0, 1 ], [1 - 10**(-d_pass / 20.), 10**(-d_stop / 20.), 1 - 10**(-d_pass / 20.)], fsamp=fs) # Bump up the order by N_bump to bring down the final d_pass & d_stop N_taps = n N_taps += N_bump b = signal.remez(N_taps, ff, aa[0::2], wts, Hz=2) print('Remez filter taps = %d.' % N_taps) return b
def BSman(self, fil_dict): self._get_params(fil_dict) self.N = round_odd(self.N) # enforce odd order self._save(fil_dict, sig.remez(self.N,[0, self.F_PB, self.F_SB, self.F_SB2, self.F_PB2, 0.5],[1, 0, 1], weight = [fil_dict['W_PB'],fil_dict['W_SB'], fil_dict['W_PB2']], Hz = 1, grid_density = self.grid_density))
def BPman(self, fil_dict): self._get_params(fil_dict) self._save(fil_dict, sig.remez(self.N,[0, self.F_SB, self.F_PB, self.F_PB2, self.F_SB2, 0.5],[0, 1, 0], weight = [fil_dict['W_SB'],fil_dict['W_PB'], fil_dict['W_SB2']], Hz = 1, grid_density = self.grid_density))
def test_hilbert(self): N = 11 # number of taps in the filter a = 0.1 # width of the transition band # design an unity gain hilbert bandpass filter from w to 0.5-w h = remez(11, [a, 0.5-a], [1], type='hilbert') # make sure the filter has correct # of taps assert_(len(h) == N, "Number of Taps") # make sure it is type III (anti-symmetric tap coefficients) assert_array_almost_equal(h[:(N-1)//2], -h[:-(N-1)//2-1:-1]) # Since the requested response is symmetric, all even coeffcients # should be zero (or in this case really small) assert_((abs(h[1::2]) < 1e-15).all(), "Even Coefficients Equal Zero") # now check the frequency response w, H = freqz(h, 1) f = w/2/np.pi Hmag = abs(H) # should have a zero at 0 and pi (in this case close to zero) assert_((Hmag[[0, -1]] < 0.02).all(), "Zero at zero and pi") # check that the pass band is close to unity idx = np.logical_and(f > a, f < 0.5-a) assert_((abs(Hmag[idx] - 1) < 0.015).all(), "Pass Band Close To Unity")
def _recv_decode_init_FIR(self, recv_f): self._filters = [] fbw = [(recv_f[1] - recv_f[0]) * 0.85, (recv_f[1] - recv_f[0]) * 0.8] for i in range(2): f = recv_f[i] filter_bp = signal.remez( 80, [0, f - fbw[i], f, f, f + fbw[i], sample_f / 2], [0, 1, 0], fs=sample_f, maxiter=100) self._filters.append(filter_bp) if not plot_spectrum: return import matplotlib.pyplot as plt plt.figure() plt.ylim(-60, 5) plt.xlim(0, 5500) plt.grid(True) plt.xlabel('Frequency (Hz)') plt.ylabel('Gain (dB)') plt.title('{}Hz, {}Hz'.format(recv_f[0], recv_f[1])) fbw = [(recv_f[1] - recv_f[0]) * 0.85, (recv_f[1] - recv_f[0]) * 0.8] for i in range(2): f = recv_f[i] w, h = signal.freqz(self._filters[i], [1], worN=2500) plt.plot(0.5 * sample_f * w / np.pi, 20 * np.log10(np.abs(h))) plt.plot((f, f), (10, -100), color='red', linestyle='dashed') plt.plot((500, 500), (10, -100), color='blue', linestyle='dashed') plt.plot((700, 700), (10, -100), color='blue', linestyle='dashed') plt.show()
def __init__(self, fir_len, fir_bits, tb_width): tb_ctr = 1 / (2 * 8) pass_corner = tb_ctr - (tb_ctr * tb_width / 2) stop_corner = tb_ctr + (tb_ctr * tb_width / 2) fir_bands = [0, pass_corner, stop_corner, 0.5] b = signal.remez(fir_len, fir_bands, [1, 0]) coeff_scl = 2**(fir_bits - 1) self.fir_coeff = np.floor(b * coeff_scl + 0.5) # Dump Coefficients? if 0: LUT = np.zeros(256, dtype=np.int) LUT[0:fir_len] = self.fir_coeff write_memh("fir8dec_coeff.memh", LUT) self.fir_coeff = self.fir_coeff / coeff_scl # plot FIR response? if 1: W, H = signal.freqz(self.fir_coeff) plt.figure() plt.plot(W / (2 * np.pi), 20 * np.log10(np.abs(H))) plt.grid() plt.xlabel("Freq (normalized)") plt.ylabel("dB") plt.title("fir8dec response (close to continue sim)") plt.show()
def prototype_filter(): """ Computes the prototype filter used in subband coding. The filter is a 512-point lowpass FIR h[n] with bandwidth pi/64 and stopband starting at pi/32 """ # number of lowpass points lowpass_points = 512 #setting sampling frequency fs = np.pi #pass frequency pass_frequency = fs / 128 #stop frequency stop_frequency = fs / 32 #filter filter = signal.remez(numtaps=lowpass_points, bands=[0, pass_frequency, stop_frequency, fs], desired=[2, 0], fs=2 * fs) return filter
def main(): # Compute filter coefficients with SciPy. coef = signal.remez(80, [0, 0.1, 0.1, 0.5], [1, 0]) fir = FIR(coef) # Simulate for different frequencies and concatenate # the results. in_signals = [] out_signals = [] for frequency in [0.05, 0.07, 0.1, 0.15, 0.2]: tb = TB(fir, frequency) fragment = autofragment.from_local() sim = Simulator(fragment, Runner()) sim.run(100) in_signals += tb.inputs out_signals += tb.outputs # Plot data from the input and output waveforms. plt.plot(in_signals) plt.plot(out_signals) plt.show() # Print the Verilog source for the filter. print(verilog.convert(fir.get_fragment(), ios={fir.i, fir.o}))
def fir_calc_filter(Fs, Fpb, Fsb, Apb, Asb, N): bands = np.array([0., Fpb/Fs, Fsb/Fs, .5]) # Remez weight calculation: # https://www.dsprelated.com/showcode/209.php err_pb = (1 - 10**(-Apb/20))/2 # /2 is not part of the article above, but makes it work much better. err_sb = 10**(-Asb/20) w_pb = 1/err_pb w_sb = 1/err_sb h = signal.remez( N+1, # Desired number of taps bands, # All the band inflection points [1,0], # Desired gain for each of the bands: 1 in the pass band, 0 in the stop band [w_pb, w_sb] ) (w,H) = signal.freqz(h) Hpb_min = min(np.abs(H[0:int(Fpb/Fs*2 * len(H))])) Hpb_max = max(np.abs(H[0:int(Fpb/Fs*2 * len(H))])) Rpb = 1 - (Hpb_max - Hpb_min) Hsb_max = max(np.abs(H[int(Fsb/Fs*2 * len(H)+1):len(H)])) Rsb = Hsb_max print("Rpb: %fdB" % (-dB20(Rpb))) print("Rsb: %fdB" % -dB20(Rsb)) return (h, w, H, Rpb, Rsb, Hpb_min, Hpb_max, Hsb_max)
def fir_remez_hpf(f_stop, f_pass, d_pass, d_stop, fs = 1.0, N_bump=5): """ Design an FIR highpass filter using remez with order determination. The filter order is determined based on f_pass Hz, fstop Hz, and the desired passband ripple d_pass dB and stopband attenuation d_stop dB all relative to a sampling rate of fs Hz. Mark Wickert October 2016 """ # Transform HPF critical frequencies to lowpass equivalent f_pass_eq = fs/2. - f_pass f_stop_eq = fs/2. - f_stop # Design LPF equivalent n, ff, aa, wts=optfir.remezord([f_pass_eq,f_stop_eq], [1,0], [1-10**(-d_pass/20.),10**(-d_stop/20.)], fsamp=fs) # Bump up the order by N_bump to bring down the final d_pass & d_stop N_taps = n N_taps += N_bump b = signal.remez(N_taps, ff, aa[0::2], wts,Hz=2) # Transform LPF equivalent to HPF n = np.arange(len(b)) b *= (-1)**n print('Remez filter taps = %d.' % N_taps) return b
def better_envelope(rf_in): # cutoff == 0.2 and 0.8 from fs = 20.832 MHz # f_cutoff = 0.2*(fs/2) = 2.0832MHz, 0.8*(fs/2) = 8.3328, # f0 = fs/4 = 5.208MHz fixed in Verasonics US systems cutoff_low = 0.2 cutoff_high = 0.8 # fs = 20.832 num_taps = 10 # This is equivalent to B=firpm(10,[.2 .8],[1 1],'Hilbert'); # hilbert is a 90-phase transform. coefficients = remez(num_taps + 1, [cutoff_low / 2, cutoff_high / 2], [1], type='hilbert') Q = filtfilt(coefficients, 1, rf_in) # zero-phase envelope = np_sqrt(rf_in**2 + Q**2) b, a = butter(5, 0.25, btype='low') envelope_filtered = filtfilt(b, a, envelope, axis=0, padtype='odd', padlen=3 * (max(len(b), len(a)) - 1)) envelope_filtered.clip(min=0, out=envelope_filtered) return envelope_filtered
def DIFFman(self, fil_dict): self._get_params(fil_dict) if not self._test_N(): return -1 self.N = ceil_even(self.N) # enforce even order self._save(fil_dict, sig.remez(self.N,[0, self.F_PB],[np.pi*fil_dict['W_PB']], Hz = 1, type = 'differentiator', grid_density = self.grid_density))
def LPmin(self, fil_dict): self._get_params(fil_dict) (self.N, F, A, W) = remezord([self.F_PB, self.F_SB], [1, 0], [self.A_PB, self.A_SB], Hz = 1, alg = self.alg) fil_dict['W_PB'] = W[0] fil_dict['W_SB'] = W[1] self._save(fil_dict, sig.remez(self.N, F, [1, 0], weight = W, Hz = 1, grid_density = self.grid_density))
def test_compare(self): # test comparison to MATLAB k = [0.024590270518440, -0.041314581814658, -0.075943803756711, -0.003530911231040, 0.193140296954975, 0.373400753484939, 0.373400753484939, 0.193140296954975, -0.003530911231040, -0.075943803756711, -0.041314581814658, 0.024590270518440] h = remez(12, [0, 0.3, 0.5, 1], [1, 0], Hz=2.) assert_allclose(h, k) h = [-0.038976016082299, 0.018704846485491, -0.014644062687875, 0.002879152556419, 0.016849978528150, -0.043276706138248, 0.073641298245579, -0.103908158578635, 0.129770906801075, -0.147163447297124, 0.153302248456347, -0.147163447297124, 0.129770906801075, -0.103908158578635, 0.073641298245579, -0.043276706138248, 0.016849978528150, 0.002879152556419, -0.014644062687875, 0.018704846485491, -0.038976016082299] assert_allclose(remez(21, [0, 0.8, 0.9, 1], [0, 1], Hz=2.), h)
def LPman(self, fil_dict): self._get_params(fil_dict) if not self._test_N(): return -1 self._save(fil_dict, sig.remez(self.N,[0, self.F_PB, self.F_SB, 0.5], [1, 0], weight = [fil_dict['W_PB'],fil_dict['W_SB']], Hz = 1, grid_density = self.grid_density))
def __init__(self, numtaps, bands, gains, fs, num_channels = 4): self.numtaps = numtaps self.fs = fs self.num_channels = num_channels self.b = signal.remez(numtaps, bands, gains, Hz = fs)[::-1] self.x = np.zeros((num_channels,numtaps))
def HILman(self, fil_dict): self._get_params(fil_dict) if not self._test_N(): return -1 self._save(fil_dict, sig.remez(self.N,[0, self.F_SB, self.F_PB, self.F_PB2, self.F_SB2, 0.5],[0, 1, 0], weight = [fil_dict['W_SB'],fil_dict['W_PB'], fil_dict['W_SB2']], Hz = 1, type = 'hilbert', grid_density = self.grid_density))
def _design_filter(self, FS): if not FS in self._coefs_cache: bands = [0, min(self.fs, self.fp), max(self.fs, self.fp), FS / 2] gains = [int(self.fp < self.fs), int(self.fp > self.fs)] b, a = signal.remez(self.order, bands, gains, Hz=FS), [1] self._coefs_cache[FS] = (b, a) else: b, a = self._coefs_cache[FS] return b, a
def __init__(self, controller='/autobed_height_controller'): self.controller = controller self.goal_pub = rospy.Publisher(controller+'/command', JointTrajectory) self.state_sub = rospy.Subscriber(controller+'/state', JointTrajectoryControllerState, self.state_cb) self.joint_names = None self.physical_sub = rospy.Subscriber('/abdout0', FloatArrayBare, self.init_physical) #Low pass filter design self.bin_numbers = 5 self.bin_numbers_for_leg_filter = 21 self.collated_cal_angle = np.zeros((self.bin_numbers, 1)) self.collated_cal_angle_for_legs = np.zeros(( self.bin_numbers_for_leg_filter, 1)) self.filtered_angle = None self.lpf = remez(self.bin_numbers, [0, 0.1, 0.25, 0.5], [1.0, 0.0]) self.lpf_for_legs = remez(self.bin_numbers_for_leg_filter, [0, 0.0005, 0.1, 0.5], [1.0, 0.0])
def BPmin(self, fil_dict): self.get_params(fil_dict) (self.N, F, A, W) = pyfda_lib.remezord([self.F_SB, self.F_PB, self.F_PB2, self.F_SB2], [0, 1, 0], [self.A_SB, self.A_PB, self.A_SB2], Hz = 1, alg = self.alg) fil_dict['W_SB'] = W[0] fil_dict['W_PB'] = W[1] fil_dict['W_SB2'] = W[2] self.save(fil_dict, sig.remez(self.N,F,[0, 1, 0], weight = W, Hz = 1, grid_density = self.grid_density))
def fircoef(L: int, fc: float, fs: int) -> np.ndarray: """ remez uses normalized frequency, where 0.5 is Nyquist frequency fc: corner frequency [Hz] """ fcn = fc / (0.5*fs) return signal.remez(L, [0, 0.6*fcn, fcn, 0.5], [0, 1])
def amfm_CCA(im): """ Channel component analysis for AM-FM Input - im : 1d vector that contains a time series Output - ia : Instantaneous amplitude computed for 3 channels - ip : Instantaneous phase computed for 3 channels - ifeq: Instantaneous frequency computed for 3 channels """ # Filter bank bp = [ ] # Low pass 0 0.02 bp.append(ss.remez(50, [0, 0.02, 0.05, 0.5], [1,0])) # Pass band 0.02 0.25 bp.append(ss.remez(50, [0, 0.02, 0.05, 0.20, 0.25, 0.5], [0, 1, 0])) # High pass 0.25 0.5 bp.append(ss.remez(50, [0, 0.20, 0.25, 0.5], [0, 1], type = "hilbert")) # apply filterbank filt = lambda x: ss.convolve(im,x,'same') in_channels = map(filt,bp) # compute IA, IP and IF from filterbank output out_channels = map(qea,in_channels) # Organize results into a matrix of channels by time points ia = [] ip = [] ifeq = [] for chan in out_channels: ia.append(chan[0]) ip.append(chan[1]) ifeq.append(chan[2]) ia = np.array(ia) ip = np.array(ip) ifeq = np.array(ifeq) return(ia,ip,ifeq)
def filter_data(self): '''Creates a low pass filter to filter out high frequency noise''' lpf = remez(self.bin_numbers, [0, 0.05, 0.1, 0.5], [1.0, 0.0]) filt_data = np.zeros(self.num_sensors) for i in xrange(self.num_sensors): with self.frame_lock: if np.shape(lpf) == np.shape(self.raw_dat_array[:,i]): filt_data[i] = np.dot(lpf, self.raw_dat_array[:,i]) else: pass return filt_data
def BSmin(self, fil_dict): self._get_params(fil_dict) (N, F, A, W) = remezord([self.F_PB, self.F_SB, self.F_SB2, self.F_PB2], [1, 0, 1], [self.A_PB, self.A_SB, self.A_PB2], Hz = 1, alg = self.alg) self.N = round_odd(N) # enforce odd order fil_dict['W_PB'] = W[0] fil_dict['W_SB'] = W[1] fil_dict['W_PB2'] = W[2] self._save(fil_dict, sig.remez(self.N,F,[1, 0, 1], weight = W, Hz = 1, grid_density = self.grid_density))