def generate(self, sigLenSecs): # notation for this method f0 = self.getParam("cf") Q = self.getParam("Q") # pop specific parameters length = round(sigLenSecs * self.sr) # in samples ticksamps = 3 # number of noise samples to use before filtering krms = 0.6 tick = 2 * np.random.rand(ticksamps) - 1 #noise samples in [-1,1] tick = np.pad(tick, (0, length - ticksamps), 'constant') # Design peak filter b, a = signal.iirpeak(f0, Q, self.sr) #use it tick = signal.lfilter(b, a, tick) if False: #print("original rms={}".format(math.sqrt(sum([x*x/ticksamps for x in tick])))) c = math.sqrt(ticksamps * krms * krms / sum([(x * x) for x in tick])) tick = [c * x for x in tick] #print("new rms={}".format(math.sqrt(sum([x*x/ticksamps for x in tick])))) else: maxfsignal = max(abs(tick)) tick = tick * .9 / maxfsignal return tick
def build_filter_resp(f, q, b=np.array([1]), a=np.array([1])): if len(f) == 0: return (b, a) b_, a_ = signal.iirpeak(f[0], q[0], fs=1) b = np.convolve(b, b_) a = np.convolve(a, a_) return build_filter_resp(f[1:], q[1:], b, a)
def filt_iirpeak(dic, fs, f0, Q, plot=False): w0 = f0 / (fs / 2) num, den = signal.iirpeak(w0, Q) data = {key: signal.lfilter(num, den, dic[key]) for key in dic.keys()} if plot == True: w, h = signal.freqz(num, den, worN=10000) freq = w * fs / (2 * np.pi) fig, ax = plt.subplots(2, 1, figsize=(8, 6)) ax[0].semilogx(freq, 20 * np.log10(abs(h)), color='blue') ax[0].set_title("Frequency Response") ax[0].set_ylabel("Amplitude (dB)", color='blue') #ax[0].set_xlim([0, 100]) #ax[0].set_ylim([-50, 10]) ax[0].grid() ax[1].semilogx(freq, np.unwrap(np.angle(h)) * 180 / np.pi, color='green') ax[1].set_ylabel("Angle (degrees)", color='green') ax[1].set_xlabel("Frequency (Hz)") #ax[1].set_xlim([0, 100]) #ax[1].set_yticks([-90, -60, -30, 0, 30, 60, 90]) #ax[1].set_ylim([-90, 90]) ax[1].grid() plt.savefig('hoge.png') plt.close() return data
def analyze(self, plot=False, wavfilename=None): # narrowband filter the data around the expected peak. fnaught = self.field_to_freq(self.expected_field) Q = 60.0 w0 = fnaught / (self.fs / 2) # normalized b, a = signal.iirpeak(w0, Q) self.a1f = signal.filtfilt(b, a, self.a1) # FIXME - we should truncate the beginning and end that are subject to filter startup, so they don't throw off # the harmonic inversion decay calculation if wavfilename != None: self.save_wavfile(wavfilename) # Use FDM harmonic inversion to calculate a set of frequencies in this band self.signals = harminv.invert(self.a1f, fmin=1000, fmax=3000, dt=1.0 / self.fs) # Select best candidate signal, or None if we couldn't find one self.fdm = self.select_candidate(self.signals) if self.fdm == None: return None, None, 0.0, 0.0 self.fdm_time_constant = 1.0 / self.fdm.decay self.field = self.freq_to_field(self.fdm.frequency) # See http://www.gellerlabs.com/PMAG%20Docs.htm # Like GellerLabs, compute an SNR which is 20 log (FID amplitude / RMS_Sum(other inband amplitudes)) # This doesn't appear to be very meaningful, based on the way FDM works. We should compute this differently. rms_sum = 0 for s in self.signals: # restrict to narrow band if s.frequency >= self.expected_freq_low and s.frequency <= self.expected_freq_high and \ s.frequency != self.fdm.frequency: rms_sum += (s.amplitude**2) self.fdm_snr = 20.0 * np.log10(self.fdm.amplitude / np.sqrt(rms_sum)) # GellerLabs calls the FDM error the Figure of Merit. # Shouldn't be converted to nT, as harminv says 'error is not really error bars on frequency' self.fom_nt = self.freq_to_field(self.fdm.error * self.fdm.frequency) if self.verbose > 0: print "FDM SNR (dB)", self.fdm_snr, "FOM", self.fdm.error if plot: #self.plot_results() self.multiplot_results() return self.field, self.fdm, self.fom_nt, self.fdm_snr
def peak_filtering(wav, fs, w0, Q): """ Apply a notch (band-stop) filter to the audio signal. Args: wav: Waveform. fs: Sampling frequency of the waveform. w0: See scipy.signal.iirnotch. Q: See scipy.signal.iirnotch. Returns: wav: Filtered waveform. """ b, a = signal.iirpeak(2 * w0 / fs, Q) wav = signal.lfilter(b, a, wav) return wav
def iirpeak(w0: float, bw: float) -> Tuple: """ Design second-order IIR peak (resonant) digital filter. A peak filter is a band-pass filter with a narrow bandwidth (high quality factor). It rejects components outside a narrow frequency band. Caution : This function is not supported variable magnitude response. Parameters ---------- w0 : float Peak frequency, specified as a positive scalar in the range 0.0 < w0 < 1.0, where 1.0 corresponds to π radiance per sample in the frequency range. bw : float Bandwidth at the –3 dB point, specified as a positive scalar in the range 0.0 < w0 < 1.0. Returns ------- system :a tuple of array_like describing the system. The following gives the number of elements in the tuple and the interpretation: * (num, den) """ if (type(w0) in [float, np.float, np.float16, np.float32, np.float64]) == False: raise ValueError("`w0` must be a float.") if (type(bw) in [float, np.float, np.float16, np.float32, np.float64]) == False: raise ValueError("`bw` must be a float.") # Calcurate quality factor Q = w0 / bw num, den = signal.iirpeak(w0, Q, fs=2.0) return num, den
def _hbEQFilter(tempo, fs, unfilteredHeartbeat): """ Filters heartbeats to mimic the effect of typical heartbeat recordings which are taken with a microphone near the abdomen. @tempo int The tempo for the heartbeat to exist @fs int Sample rate of the the file @unfilteredHeartbeat bool Specifies the inclusion of the S3 abnormality @returns [int] The filtered heartbeat. """ # Butterworth 3rd order bandpass frequencyArray = [ x / (0.4*fs) for x in [20, 140+tempo] ] [bBut, aBut] = butter(3, frequencyArray, 'bandpass') # Peaking filter [bPeak, aPeak] = iirpeak((110/(fs/2)), (120/(0.5*fs))) # Filter the pulse to simulate an abdomen return lfilter(bPeak, aPeak, lfilter(bBut, aBut, unfilteredHeartbeat))
def peak_iir_filter(sig, freq=2500, q=3): # this is signal.iirpeak function b, a = signal.iirpeak(freq, q, sr) filtered_sig = signal.lfilter(b, a, sig) return filtered_sig
depth = 2 # factor Q, filter iirpeak # crear una onda triangular con los valores de frecuencias long = 1024*107 fc = [] while (len(fc)< (long)): fc = np.append(fc, np.arange(cut_min, cut_max, delta)) fc = np.append(fc, np.arange(cut_max, cut_min, -delta)) # quitamos lo que sobra fc = fc[:long] # 109568 # fc es el LFO # ahora calculamos los parámetros del filtro bs= np.zeros(long*3)# [] ais = np.zeros(long*3)#np.zeros(3) for i in range(long): b, a = iirpeak(fc[i]/(RATE/2), depth) for h in range(3): bs[(i*3)+h] = b[h] ais[(i*3)+h] = a[h] print('len lfo ', len(fc)) print('b ', len(bs), ' a', len(ais)) #plt.plot(fc) #plt.show() y = np.zeros(1024) ind = 0 # llegará hasta 328704 = 3 x 109568 long pa= pyaudio.PyAudio() def callback(in_data, frame_count, time_info, status): # convert data to array
def peak_filter(input_signal, fc, fs, Q): b, a = signal.iirpeak(fc, Q, fs) filtered_signal = signal.filtfilt(b, a, input_signal) return filtered_signal
# Design and plot filter to remove the frequencies other than the 300 Hz # component from a signal sampled at 1000 Hz, using a quality factor Q = 30 from scipy import signal import matplotlib.pyplot as plt fs = 1000.0 # Sample frequency (Hz) f0 = 300.0 # Frequency to be retained (Hz) Q = 30.0 # Quality factor # Design peak filter b, a = signal.iirpeak(f0, Q, fs) # Frequency response freq, h = signal.freqz(b, a, fs=fs) # Plot fig, ax = plt.subplots(2, 1, figsize=(8, 6)) ax[0].plot(freq, 20 * np.log10(np.maximum(abs(h), 1e-5)), color='blue') ax[0].set_title("Frequency Response") ax[0].set_ylabel("Amplitude (dB)", color='blue') ax[0].set_xlim([0, 500]) ax[0].set_ylim([-50, 10]) ax[0].grid() ax[1].plot(freq, np.unwrap(np.angle(h)) * 180 / np.pi, color='green') ax[1].set_ylabel("Angle (degrees)", color='green') ax[1].set_xlabel("Frequency (Hz)") ax[1].set_xlim([0, 500]) ax[1].set_yticks([-90, -60, -30, 0, 30, 60, 90]) ax[1].set_ylim([-90, 90]) ax[1].grid() plt.show()
import soundfile as sf # filter för en given knappkombination overtones = [3/4, 1, 3/2] + list(range(2, 9)) # insignal x, fs = sf.read(r'Z:\Användarmappar\Fredrik\brussvep.wav') f0 = 233.082 # Frequency to be retained (Hz) (Bb3) Q = 200.0 # Quality factor w0 = f0/(fs/2) # Normalized Frequency print('sample rate: {}'.format(fs)) fig, ax = plt.subplots(2, 1, figsize=(8, 6)) # Design peak filters for ii, factor in enumerate(overtones): b, a = signal.iirpeak(w0 * factor, Q) if ii == 0: y = signal.lfilter(b, a, x) else: y = signal.lfilter(b, a, y) # normalisera (nivån sjunker lite för varje filtrering) y = .997 * y / np.linalg.norm(y) # Frequency response w, h = signal.freqz(b, a) # Generate frequency axis freq = w*fs/(2*np.pi) # Plot ax[0].semilogx(freq, 20*np.log10(abs(h)), color='blue') ax[1].semilogx(freq, np.unwrap(np.angle(h)) * 180 / np.pi, color='green')
def test_iirpeak_1(self): # Test case IIR = IIRDesign.iirpeak(self.w0, self.bw) iir = signal.iirpeak(self.w0, self.w0 / self.bw, fs=2) self.assertTrue(np.all(IIR[0] == iir[0]) and np.all(IIR[1] == iir[1]))
# Design and plot filter to remove the frequencies other than the 300Hz # component from a signal sampled at 1000Hz, using a quality factor Q = 30 from scipy import signal import numpy as np import matplotlib.pyplot as plt fs = 1000.0 # Sample frequency (Hz) f0 = 300.0 # Frequency to be retained (Hz) Q = 30.0 # Quality factor w0 = f0 / (fs / 2) # Normalized Frequency # Design peak filter b, a = signal.iirpeak(w0, Q) # Frequency response w, h = signal.freqz(b, a) # Generate frequency axis freq = w * fs / (2 * np.pi) # Plot fig, ax = plt.subplots(2, 1, figsize=(8, 6)) ax[0].plot(freq, 20 * np.log10(abs(h)), color='blue') ax[0].set_title("Frequency Response") ax[0].set_ylabel("Amplitude (dB)", color='blue') ax[0].set_xlim([0, 500]) ax[0].set_ylim([-50, 10]) ax[0].grid() ax[1].plot(freq, np.unwrap(np.angle(h)) * 180 / np.pi, color='green') ax[1].set_ylabel("Angle (degrees)", color='green') ax[1].set_xlabel("Frequency (Hz)") ax[1].set_xlim([0, 500]) ax[1].set_yticks([-90, -60, -30, 0, 30, 60, 90])
depth = 2 # factor Q, filter iirpeak fw/fs # crear una onda triangular con los valores de frecuencias fc = [] while (len(fc) < len(data)): fc = np.append(fc, np.arange(cut_min, cut_max, delta)) fc = np.append(fc, np.arange(cut_max, cut_min, -delta)) # quitamos lo qe sobra fc = fc[:len(data)] # fc es el LFO y = np.zeros(len(data)) for i in range(2, len(data)): b, a = iirpeak(fc[i] / (fs / 2), depth) y[i] = (b[0] * data[i] + b[1] * data[i - 1] + b[2] * data[i - 2] - a[1] * y[i - 1] - a[2] * y[i - 2]) gain = 0.8 yout = (1 - gain) * data + gain * y # write wav file try: wavfile.write('/home/josemo/python/wavfiles/wahwah2.wav', fs, yout.astype(np.int16)) #print('Escritura de archivo correcta') except IOError as e: # # parent of IOError, OSError *and* WindowsError where available print('Error al escritura el archivo') print(e)
def peakAmplification(chosenSignal, outFr, f0, Q=2): b1, a1 = signal.iirpeak(f0, Q, outFr) peakFiltered = signal.filtfilt(b1, a1, chosenSignal.ravel()) b2, a2 = signal.iirpeak(f0 / 2, Q, outFr) harmonicFiltered = signal.filtfilt(b2, a2, chosenSignal.ravel()) return peakFiltered + harmonicFiltered
inpath = '../../fill/out/' outpath = '../out/' df = pd.read_csv(inpath + "Ta.csv", index_col=0, parse_dates=True) input_signal = df.loc[:,'C07'].resample('H').mean() #=============================================================================== # Example #=============================================================================== fs = 1000.0 # Sample frequency (Hz) f0 = 300.0 # Frequency to be retained (Hz) Q = 30.0 # Quality factor w0 = f0/(fs/2) # Normalized Frequency b, a = signal.iirpeak(w0, Q) # Design peak filter w, h = signal.freqz(b, a) # Frequency response freq = w*fs/(2*np.pi) # generate frequency axis plt.title('Digital filter frequency response') plt.plot(w, 20*np.log10(np.abs(h))) plt.title('Digital filter frequency response') plt.ylabel('Amplitude Response [dB]') plt.xlabel('Frequency (rad/sample)') plt.grid() plt.show() #=============================================================================== # Butter application #===============================================================================
def autowah(data, maximum, minimum, order=2, peak=True, Q=1, p=0.8, delay=0, fs=44100): """ This function apply a dynamic filter (or autowah) on a given signal. Parameters: data = A numpy array containg audio values between -1 and 1 maximum = The maximum value (in herz) the filter will cut too. Everything higher than that will always be cut. minimum = The minimum value (in herz) the filter will cut too. Everything lower than that will never be cut. order = The order of the IIR filter. 2 is fine. Try higher values if you want some weird techno-ish sounds peak = Boolean value. If set to false the filter will only be lowpass without the resonante component. Q = Quality factor of the peak. p = Height of the peak. It set to zero, equivalent to peak = False. Should be between 0 and 1 (included) delay = delay between the filter and the envelope. May give some weird result. fs = Sampling rate. Return : A numpy array containing the resulting audio signal, between 0 and 1. """ if (order < 2): raise ValueError("order must be at least 2") envelope = compute_envelope(data) Q = max(Q, 0.5) if peak and (p > 1 or p < 0): raise ValueError("p must be between 0 and 1") y = np.zeros(len(data) + order + 1) z = np.zeros( len(data) + order + 1 ) # Create the y (order + 1 zeros at the begining to compute the 1st values...) if delay > 0: d = np.concatenate((np.zeros(order + 1 + int(delay * fs)), data)) # add padded zeros at the beginning else: d = np.concatenate( (np.zeros(order + 1), data, np.zeros(int(-delay * fs)))) # add padded zeros at the beginning envelope = np.concatenate((np.zeros(order + 1), envelope)) vals_b = np.zeros(order + 1) vals_a = np.zeros(order + 1) for i in range( order + 1, len(y)): # begin at order+1 since we must use previous values (0) if (i % 100 == order + 1): cutoff = envelope[i] * (maximum - minimum) / fs * 2 + minimum / fs * 2 b, a = sgn.iirfilter(N=order, Wn=(cutoff), rp=30, rs=60, btype='lowpass', analog=False, ftype='butter', output='ba') for j in range(0, order + 1): # Compute X of the tranfer function vals_b[j] = b[j] * d[i - j] for j in range(1, order + 1): # Compute Y of the tranfer function vals_a[j] = a[j] * y[i - j] y[i] = (1 / a[0]) * (np.sum(vals_b) - np.sum(vals_a) ) # Transfer function if peak: for i in range(3, len(z)): if (i % 100 == 3): # sinon trop lent cutoff = envelope[i] * (maximum - minimum) / fs * 2 + minimum / fs * 2 b2, a2 = sgn.iirpeak(cutoff, Q) for j in range(0, 3): # Compute X of the tranfer function vals_b[j] = b2[j] * y[i - j] for j in range(1, 3): # Compute Y of the tranfer function vals_a[j] = a2[j] * z[i - j] z[i] = (1 / a[0]) * (np.sum(vals_b) - np.sum(vals_a) ) # Transfer function y = p * z + (1 - p) * y return y / np.max(abs(y))
import numpy as np from scipy import signal import subprocess import filters from scipy import interpolate f0=0.4 f1=0.0001 q0=300 q1=300 b0,a0=signal.iirpeak(f0,q0,fs=1) r0,c0=filters.b_a_to_r_c(b0,a0) b1,a1=signal.iirpeak(f1,q1,fs=1) r1,c1=filters.b_a_to_r_c(b1,a1) N=100000 def get_interp(a0,a1): return interpolate.interp1d( [0,N], np.concatenate((a0[:,None],a1[:,None]),axis=1))(np.arange(N)) r=get_interp(r0,r1) c=get_interp(c0,c1) x=np.random.standard_normal(N).astype('float32') x.tofile('/tmp/in.f32') r=r.astype('float32') c=c.astype('float32') r.T.tofile('/tmp/r.f32') c.T.tofile('/tmp/c.f32') env=dict(P='%d'%(len(r),)) subprocess.run('src/test/bin/lattice_filter_proc',env=env)
def value_determined(self, event=None): sampling_rate = 44100.0 analog_b = np.poly1d([1]) analog_a = np.poly1d([1]) if self.switch_vars['LPB'].get() == True: analog_b *= [1] # Numerator analog_a *= [ 1 / self.convert_radian_z_to_s( 2 * np.pi * self.scales['LPB'].get() / sampling_rate), 1 ] # Denominator if self.switch_vars['LPS'].get() == True: l0 = 1.0 lpi = float(np.power(10.0, self.scales['LPS'].get() / -20.0)) analog_b *= [np.sqrt(l0 * lpi), l0] # Numerator analog_a *= [np.sqrt(l0 / lpi), 1] # Denominator if self.switch_vars['LPT'].get() == True: pole = (20.0 / sampling_rate) * 2.0 * np.pi zero = (20.0 / sampling_rate) * 2.0 * np.pi * pow( np.sqrt(10.0), self.scales['LPT'].get() / 20.0) for i in range(6): analog_b *= [1, self.convert_radian_z_to_s(zero)] analog_a *= [1, self.convert_radian_z_to_s(pole)] pole *= np.sqrt(10.0) zero *= np.sqrt(10.0) if self.switch_vars['HPB'].get() == True: analog_b *= [1, 0] # Numerator analog_a *= [ 1, self.convert_radian_z_to_s( 2 * np.pi * self.scales['HPB'].get() / sampling_rate) ] # Denominator if self.switch_vars['HPS'].get() == True: lpi = 1.0 l0 = float(np.power(10.0, self.scales['HPS'].get() / -20.0)) analog_b *= [np.sqrt(l0 * lpi), l0] # Numerator analog_a *= [np.sqrt(l0 / lpi), 1] # Denominator if self.switch_vars['HPT'].get() == True: pole = (20.0 / sampling_rate) * 2.0 * np.pi zero = (20.0 / sampling_rate) * 2.0 * np.pi / pow( np.sqrt(10.0), self.scales['HPT'].get() / 20.0) for i in range(6): analog_b *= [1, self.convert_radian_z_to_s(zero)] analog_a *= [1, self.convert_radian_z_to_s(pole)] pole *= np.sqrt(10.0) zero *= np.sqrt(10.0) (digital_b, digital_a) = signal.bilinear(analog_b.coeffs, analog_a.coeffs) digital_b = np.poly1d(digital_b) digital_a = np.poly1d(digital_a) for i in xrange(4): if self.switch_vars['PK' + str(i + 1)].get() == True: center_frequency = self.scales['PK' + str(i + 1)].get() band_width = self.scales['PK' + str(i + 1) + '-Width'].get() normalized_frequency = center_frequency / float( sampling_rate) * 2 Q = center_frequency / float(band_width) (pk_digital_b, pk_digital_a) = signal.iirpeak(normalized_frequency, Q) digital_b *= pk_digital_b digital_a *= pk_digital_a digital_b = digital_b.coeffs digital_a = digital_a.coeffs max_coeff = self.plot(digital_b, digital_a, sampling_rate) digital_b /= max_coeff self.main_ui.controller.digital_filter = { 'b': digital_b, 'a': digital_a }