def butter_bandpass_filter(data, cutoffs=[0.5, 3], fs=125.0, order=5): # data, cutoff frequency, sampling frequency, butterworth filter order b, a = butter_pass(cutoffs[1], fs, order=order, btype="low") data_lp = lfilter(b, a, data) b, a = butter_pass(cutoffs[0], fs, order=order, btype="high") data_hp = lfilter(b, a, data_lp) return data_hp
def _process_data(self, pattern, data, timestamps): """ Inherited from DataConsumer. Buffers the incoming signal and returns the filtered data to the blackboard """ for d, t in zip(data, timestamps): self._buffer.append(d) self._buffer = self._buffer[-len(self._coefficients):] result = lfilter(self._coefficients, 1, self._buffer)[-1] self.blackboard.put_data(pattern + self._pat_extension, result, t)
def test_elementwise_lfilter(self): """ Test whether our method of elementwise processing yields the same results as processing a whole signal at once """ fir = FIRFilter( self.bb, self.pattern, 33, 256, 75, 'lpf' ) a = 1 sig = [ randint(0,1024) for _ in range(256) ] result = lfilter( fir.get_coefficients(), a, sig, axis=0 ) result2 = [] buf = [] for s in sig: buf.append(s) buf = buf[-33:] result2.append(lfilter( fir.get_coefficients(), a, buf )[-1] ) self.assertEqual( len(result), len(result2), 'Results should be equal length') self.assertEqual( sum([ abs( x-y ) for x,y in zip(result, result2 ) ]), 0, 'Results should be equal value')
def lfilter_filter(df: DataFrame) -> DataFrame: b, a = butter(2, 0.1) sample_header_names = [ h.name for h in process_header_data(df, HeaderType.SAMPLE) ] lfilter_func = lambda x: lfilter(b, a, x) df[sample_header_names] = df[sample_header_names].transform(lfilter_func) return df
def _process_data(self, pattern, data, timestamps ): """ Inherited from DataConsumer. Buffers the incoming signal and returns the filtered data to the blackboard """ for d,t in zip(data,timestamps): self._buffer.append(d) self._buffer = self._buffer[-len(self._coefficients):] result = lfilter( self._coefficients, 1, self._buffer )[-1] self.blackboard.put_data(pattern+self._pat_extension, result, t )
def test_elementwise_lfilter(self): """ Test whether our method of elementwise processing yields the same results as processing a whole signal at once """ fir = FIRFilter(self.bb, self.pattern, 33, 256, 75, 'lpf') a = 1 sig = [randint(0, 1024) for _ in range(256)] result = lfilter(fir.get_coefficients(), a, sig, axis=0) result2 = [] buf = [] for s in sig: buf.append(s) buf = buf[-33:] result2.append(lfilter(fir.get_coefficients(), a, buf)[-1]) self.assertEqual(len(result), len(result2), 'Results should be equal length') self.assertEqual(sum([abs(x - y) for x, y in zip(result, result2)]), 0, 'Results should be equal value')
def create_AR_noise(bold_shape, v_noise, order=2, v_corr=0.1): noise = np.random.randn(*bold_shape) nbVox = bold_shape[1] length = bold_shape[0] noiseMean = np.zeros(nbVox, dtype=float) noiseVar = v_noise * np.random.rand(nbVox) ARorder = order noiseARp = v_corr * (np.ones((nbVox, ARorder), dtype=float) + np.random.rand(nbVox, ARorder)) for v in xrange(nbVox): tmp = np.sqrt(noiseVar[v]) * np.random.randn(length) + noiseMean[v] ARArray = np.concatenate(([1], -noiseARp[v, :])) noise[:, v] = lfilter([1], ARArray, tmp) return noise
def create_AR_noise(bold_shape, v_noise, order=2, v_corr=0.1): noise = np.random.randn(*bold_shape) nbVox = bold_shape[1] length = bold_shape[0] noiseMean = np.zeros(nbVox, dtype=float) noiseVar = v_noise * np.random.rand(nbVox) ARorder = order noiseARp = v_corr * (np.ones( (nbVox, ARorder), dtype=float) + np.random.rand(nbVox, ARorder)) for v in xrange(nbVox): tmp = np.sqrt(noiseVar[v]) * np.random.randn(length) + noiseMean[v] ARArray = np.concatenate(([1], -noiseARp[v, :])) noise[:, v] = lfilter([1], ARArray, tmp) return noise
def sgolayfilt(x, p, n): x = array(x, float32).ravel() size = len(x) if size < n: raise Exception, "'sgolayfilt': insufficient data for filter" # # The first k rows of F are used to filter the first k points # # of the data set based on the first n points of the data set. # # The last k rows of F are used to filter the last k points # # of the data set based on the last n points of the dataset. # # The remaining data is filtered using the central row of F. F = sgolay(p, n) k = int(n / 2) # z = filter(F(k+1,:), 1, x); z = lfilter(F[k], 1, x) # y = [ F(1:k,:)*x(1:n,:) ; z(n:len,:) ; F(k+2:n,:)*x(len-n+1:len,:) ]; left = dot(take(F, arange(k), 0), take(x, arange(n), 0)) right = dot(take(F, arange(k + 1, n), 0), take(x, arange(size - n, size), 0)) middle = take(z, arange(n - 1, size)) return concatenate((left, middle, right))
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) yf_fir, zf = lfilter(b_fir, a_fir, y, zi=np.zeros(max(len(a_fir), len(b_fir)) - 1)) yf_iir, zf = lfilter(b_iir, a_iir, y, zi=np.zeros(max(len(a_iir), len(b_iir)) - 1)) impulse = np.zeros(N) impulse[N / 2] = 1. yf_imp_fir, zf = lfilter(b_fir, a_fir, impulse, zi=np.zeros(max(len(a_fir), len(b_fir)) - 1)) yf_imp_iir, zf = lfilter(b_iir, a_iir, impulse,
def filter(self, data): import scipy.signal.signaltools as st res = st.lfilter(self.b, self.a, data, zi=self.ic) self.ic = res[-1] return res[0]
yt = irfft(rfft(x[i:il], n=N)*bf, n=N) # compute the convolution on the segment k = min(i+N, Nx) y[i:k] += yt[:k-i] # add the overlapped output blocks i += L #check if we have enough samples available #and compute number of fft to be done zf = 0. return y, zf import time t0 = time.time() yf_fir, zf = lfilter(b_fir, a_fir, y, zi=zeros(max(len(a_fir),len(b_fir))-1)) t1 = time.time() yf_fir_oa, zf = fft_overlap_add_lfilter(b_fir, y, zi=zeros(max(len(a_fir),len(b_fir))-1)) t2 = time.time() tlin = t1 - t0 toa = t2 - t1 print("lin", tlin, "o-a", toa, "lin/o-a", tlin/toa) impulse = zeros(N); impulse[0] = 1. yf_imp_fir, zf = lfilter(b_fir, a_fir, impulse, zi=zeros(max(len(a_fir),len(b_fir))-1)) yf_imp_fir_oa, zf = fft_overlap_add_lfilter(b_fir, impulse, zi=zeros(max(len(a_fir),len(b_fir))-1)) #yf_imp_iir, zf = lfilter(b_iir, a_iir, impulse, zi=zeros(max(len(a_iir),len(b_iir))-1)) clf() subplot(311)
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()
y = window * sin(2 * pi * x * f) pbrip = .5 sbrip = 50 order = 2 fi = 63.41 flow = 62.5 fhigh = 64.33 wi = fi / (fs / 2.) wlow = flow / (fs / 2.) whigh = fhigh / (fs / 2.) w = [wlow, whigh] [b, a] = ellip(order, pbrip, sbrip, w, btype='bandpass') #cheb1ord(wp, ws, 1., sbrip) #cheby1(N, rp, Wn, btype='low', analog=0, output='ba') yf = lfilter(b, a, y) yf2 = lfilter(b, a, yf) clf() subplot(211) plot(x, y) plot(x, yf) plot(x, yf2) subplot(212) loglog( fftshift(fftfreq(N, 1. / fs))[N / 2:], fftshift(abs((fft(y)))**2)[N / 2:]) loglog( fftshift(fftfreq(N, 1. / fs))[N / 2:], fftshift(abs((fft(yf)))**2)[N / 2:]) ylim(ymin=1e-6)
def filter(self, data): res = st.lfilter(self.b, self.a, data, zi=self.ic) self.ic = res[-1] return res[0]
def default_filt(b, a, x, Z): return lfilter(b, a, x, zi=Z)
#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() yf_imp_lfilter, zf = lfilter(b, a, impulse, zi=z)#, zi=zeros(max(len(a_full),len(b_full))-1)) t1 = time.time() print("scipy", t1-t0) t0 = time.time() yf_imp_handmade, zf = pure_lfilter_float64_1D(b, a, impulse, z) t1 = time.time() print("pure", t1-t0) t0 = time.time() yf_imp_pyx, zf_pyx = pyx_lfilter_float64_1D(b, a, impulse, z) t1 = time.time() print("cython", t1-t0) N2 = 100 N3 = 100
def __init__(self, file_data, ca_timeconstant, frame_rate, scan_frame_length=None): """ Creates a new TailData object Args: file_data: Matrix loaded from tailfile ca_timeconstant: Timeconstant of calcium indicator used during experiments frame_rate: The tail camera acquisition framerate scan_frame_length: For more accurate alignment the time it took to acquire each 2P scan frame in seconds """ self.scanning = file_data[:, 0] == 1 self.scan_frame = file_data[:, 1].astype(int) self.scan_frame[np.logical_not(self.scanning)] = -1 # after the last frame is scanned, the scanImageIndex will be incremented further # and the isScanning indicator will not immediately switch off. Therefore, if # the highest index frame has less than 75% of the average per-index frame-number # set it to -1 as well c = Counter(self.scan_frame[self.scan_frame != -1]) avg_count = np.median(list(c.values())) max_frame = np.max(self.scan_frame) if np.sum(self.scan_frame == max_frame) < 0.75 * avg_count: self.scan_frame[self.scan_frame == max_frame] = -1 self.cumAngles = np.rad2deg(file_data[:, 2]) self.ca_original = self.cumAngles.copy() self.remove_track_errors() self.vigor = comp_vigor(self.cumAngles, 80 // (1000 / frame_rate)) # compute vigor bout threshold t = np.mean(self.vigor[self.vigor < 25]) + 3 * np.std( self.vigor[self.vigor < 25]) print(f"Vigor threshold = {t}") self.bouts = detect_tail_bouts(self.cumAngles, self.vigor, min_frames=80 // (1000 / frame_rate), threshold=t, frame_rate=frame_rate) if self.bouts is not None and self.bouts.size == 0: self.bouts = None if self.bouts is not None: bs = self.bouts[:, 0].astype(int) self.boutFrames = self.scan_frame[bs] else: self.boutFrames = [] self.ca_kernel = TailData.ca_kernel(ca_timeconstant, frame_rate) self.ca_timeconstant = ca_timeconstant # try to compute frame-rate from timestamps in the tail-data if they are present # use heuristics to determine if the 4th column (index 3) contains timestamp data putative_ts = file_data[:, 3] if np.all(np.diff(putative_ts) > 0) and np.mean(putative_ts) > 1e9: all_frame_times_ms = np.diff( putative_ts) / 1_000_000 # timestamp in ns frame_time_ms = np.median(all_frame_times_ms) print( f"Found timestamp information in tail file. Median time between frames is " f"{np.round(frame_time_ms, 2)}ms") print( f"99th percentile time between frames is {np.round(np.percentile(all_frame_times_ms, 99), 2)}ms" ) self.frame_rate = int(1000 / frame_time_ms) print(f"Set tail camera frame-rate to {self.frame_rate} Hz") else: print("Did not find timestamp information in tail file.") self.frame_rate = frame_rate putative_ts = None # compute tail velocities based on 10-window filtered cumulative angle trace fca = lfilter(np.ones(10) / 10, 1, self.cumAngles) self.velocity = np.hstack((0, np.diff(fca))) self.velcty_noise = np.nanstd(self.velocity[self.velocity < 4]) # compute a time-trace assuming a constant frame-rate which starts at 0 # for the likely first camera frame during the first acquisition frame # we infer this frame by going back avgCount frames from the first frame # of the second (!) scan frame (i.e. this should then be the first frame # of the first scan frame) frames = np.arange(self.cumAngles.size) first_frame = np.min( frames[self.scan_frame == 1]) - avg_count.astype(int) # remove overhang from frame 0 call self.scan_frame[:first_frame] = -1 if scan_frame_length is not None and putative_ts is not None: # We will use the camera timestamp to assign sequential frame-times # To transform the timing information into a time relative to the scan-frame # times we extract the likely scan time for each camera frame that is in the middle # of each scan frame. Then we pick the median suggested start time based on these key- # frame times timestamp_first_frame = putative_ts[0] start_times = [] for i in range(self.scan_frame.max()): if np.sum(self.scan_frame == i) < 1: continue # compute index of the camera frame in the middle of the current scan frame ix_key = int(np.mean(frames[self.scan_frame == i])) # based on how long it takes to scan a frame, compute the approximate scan time at the key-frame key_time = scan_frame_length / 2 + scan_frame_length * i # compute the relative scan time of the first camera frame based on the key time camera_delta = (putative_ts[ix_key] - timestamp_first_frame) / 1e9 start_times.append(key_time - camera_delta) likely_start_time = np.median(start_times) self.frame_time = (putative_ts - timestamp_first_frame) / 1e9 + likely_start_time else: frames -= first_frame self.frame_time = (frames / frame_rate).astype(np.float32) # create bout-start trace at original frame-rate self.starting = np.zeros_like(self.frame_time) if self.bouts is not None: bout_starts = self.bouts[:, 0].astype(int) # since we potentially clip our starting trace to the last valid frame-time (experiment end) # we also only include bout-starts that occured up to that index bout_starts = bout_starts[bout_starts < self.frame_time.size] self.starting[bout_starts] = 1
#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() yf_imp_lfilter, zf = lfilter( b, a, impulse, zi=z) #, zi=zeros(max(len(a_full),len(b_full))-1)) t1 = time.time() print("scipy", t1 - t0) t0 = time.time() yf_imp_handmade, zf = pure_lfilter_float64_1D(b, a, impulse, z) t1 = time.time() print("pure", t1 - t0) t0 = time.time() yf_imp_pyx, zf_pyx = pyx_lfilter_float64_1D(b, a, impulse, z) t1 = time.time() print("cython", t1 - t0) N2 = 100 N3 = 100
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()
N = 2**13 fs = 44100. x = arange(0,N)/fs f = 63.4 Nw = 2**13 window = zeros(N) window[:Nw] = hamming(Nw) y = window*sin(2*pi*x*f) pbrip = .5 sbrip = 50 order = 2 fi = 63.41 flow = 62.5 fhigh = 64.33 wi = fi/(fs/2.) wlow = flow/(fs/2.) whigh = fhigh/(fs/2.) w = [wlow, whigh] [b, a] = ellip(order, pbrip, sbrip, w, btype='bandpass') yf, zf = lfilter(b, a, y, zi=zeros(max(len(a),len(b))-1)) yf2, zf = lfilter(b, a, 0.*y, zi=zf) yf3, zf = lfilter(b, a, 0.*y, zi=zf) print(x[-1]+x, yf2) clf() subplot(211); plot(x,y); plot(x, yf); plot(x[-1]+x, yf2); plot(2*x[-1]+x, yf3) subplot(212); loglog(fftshift(fftfreq(N,1./fs))[N/2:],fftshift(abs((fft(y)))**2)[N/2:]); loglog(fftshift(fftfreq(N,1./fs))[N/2:],fftshift(abs((fft(yf)))**2)[N/2:]); ylim(ymin=1e-6) show()
N = 2**15 fs = 44100. x = arange(0,N)/fs f = 63.4 Nw = 2**13 window = zeros(N) window[:Nw] = hamming(Nw) y = window*sin(2*pi*x*f) pbrip = .5 sbrip = 50 order = 2 fi = 63.41 flow = 62.5 fhigh = 64.33 wi = fi/(fs/2.) wlow = flow/(fs/2.) whigh = fhigh/(fs/2.) w = [wlow, whigh] [b, a] = ellip(order, pbrip, sbrip, w, btype='bandpass') #cheb1ord(wp, ws, 1., sbrip) #cheby1(N, rp, Wn, btype='low', analog=0, output='ba') yf = lfilter(b, a, y) yf2 = lfilter(b, a, yf) clf() subplot(211); plot(x,y); plot(x, yf); plot(x, yf2) subplot(212); loglog(fftshift(fftfreq(N,1./fs))[N/2:],fftshift(abs((fft(y)))**2)[N/2:]); loglog(fftshift(fftfreq(N,1./fs))[N/2:],fftshift(abs((fft(yf)))**2)[N/2:]); ylim(ymin=1e-6); loglog(fftshift(fftfreq(N,1./fs))[N/2:],fftshift(abs((fft(yf2)))**2)[N/2:]) show()
window = zeros(N) window[:Nw] = hamming(Nw) y = window * sin(2 * pi * x * f) pbrip = .5 sbrip = 50 order = 2 fi = 63.41 flow = 62.5 fhigh = 64.33 wi = fi / (fs / 2.) wlow = flow / (fs / 2.) whigh = fhigh / (fs / 2.) w = [wlow, whigh] [b, a] = ellip(order, pbrip, sbrip, w, btype='bandpass') yf, zf = lfilter(b, a, y, zi=zeros(max(len(a), len(b)) - 1)) yf2, zf = lfilter(b, a, 0. * y, zi=zf) yf3, zf = lfilter(b, a, 0. * y, zi=zf) print x[-1] + x, yf2 clf() subplot(211) plot(x, y) plot(x, yf) plot(x[-1] + x, yf2) plot(2 * x[-1] + x, yf3) subplot(212) loglog( fftshift(fftfreq(N, 1. / fs))[N / 2:], fftshift(abs((fft(y)))**2)[N / 2:])