def window(f,start,stop,type='blackman'): """ runs the data through a hamming window. @param f: The data matrix @param start: The start index of the hamming window. @param stop: The end index of the hamming window. """ h=numpy.zeros(f.shape,dtype=float) if len(h.shape)==1: if type=='hamming': h[start:stop]=signal.hamming(stop-start) elif type=='blackman': h[start:stop]=signal.blackman(stop-start) elif type=='hann': h[start:stop]=signal.hann(stop-start) elif type=='blackmanharris': h[start:stop]=signal.blackmanharris(stop-start) elif type=='rectangular' or type=='rect' or type=='boxcar': h[start:stop]=signal.boxcar(stop-start) else: if type=='hamming': h[:,start:stop]=signal.hamming(stop-start) elif type=='blackman': h[:,start:stop]=signal.blackman(stop-start) elif type=='hann': h[:,start:stop]=signal.hann(stop-start) elif type=='blackmanharris': h[:,start:stop]=signal.blackmanharris(stop-start) elif type=='rectangular' or type=='rect' or type=='boxcar': h[:,start:stop]=signal.boxcar(stop-start) return numpy.multiply(f,h)
def window(f, start, stop, type='blackman'): """ runs the data through a hamming window. @param f: The data matrix @param start: The start index of the hamming window. @param stop: The end index of the hamming window. """ h = numpy.zeros(f.shape, dtype=float) if len(h.shape) == 1: if type == 'hamming': h[start:stop] = signal.hamming(stop - start) elif type == 'blackman': h[start:stop] = signal.blackman(stop - start) elif type == 'hann': h[start:stop] = signal.hann(stop - start) elif type == 'blackmanharris': h[start:stop] = signal.blackmanharris(stop - start) elif type == 'rectangular' or type == 'rect' or type == 'boxcar': h[start:stop] = signal.boxcar(stop - start) else: if type == 'hamming': h[:, start:stop] = signal.hamming(stop - start) elif type == 'blackman': h[:, start:stop] = signal.blackman(stop - start) elif type == 'hann': h[:, start:stop] = signal.hann(stop - start) elif type == 'blackmanharris': h[:, start:stop] = signal.blackmanharris(stop - start) elif type == 'rectangular' or type == 'rect' or type == 'boxcar': h[:, start:stop] = signal.boxcar(stop - start) return numpy.multiply(f, h)
def test_basic(self): assert_allclose(signal.blackman(6, sym=False), [0, 0.13, 0.63, 1.0, 0.63, 0.13], atol=1e-14) assert_allclose(signal.blackman(6), [0, 0.2007701432625305, 0.8492298567374694, 0.8492298567374694, 0.2007701432625305, 0], atol=1e-14) assert_allclose(signal.blackman(7, True), [0, 0.13, 0.63, 1.0, 0.63, 0.13, 0], atol=1e-14)
def test_basic(self): assert_allclose(signal.blackman(6, sym=False), [0, 0.13, 0.63, 1.0, 0.63, 0.13], atol=1e-14) assert_allclose(signal.blackman(7, sym=False), [0, 0.09045342435412804, 0.4591829575459636, 0.9203636180999081, 0.9203636180999081, 0.4591829575459636, 0.09045342435412804], atol=1e-8) assert_allclose(signal.blackman(6), [0, 0.2007701432625305, 0.8492298567374694, 0.8492298567374694, 0.2007701432625305, 0], atol=1e-14) assert_allclose(signal.blackman(7, True), [0, 0.13, 0.63, 1.0, 0.63, 0.13, 0], atol=1e-14)
def get_SNR(self, t, hn, ht, fs): T = t[-1] - t[0] NFFT = int(fs / 4) # should be T*fs/8 to get a better background psd psd_window = np.blackman(NFFT) NOVL = int(NFFT / 2) dt = t[1] - t[0] template = ht + ht * 1.j datafreq = np.fft.fftfreq(template.size) * fs df = np.abs(datafreq[1] - datafreq[0]) try: dwindow = signal.tukey(template.size, alpha=1. / 8) # Tukey window preferred, but requires recent scipy version except: dwindow = signal.blackman(template.size) # Blackman window OK if Tukey is not available template_fft = np.fft.fft(template * dwindow) / fs data = hn.copy() data_psd, freqs = mlab.psd(data, Fs=fs, NFFT=NFFT, window=psd_window, noverlap=NOVL) data_fft = np.fft.fft(data * dwindow) / fs power_vec = np.interp(np.abs(datafreq), freqs, data_psd) optimal = template_fft.conjugate() * data_fft / power_vec optimal_time = 2 * np.fft.ifft(optimal) * fs sigmasq = 1 * (template_fft * template_fft.conjugate() / power_vec).sum() * df sigma = np.sqrt(np.abs(sigmasq)) SNR_complex = optimal_time / sigma peaksample = int(data.size / 2) SNR_complex = np.roll(SNR_complex, peaksample) # peaksample = int(data.size / 2) # SNR_complex = np.roll(SNR_complex, peaksample) SNR = abs(SNR_complex) indmax = np.argmax(SNR) timemax = t[indmax] SNRmax = SNR[indmax] return SNRmax
def Blackman(N, x): ventana = signal.blackman(N) salida = np.multiply(x, ventana) return salida
def plot_spectrum(sys): """ Plot the High Harmonic Generation spectrum """ # Power spectrum emitted is calculated using the Larmor formula # (https://en.wikipedia.org/wiki/Larmor_formula) # which says that the power emitted is proportional to the square of the acceleration # i.e., the RHS of the second Ehrenfest theorem N = len(sys.P_average_RHS) k = np.arange(N) # frequency range omegas = (k - N / 2) * np.pi / (0.5 * sys.t) # spectra of the spectrum = np.abs( # used windows fourier transform to calculate the spectra # rhttp://docs.scipy.org/doc/scipy/reference/tutorial/fftpack.html fftpack.fft((-1)**k * blackman(N) * sys.P_average_RHS))**2 spectrum /= spectrum.max() plt.semilogy(omegas / sys.omega_laser, spectrum) plt.ylabel('spectrum (arbitrary units)') plt.xlabel('frequency / $\\omega_L$') plt.xlim([0, 45.]) plt.ylim([1e-15, 1.])
def main(): print('this is my main') audioFilePath = r'C:\Users\krtzer\Documents\albino-grackle\content\projects\box-counting-sound\Falls of Rauros - Patterns in Mythology - 02 Weapons of Refusal.wav' data, samplerate = sf.read(audioFilePath) print(samplerate) print(len(data)) noise = [gauss(0.0, 1.0) for i in range(len(data))] w = blackman(len(data)) leftchannel = data[0:, 0] rightchannel = data[0:, 1] leftfft = fft(leftchannel * w) rightfft = fft(rightchannel * w) timeaxis = np.linspace(0.0, len(data) / samplerate, len(data)) freqrange = np.linspace(0.0, samplerate / 2, len(leftfft) // 2) #make axis make sense fig, axs = plt.subplots(2) fig.suptitle('Time Domain') axs[0].plot(timeaxis, leftchannel) axs[1].plot(timeaxis, rightchannel) # plt.show() fig2, axs2 = plt.subplots(2) fig2.suptitle('FFT') # // means floor division axs2[0].plot(freqrange, np.abs(rightfft[:len(rightfft) // 2])) axs2[1].plot(freqrange, np.abs(leftfft[:len(leftfft) // 2])) plt.show()
def get_fft(a, step_size): ''' Zero-pads an array so that its a multiple of step_size. Splits it into two sets of step_size'd windows - an "outer" and "inner". These two sets overlap by step_size/2. Interleaves the two sets and applies a blackman (cosine) envelope to each window. Takes the fft of each window and takes the fourier coefficients times their complex conjugate to get the power spectrum for each window. Applies a noise floor of -130dB to account for the case where the magnitude of the fourier coefficient is zero (-inf on a log scale which we cannot plot). We chose -130dB because if 0dB causes your ears to bleed, -130dB would be the quietest thing you could possibly hear. Then we take the log base 10 and swap the axes to be plt.imshow() -able. ''' pad = step_size - (a.size % step_size) zerod = np.append(a, np.zeros(pad)) outer = zerod.reshape(zerod.size // step_size, step_size) inner = zerod[(step_size // 2):(-step_size // 2)]\ .reshape((zerod.size - step_size) // step_size, step_size) interleaved = np.empty([outer.shape[0] + inner.shape[0], outer.shape[1]]) interleaved[::2,:] = outer; interleaved[1::2,:] = inner windowed = blackman(step_size) * interleaved coeffs = fft(windowed)[:, :(step_size // 2) + 1] power_units = np.abs(np.multiply(coeffs, np.conj(coeffs))) power_units = power_units/power_units.max() power_units[np.where(power_units < 1e-13)] = 1e-13 decibels = 10 * np.log10(power_units) return decibels.swapaxes(0, 1)
def time_fourier( x, *ys, sampleFactor=1, interpKind='linear', minFreq='auto', maxFreq='auto', minAmps=None, maxAmps=None, ): if minAmps is None: minAmps = [None for y in ys] if maxAmps is None: maxAmps = [None for y in ys] x, *ys = time_smooth(x, *ys, sampleFactor=sampleFactor, kind=interpKind) N = len(x) T = np.diff(x).mean() freqs = rfftfreq(N, T)[:N // 2] if minFreq is None: minFreq = min(freqs) elif minFreq == 'auto': minFreq = (1 / np.ptp(x)) * 10 if maxFreq is None: maxFreq = max(freqs) elif maxFreq == 'auto': maxFreq = (1 / T) / 10 mask = np.logical_and(freqs >= minFreq, freqs <= maxFreq) freqs = freqs[mask] w = blackman(N) amps = [] for y, minAmp, maxAmp in zip(ys, minAmps, maxAmps): y = y - y.mean() amp = np.abs(rfft(y * w))[:N // 2] if not minAmp is None: amp = np.where(amp < minAmp, 0, amp) if not maxAmp is None: amp = np.where(amp > maxAmp, maxAmp, amp) amps.append(amp[mask]) return (freqs, *amps)
def win_sel(win_str, win_size): """ Function returns a window vector based on window name. Note class can only use windows found in scipy.signal library. """ overlap = 0 if (win_str == 'blackmanharris'): win = sig.blackmanharris(win_size) overlap = .75 elif (win_str == 'blackman'): win = sig.blackman(win_size) elif (win_str == 'bartlett'): win = sig.bartlett(win_size) elif (win_str == 'hamming'): win = sig.hamming(win_size) elif (win_str == 'hanning'): win = sig.hanning(win_size) elif (win_str == 'hann'): win = sig.hann(win_size) elif (win_str == 'barthann'): win = sig.barthann(win_size) elif (win_str == 'triang'): win = sig.triang(win_size) elif (win_str == 'rect' or win_str == None): win = np.ones(win_size) else: print('Invalid Window Defined') return -1 return win, overlap
def highpass_filter(data, width): """Highpass filter on *width* scales using blackman window. Finite impulse response filter *that discards invalid data* at the ends. """ ntime = data.shape[-1] # Blackman FWHM factor. window_width = int(width / 0.4054785) if window_width % 2: window_width += 1 window = np.zeros(ntime, dtype=np.float32) window_core = signal.blackman(window_width, sym=True) window_core = -window_core / np.sum(window_core) window_core[window_width // 2] += 1 window[:window_width] = window_core window_fft = fftpack.fft(window) ntime_out = data.shape[-1] - window_width + 1 out_shape = data.shape[:-1] + (ntime_out,) out = np.empty(out_shape, data.dtype) for ii in range(data.shape[0]): d_fft = fftpack.fft(data[ii]) d_fft *= window_fft d_lpf = fftpack.ifft(d_fft) out[ii] = d_lpf[-ntime_out:].real return out
def compute_spectrum(X, fs): """ Computes the fourier of multiple equidistantly samples signals at a time. Parameters ---------- X : numpy.ndarray Array of signals where ``X[:,k]`` is the k-th signal. fs : float Sampling frequency. Returns ---------- f : numpy.ndarray Freqeuency array. P : numpy.ndarray Power spectrum of the signals. """ assert isinstance(X, np.ndarray) assert isinstance(fs, float) and fs > 0. assert X.ndim <= 2 from scipy.fftpack import fft, fftfreq from scipy.signal import blackman n = X.shape[0] f = fftfreq(n, d=1. / fs) w = blackman(n) spec = fft(( (X - X.mean(axis=0) ).T * w ).T, axis=0) return np.abs(spec[:n//2]), f[:n//2]
def td_dft(dat, winlen=4096, winoverlap=2048, dftsize=4096, winty='blackman'): # calculate the views views = view_as_windows(dat,winlen,winlen-winoverlap) # generate desired window if winty == 'rect': win = np.ones(winlen) elif winty == 'bartlett': win = bartlett(winlen) elif winty == 'hann': win = hanning(winlen) elif winty == 'hamming': win = hamming(winlen) elif winty == 'blackman': win = blackman(winlen) else: assert False # invalid winty # apply window sequence to views views = [ v*win for v in views ] # computes time aliasing to input sequences if needed if winlen > dftsize: views = [ time_alias(v,dftsize) for v in views ] # apply fft and fftshift to all views dfts = [ fftshift(fft(v,dftsize)) for v in views ] return np.array(dfts)
def filtering(signal, range=20, type='gaussian'): N = signal.size # sampling rate T = 1.0 / 1000.0 time_domain = np.linspace(0, 1 / (2 * T), N - 1) signal_fft = fft(signal) signal_fft = signal_fft[1:N] signal_fft_abs = np.abs(signal_fft[:N // 2]) fft_peak = np.argmax(signal_fft_abs) #fft_peak = 400 # for bandpass filter if (type == 'gaussian'): blackman_ = blackman(2 * range) sameSizeKernel = np.zeros(len(signal_fft)) sameSizeKernel[fft_peak - range:fft_peak + range] = blackman_ # for lowpass filtering if (type == 'lowpass'): sigmoid_ = sigmoid(2 * range) sameSizeKernel = np.ones(len(signal_fft)) sameSizeKernel[fft_peak:fft_peak + len(sigmoid_)] = sigmoid_ sameSizeKernel[fft_peak + len(sigmoid_):] = 0 filtered = np.multiply(sameSizeKernel, signal_fft.real) #filtered[:fft_peak-range] = 0 #filtered[fft_peak+range:] = 0 inverse_signal = ifft(filtered) #fft = np.abs(fft[0:N//2]) return inverse_signal.real
def spectrogramme_inv(Spectro,Phase,Fs,Tau,hopsize,win): X = Spectro * np.exp(1j*Phase) [Nf,Nt] = X.shape Nw=np.round(Tau * Fs) R = np.round(hopsize * Nw) if win=='h': w = signal.hamming(Nw, sym=True) elif win=='b': w = signal.blackman(Nw, sym=True) else: w = np.ones(Nw) I = np.round(hopsize * Nw) M = 2 * (Nf-1) L = np.ceil( (Nt-1)*I + M ) y = np.zeros([L,1]) aux_window = ola(np.power(w,2),R, Nt) window=np.sqrt((1/np.max(aux_window))*np.power(w,2)) y_aux=np.zeros([Nw,1]) for r in range(0, Nt): deb = (r)*R fin = deb + Nw Xtilde_inv = ifft(X[:,r]) y_aux[:,0] = Xtilde_inv*window y[deb:fin,0]=y[deb:fin,0]+y_aux[:,0] return y
def plot_specgram(ax, data, fs, nfft=256, noverlap=128, window='hann', cmap='jet', interpolation='bilinear', rasterized=True): if window not in SPECGRAM_WINDOWS: raise ValueError("Window not supported") elif window == "boxcar": mwindow = signal.boxcar(nfft) elif window == "hamming": mwindow = signal.hamming(nfft) elif window == "hann": mwindow = signal.hann(nfft) elif window == "bartlett": mwindow = signal.bartlett(nfft) elif window == "blackman": mwindow = signal.blackman(nfft) elif window == "blackmanharris": mwindow = signal.blackmanharris(nfft) specgram, freqs, time = mlab.specgram(data, NFFT=nfft, Fs=fs, window=mwindow, noverlap=noverlap) specgram = 10 * np.log10(specgram[1:, :]) specgram = np.flipud(specgram) freqs = freqs[1:] halfbin_time = (time[1] - time[0]) / 2.0 halfbin_freq = (freqs[1] - freqs[0]) / 2.0 extent = (time[0] - halfbin_time, time[-1] + halfbin_time, freqs[0] - halfbin_freq, freqs[-1] + halfbin_freq) ax.imshow(specgram, cmap=cmap, interpolation=interpolation, extent=extent, rasterized=rasterized) ax.axis('tight')
def get_MBS(x, fs, T0mean): # Obtain the mean-based signal MBS = np.zeros(len(x)) halfL = int(1.6 * T0mean[0] / 2) StepExp = 3 Step = 2**StepExp for m in range(halfL, len(x) - halfL, Step): if len(T0mean) == 1: halfL = int(1.7 * T0mean[0] / 2) else: halfL = int(1.7 * T0mean[m] / 2) Blackwin = blackman(2 * halfL) start = int(m - halfL) stop = int(m + halfL) if stop > len(x): break if start > 0: vec = x[start:stop] * Blackwin MBS[m] = np.mean(vec) t = np.where(MBS != 0)[0] MBS = np.interp(np.arange(len(x)), t, MBS[t]) MBS[np.isnan(MBS)] = 0 MBS = zeroPhaseHPFilt(MBS, fs, 70, 10) MBS = MBS / max(abs(MBS)) MBS = smooth(MBS, 7) return MBS
def __window_data(data): # Apply window function to the decoded data & store as new key:value pair in dictionary # Parameters: data: [{'frame_data': string, # 'frame_count': int, # 'frame_time': float, # 'frame_position': int, # 'frame_decoded': numpy.ndarray}, ...] # cache window function if 'hann' == config_analysis.frame_window: window = signal.hann(config_audio.frames_per_buffer) elif 'hamming' == config_analysis.frame_window: window = signal.hamming(config_audio.frames_per_buffer) elif 'blackman' == config_analysis.frame_window: window = signal.blackman(config_audio.frames_per_buffer) elif 'bartlett' == config_analysis.frame_window: window = signal.bartlett(config_audio.frames_per_buffer) elif 'barthann' == config_analysis.frame_window: window = signal.barthann(config_audio.frames_per_buffer) else: # window function unavailable return # apply specified window function in config for i in range(len(data)): data[i]['frame_windowed'] = data[i]['frame_decoded'][:] * window
def fft_frame(df): x = df.iloc[:, 1].values y = np.abs(fft(x)) length = y.shape[0] w = blackman(length) spectra = df.apply(lambda x: np.abs(fft(w * x))) return spectra
def plot_spectrum(sys): """ Plot the High Harmonic Generation spectrum """ # Power spectrum emitted is calculated using the Larmor formula # (https://en.wikipedia.org/wiki/Larmor_formula) # which says that the power emitted is proportional to the square of the acceleration # i.e., the RHS of the second Ehrenfest theorem # plot the HHG spectrum for each system in the batch separately for p_average_rhs in np.swapaxes(sys.p_average_rhs, 0, 1): N = len(p_average_rhs) k = np.arange(N) # frequency range omegas = (k - N / 2) * np.pi / (0.5 * sys.t) # spectra of the spectrum = np.abs( # used windows fourier transform to calculate the spectra # rhttp://docs.scipy.org/doc/scipy/reference/tutorial/fftpack.html fftpack.fft((-1)**k * blackman(N) * p_average_rhs))**2 spectrum /= spectrum.max() plt.semilogy(omegas / omega_laser, spectrum) plt.ylabel('spectrum (arbitrary units)') plt.xlabel('frequency / $\\omega_L$') plt.xlim([0, 45.]) plt.ylim([1e-15, 1.]) # plot vertical lines corresponding to odd frequencies for k in 2 * np.arange(21) + 1: plt.axvline(k, linestyle='--', color='black') plt.show()
def BandPassFilter(data, lowcut, highcut, fs, order, bWindowData): nyq = 0.5 * fs low = lowcut / nyq high = highcut / nyq b, a = butter(order, [low, high], btype='band') b = b / a[0] a = a / a[0] #For higher order filters use second order signal sos = butter(6, [low, high], btype='bandpass', output='sos') w, h = sosfreqz(sos, round(fs / 2)) if bWindowData == True: #Uss a blackman window accross the data window = blackman(len(data)) data = data * window #w, h = freqz(b, a, round(fs/2)) plt.plot((fs * 0.5 / np.pi) * w, abs(h), label="order = %d" % order) plt.plot([0, 0.5 * fs], [np.sqrt(0.5), np.sqrt(0.5)], '--', label='sqrt(0.5)') plt.xlabel('Frequency (Hz)') plt.ylabel('Gain') plt.grid(True) plt.legend(loc='best') plt.show() fData = lfilter(b, a, data) return fData
def fftPlot(sig, dt=None, block=False, plot=True, title = 'Analytic FFT plot'): # here it's assumes analytic signal (real signal...)- so only half of the axis is required if dt is None: dt = 1 t = np.arange(0, sig.shape[-1]) xLabel = 'samples' else: t = np.arange(0, sig.shape[-1]) * dt xLabel = 'freq [Hz]' if sig.shape[0] % 2 != 0: warnings.warn("signal prefered to be even in size, autoFixing it...") t = t[0:-1] sig = sig[0:-1] w = blackman(t.shape[0]) sig = signal.detrend(sig, axis=0) #newsig = sig - np.mean(sig) sigFFT = np.fft.fft(sig*w) / t.shape[0] # divided by size t for coherent magnitude freq = np.fft.fftfreq(t.shape[0], d=dt) # plot analytic signal - right half of freq axis needed only... firstNegInd = np.argmax(freq < 0) freqAxisPos = freq[0:firstNegInd] sigFFTPos = 2 * sigFFT[0:firstNegInd] # *2 because of magnitude of analytic signal return sigFFTPos, freqAxisPos
def waterfspec(data, start, steps, N, fS, clippingpoint, baseplane): import matplotlib.pyplot as plt import numpy as np from scipy import signal from matplotlib.collections import PolyCollection from mpl_toolkits.mplot3d import Axes3D if baseplane is None: baseplane = -100 if clippingpoint is None: clippingpoint = 0 if fS is None: fS = 44100 if N is None: N = 1024 # default FFT if steps is None: steps = round(len(data) / 25) if start is None: start = 0 #%% windoo = signal.blackman(N) # window - default windoo = windoo * N / float(sum(windoo)) # scaling # Calculation of number of spectra nos n = len(data) rest = n - start - N nos = round(rest / steps) if nos > rest / steps: nos = nos - 1 nos = int(nos) #vectors for 3D representation x = np.linspace(0, fS, N) data = data + 0.0000001 #%% Computation of spectra and visual representation verts = [] for i in range(0, nos + 1): spek = 20 * np.log10( np.abs( np.fft.fft( windoo * data[start + i * steps:start + N + i * steps])) / (N) / 0.5) spek = np.insert(spek, 0, -200) #setting the clipping point and baseplane spek = spek.clip(min=baseplane, max=clippingpoint) #first and last point to the baseplane spek[0] = baseplane - 10 spek[N / 2 - 1] = baseplane - 10 xx = x[:N / 2] verts.append(list(zip(xx, spek[:N / 2]))) #%% Plot figure fig = plt.figure() ax = fig.gca(projection='3d') poly = PolyCollection(verts, facecolors='w') y = range(len(x / 2)) poly.set_alpha(1) ax.add_collection3d(poly, zs=y, zdir='y') ax.set_title('Waterfall Representation of Short-time FFTs') ax.set_xlabel('f in Hz') ax.set_xlim3d(0, fS / 2) ax.set_ylabel('N') ax.set_ylim3d(1, 30) ax.set_zlabel('Magnitude in dB') ax.set_zlim3d(baseplane - 10, 0) plt.tight_layout() plt.show()
def spectrum_wwind(array, time, window='hanning'): # time should be in seconds # Size of array Nw = array.shape[0] # Calculate time step (assumed to be in seconds) dt = time[1] - time[0] # prefactor # print 'dt = ',dt prefactor = dt # Calculate array of frequencies, shift w = np.fft.fftfreq(Nw, dt) w0 = np.fft.fftshift(w) # make window # blackman window if window == 'blackman': bwin = blackman(Nw) # pretty good if window == 'hanning': bwin = hanning(Nw) # pretty good if window == 'hamming': bwin = hamming(Nw) # not as good if window == 'bartlett': bwin = bartlett(Nw) # pretty good if window == 'kaiser': bwin = kaiser(Nw, 6) if window == 'None': bwin = 1.0 # Calculate FFT aw = prefactor * np.fft.fft(array * bwin) aw0 = np.fft.fftshift(aw) # Calcuate Phase phase = np.angle(aw) phase0 = np.fft.fftshift(phase) # Adjust arrays if not div by 2 if not np.mod(Nw, 2): w0 = np.append(w0, -w0[0]) aw0 = np.append(aw0, -aw0[0]) phase0 = np.append(phase0, -phase0[0]) # Cut FFTs in half Nwi = Nw // 2 w2 = w0[Nwi:] aw2 = aw0[Nwi:] phase2 = phase0[Nwi:] comp = aw pwr = (np.abs(aw2))**2 pwr2 = (np.abs(aw))**2 mag = np.sqrt(pwr) cos_phase = np.cos(phase2) freq = w2 freq2 = w return freq, freq2, comp, pwr, mag, phase2, cos_phase, dt
def showSpectrogram(audio,fs): N = 512 f, t, Sxx = signal.spectrogram(audio, fs,window = signal.blackman(N),nfft=N) plt.figure() plt.pcolormesh(t, f,10*np.log10(Sxx)) plt.ylabel('Frequency [Hz]') plt.xlabel('Time [seg]') plt.title('Spectrogram',size=16); plt.show()
def fft_frame(df): x = df.iloc[:, 10].values y = np.abs(fft(x)) length = y.shape[0] w = blackman(length) print(x.shape, ' ', y.shape, ' ', w.shape) plt.plot(fft(w * x)) spectra = df.apply(lambda x: np.abs(np.fft.fft(w * x))) return spectra
def fft_frame(df,shape): print('funkcja2') length=shape print('shape') w = blackman(length) print('blackman') spectra=df.T.applymap(lambda y:y+2)#df.applymap(lambda x: np.abs(fft(w*x))) print('fft') return spectra
def getFFT(signal, T): N = len(signal) xf = np.linspace(0.0, 1.0 / (2.0 * float(T)), N / 2) w = blackman(N) ffts = [] sfft = fft(np.array(signal) * w) return xf, sfft
def plot_fourier(): # Two subplots, unpack the axes array immediately k = 12 U2 = np.load("npy/U2_%03d.npy"%k) t = np.load("npy/T_%03d.npy"%k) plt.figure() plt.plot(t,U2) plt.show() Tmax = np.max(t) N = len(U2) N2 = N-2 T = Tmax/N*1000 w = blackman(N) U2f = fft(U2*w) U2f2 = fft(U2) U2acf = acf(U2,N2) w2 = blackman(N2) U2acff = fft(U2acf*w2) U2acff2 = fft(U2acf) tf = np.linspace(0.0, 1.0/(2.0*T), N/2) tf2 = np.linspace(0.0, 1.0/(2.0*T), (N2)/2) f, axarr = plt.subplots(2, 2, figsize = (11.5,8.2)) axarr[0, 0].semilogy(tf, 2.0 / N * np.abs(U2f2[0:N/2])**2) axarr[0, 0].set_title('Fourier Transform without blackman') axarr[0, 1].semilogy(tf, 2.0 / N * np.abs(U2f[0:N/2])**2) axarr[0, 1].set_title('Fourier Transform with blackman') axarr[1, 0].semilogy(tf2, 2.0 / N2 * np.abs(U2acff2[0:N2/2])**2) axarr[1, 0].set_title('Fourier of Autocorrelation function') axarr[1, 0].set_xlabel('time in ms') axarr[1, 1].semilogy(tf2, 2.0 / N2 * np.abs(U2acff[0:N2/2])**2) axarr[1, 1].set_title('Fourier transform of Autocorrelation with blackman') axarr[1, 1].set_xlabel('Frequency in kHz') plt.show()
def get_fft(sig, fs, N): T = 1.0/fs if N is None: N = len(sig) w = blackman(N) yf = fft(sig[:N]*w) xf = np.linspace(0.0, 1.0/(2.0*T), N/2.) return xf, yf
def eval_visualize(file_name, f, window_size, noverlap, side="left"): fs, Audiodata = wavfile.read(file_name) if side == "right": Audiodata = Audiodata[:, 1] else: Audiodata = Audiodata[:, 0] # Audiodata = np.zeros_like(Audiodata) freq, t, Sxx = signal.spectrogram(Audiodata, fs, window=signal.blackman(window_size), noverlap=noverlap, nfft=window_size, nperseg=window_size) print(Sxx.shape) tmp = Sxx.transpose() Sxx = np.transpose(10 * np.log10(Sxx + 1e-8))[:, :f.opts.s_dim] print(Sxx.shape) graph_i = 0 plt.subplot(1 + 4, 1, 1) plt.imshow(Sxx.transpose()) for shift in range(0, 20, 5): res_label = [] batch = [] graph_i += 1 for i in range(0, Sxx.shape[0], f.opts.s_window_size): r = Sxx[i:i + f.opts.s_window_size, :] if r.shape[0] == f.opts.s_window_size: lol = np.zeros_like( r.reshape(1, f.opts.s_dim, f.opts.s_window_size, 1)) lol[0, :, :, 0] = r.transpose() batch.append(lol) s = np.vstack(batch) print(s.shape) sample = np.vstack((s, np.zeros((f.opts.batch_size - s.shape[0], f.opts.s_dim, f.opts.s_window_size, 1)))) res = f.sess.run(f.activated_res, feed_dict={f.s_input_sample: sample}) print(res.shape, "HAHAHAHAH") for j in range(s.shape[0]): res_label.append(res[j].ravel()) # print(res_label) print(len(res_label), res_label[0].shape) res_label = np.hstack(res_label) if shift != 0: res_label = np.hstack((np.zeros([shift]), res_label)) if res_label.shape[0] < Sxx.shape[0]: res_label = np.hstack( (res_label, np.zeros(Sxx.shape[0] - res_label.shape[0]))) plt.subplot(1 + 4, 1, graph_i + 1) plt.bar(np.arange(res_label.shape[0]), res_label) plt.show()
def spectrum(timestamps, iq_samples, start_bin=0, num_bins=None, n_fft=8192, return_timestamps=True, save_memory=False): """ Calculate FFT spectrum of a given signal. Blackman-Harris windowing is applied. Parameters ---------- timestamps : Timestamps, for changing the rate of the timestamps to the rate of the FFT windows iq_samples : Raw IQ samples as obtained from GNU Radio start_bin : optional Start bin for the bins we want to keep num_bins : optional Number of bins we want to keep. If None, will return all bins n_fft : optional Size of FFT return_timestamps : optional Whether to return resampled timestamps save_memory : optional If False, will run the FFT transform in one go on the full data array and then take the subset specified by start_bin and num_bins, and otherwise take the FFT window by window and reduce to the subset for each window. The same end result is achieved, but the former is faster and the latter is less memory-extensive. Returns ------- timestamps : optional Resampled timestamps, if return_timestamps is set to True ret_spectrum : FFT spectrum at specified bins """ if num_bins is None: num_bins = n_fft w = blackman(n_fft) num_frames = len(iq_samples)/n_fft end_bin = start_bin + num_bins if not save_memory: ret_spectrum = fftshift(fft(np.reshape(iq_samples[0:num_frames*n_fft], (num_frames, n_fft)), n=n_fft), axes=1)[:, start_bin:end_bin] else: ret_spectrum = np.zeros((num_frames, num_bins), dtype=np.complex64) for i in np.arange(0, num_frames): fft_res = np.fft.fftshift(np.fft.fft(w*iq_samples[i*n_fft:(i+1)*n_fft])) ret_spectrum[i,:] = fft_res[start_bin:end_bin] if return_timestamps: timestamps = timestamps[n_fft/2:-1:n_fft] timestamps = timestamps[0:ret_spectrum.shape[0]] return timestamps, ret_spectrum else: return ret_spectrum
def matched_filter_Real(s, h, fs, psdfun=None, cut=None, window=True): if window: try: dwindow = signal.tukey( h.size, alpha=1. / 8) # Tukey window preferred, but requires recent scipy version except: dwindow = signal.blackman(h.size) else: dwindow = 1 stilde = np.fft.fft(s * dwindow) / fs hrtilde = np.fft.fft(h.real * dwindow) / fs hitilde = np.fft.fft(h.imag * dwindow) / fs htilde = np.fft.fft(h * dwindow) / fs datafreq = np.fft.fftfreq(h.size, 1. / fs) df = abs(datafreq[1] - datafreq[0]) if psdfun is None: NFFT = 4 * fs psd_window = np.blackman(NFFT) # and a 50% overlap: NOVL = NFFT / 2 data_psd, freqs = mlab.psd(s, Fs=fs, NFFT=NFFT, window=psd_window, noverlap=NOVL) power_vec = np.interp(np.abs(datafreq), freqs, data_psd) else: power_vec = psdfun(np.abs(datafreq)) if cut is not None: fmin, fmax = cut if fmin < min(abs(datafreq)): fmin = min(abs(datafreq)) if fmax > max(abs(datafreq)): fmax = max(abs(datafreq)) kmin = np.where(np.abs(datafreq - fmin) < df)[0][0] kmax = np.where(np.abs(datafreq - fmax) < df)[0][0] stilde[:kmin] = 0 stilde[kmax:] = 0 hrtilde[:kmin] = 0 hrtilde[kmax:] = 0 hitilde[:kmin] = 0 hitilde[kmax:] = 0 sig2 = 1 * (htilde * htilde.conjugate() / power_vec).sum() * df op_r = 2 * stilde * hrtilde.conjugate() / power_vec op_r_time = np.fft.ifft(op_r) * fs op_i = 2 * stilde * hitilde.conjugate() / power_vec op_i_time = np.fft.ifft(op_i) * fs op = (op_r_time + 1.j * op_i_time) / np.sqrt(np.abs(sig2)) return op
def test_compare_both_biorthogonal_window_variants(self): window = signal.blackman(1024) shift = 256 for_result = _biorthogonal_window_loopy(window, shift) vec_result = _biorthogonal_window(window, shift) brute_force_result = _biorthogonal_window_brute_force(window, shift) tc.assert_equal(for_result, vec_result) tc.assert_allclose(for_result, brute_force_result) tc.assert_equal(for_result.shape, (1024, ))
def calc_fft(df): # Number of sample points N = len(df) # sample spacing T = 1.0 / N * 1.5 ##window function w = blackman(N) y = df yf = 2.0 / N * np.abs(fft(y * w)[0:N // 2]) xf = np.linspace(0.0, 1.0 / (2.0 * T), N // 2) return yf, xf
def running_window(a, step_size): ''' ''' padded = np.append(np.append(np.zeros(step_size), a), np.zeros(step_size)) windows = [] for i in range(a.size + step_size): windows.append(padded[i: i + step_size]) coeffs = fft(blackman(step_size) * np.array(windows)).swapaxes(0, 1)[:step_size//2 + 1] power = np.array(coeffs) power = (power * power.conj()).real power = power / power.max() power[np.where(power < 1e-13)] = 1e-13 return 10 * np.log10(power)
def go_through(): for k in range(27+1): U2 = np.load("npy/U2_%03d.npy"%k) t = np.load("npy/T_%03d.npy"%k) Tmax = np.max(t) N = len(U2) N2 = N-2 T = Tmax/N*1000 w2 = blackman(N2) U2acf = acf(U2,N2) U2acff = fft(U2acf*w2) tf2 = np.linspace(0.0, 1.0/(2.0*T), (N2)/2)
def mkWindow(com,N): if com == "hm": win = sg.hamming(N) elif com == "hn": win = sg.hann(N) elif com == "bk": win = sg.blackman(N) elif com == "ga": win = sg.gaussian(N,N/16) elif com == "bar": win = sg.bartlett(N) elif com == "rect": win = np.ones(N) else : usage() return win
def filter(data): from scipy.signal import blackman, firwin, filtfilt a = np.array([1]) # 10 Hz highpass n = 127; # filter order Wn = 10 / (sample_rate/2) # cut-off frequency window = blackman(n) b = firwin(n, Wn, window='blackman', pass_zero=False) data = filtfilt(b, a, data) data = abs(data) # rectify signal # 5 Hz lowpass Wn = 5 / (sample_rate/2) b = firwin(n, Wn, window='blackman') data = filtfilt(b, a, data) return data
def generate_window_coefs(window,window_length,file_path,numPoints): print '\nGenerating {} window of length {}...'.format(window,window_length) # specify total bits and fractional bits for fixed point input: n_bits = 16 n_frac_bits = 15 if (window=='boxcar'): coefs=signal.boxcar(window_length) elif (window=='hamming'): coefs=signal.hamming(window_length) elif (window=='hann'): coefs=signal.hann(window_length) elif (window=='blackman'): coefs=signal.blackman(window_length) else: coefs=signal.boxcar(window_length) #Write out hex file for VHDL intData=np.zeros(numPoints) nintData=np.uint16(coefs*(2**n_bits-1)) paddingFrac=4 if (window_length==numPoints): intData=coefs else: for i in range(len(coefs)): intData[int(numPoints/paddingFrac)+i]=coefs[i] intData = [ID*(2**n_bits-1) for ID in intData] intData=np.hstack([intData,intData]) with open(str(file_path)+'/fpgaCoefData'+str(numPoints)+'_'+str(window)+'.txt','w') as FID: FID.write('\n'.join(['{}'.format(int(x)) for x in intData])) with open(str(file_path)+'/macCoefData'+str(numPoints)+'_'+str(window)+'.txt','w') as FID: FID.write('signal myCoef : input_array32 :=(') FID.write(','.join(['x"{0:08X}"'.format(int(x)) for x in intData])+');')
def spectrogramme(s,Fs,Tau,hopsize, win): N = s.shape[0] Nw=np.round(Tau * Fs) R = np.round(hopsize * Nw) Nt = np.array([np.fix((N-Nw)/R)]) I = np.round(hopsize * Nw) if win=='h': w = signal.hamming(Nw, sym=True) elif win=='b': w = signal.blackman(Nw, sym=True) else: w = np.ones(Nw) aux_window = ola(np.power(w,2),R,int (Nt[0])) window=np.sqrt((1/np.max(aux_window))*np.power(w,2)) Spectro = np.zeros([Nw, int (Nt[0])]) Phase = np.zeros([Nw, int (Nt[0])]) for r in range(0,int (Nt[0])): deb = (r)*R fin = deb + Nw tx = s[deb:fin]*window X = fft(tx) Spectro[:,r] = np.abs(X[0:len(tx)]) Phase[:,r] = np.angle(X[0:len(tx)]) tr=np.arange(0,Nt-1,1)*(I/Fs)+(N/2)/Fs f=np.arange(0,len(tx)-1,1)*(Fs/2)/len(tx) return (Spectro,Phase,tr,f)
# Plot HHG spectra as FFT(<P>) # ################################################################# N = len(quant_sys.P_average) # the windowed fft of the evolution # to remove the spectral leaking. For details see # rhttp://docs.scipy.org/doc/scipy/reference/tutorial/fftpack.html from scipy import fftpack from scipy.signal import blackman # obtain the dipole J = np.array(quant_sys.P_average) fft_J = fftpack.fft(blackman(N) * J) #fft_J = fftpack.fft(J) spectrum = np.abs(fftpack.fftshift(fft_J))**2 omegas = fftpack.fftshift(fftpack.fftfreq(N, quant_sys.dt/(2*np.pi))) / quant_sys.omega spectrum /= spectrum.max() plt.semilogy(omegas, spectrum) plt.ylabel('spectrum FFT($\\langle p \\rangle$)') plt.xlabel('frequency / $\\omega$') plt.xlim([0, 100.]) plt.ylim([1e-20, 1.]) plt.show() #"""
# Plot the window and its frequency response: from scipy import signal from scipy.fftpack import fft, fftshift import matplotlib.pyplot as plt window = signal.blackman(51) plt.plot(window) plt.title("Blackman window") plt.ylabel("Amplitude") plt.xlabel("Sample") plt.figure() A = fft(window, 2048) / (len(window)/2.0) freq = np.linspace(-0.5, 0.5, len(A)) response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) plt.plot(freq, response) plt.axis([-0.5, 0.5, -120, 0]) plt.title("Frequency response of the Blackman window") plt.ylabel("Normalized magnitude [dB]") plt.xlabel("Normalized frequency [cycles per sample]")
tau_model3 = np.copy(tau_next); for i in range(1,m-2): if(i%100000==0): tau_model[i+1] = a*tau[i] + b*delta_q[i]; tau_model2[i+1] = a2*tau[i] + b2*delta_q[i]; tau_model3[i+1] = a3*tau[i] + b3*tau[i-1] + c3*delta_q[i]; else: tau_model[i+1] = a*tau_model[i] + b*delta_q[i]; tau_model2[i+1] = a2*tau_model2[i] + b2*delta_q[i]; tau_model3[i+1] = a3*tau_model3[i] + b3*tau_model3[i-1] + c3*delta_q[i]; print '\n Compute FFT of signals' #time = scipy.linspace(0,120,4000); #acc = lambda t: 10*scipy.sin(2*np.pi*2.0*t) + 5*scipy.sin(2*np.pi*8.0*t) + 2*scipy.random.random(len(t)); #signal = acc(t); w = blackman(len(tau)); FFT = abs(scipy.fftpack.fft(tau)); FFT_model = abs(scipy.fftpack.fft(tau_model3)); FFT_wf = abs(scipy.fftpack.fft(tau*w)); FFT_model_w = abs(scipy.fftpack.fft(tau_model3*w)); freqs = scipy.fftpack.fftfreq(tau.size, DT); w = 2*np.pi*freqs; if(PLOT_TRANSFER_FUNCTION): print 'Compute frequency responce of identified system'; #sys1 = my_ltisys.lti([a], [b], [1], [0]); #sys1 = scipy.signal.lti([b], [1, -a]); sys1 = scipy.signal.lti(1,[1, 1.0/RC]); w, mag, phase = my_ltisys.bode(sys1, w); f, ax = plt.subplots(2,1,sharex=False);
# ax3 = fig_rain.add_subplot(1,1,1) # im_rain = ax3.imshow(rainfieldSmoothed, interpolation='nearest')#, vmin=0.99, vmax=1) # fig_rain.subplots_adjust(right=0.8) # cbar_ax = fig_rain.add_axes([0.85, 0.15, 0.05, 0.7]) # fig_rain.colorbar(im_rain, cax=cbar_ax) # ax3.set_title('minDBZ = ' + fmt2 % minDBZ + ', filterSize = ' + str(filterSize)) # plt.show() # sys.exit() ########### Compute Fourier power spectrum ########### ticFFT = time.clock() # Generate a window function if windowFunction == 'blackman': w = ss.blackman(fftDomainSize) window = np.outer(w,w) else: window = np.ones((fftDomainSize,fftDomainSize)) # Compute FFT if FFTmod == 'NUMPY': fprecipNoShift = np.fft.fft2(rainfieldSmoothed*window) # Numpy implementation if FFTmod == 'FFTW': fprecipNoShift = pyfftw.interfaces.numpy_fft.fft2(rainfieldSmoothed*window) # FFTW implementation # Turn on the cache for optimum performance pyfftw.interfaces.cache.enable() # Shift frequencies fprecip = np.fft.fftshift(fprecipNoShift)
import matplotlib.pyplot as plt import numpy as np from scipy.fftpack import fft, fftshift from scipy import signal M = 32 N = 128 hN = N/2 hM = M/2 fftbuffer = np.zeros(N) w = signal.blackman(M) plt.subplot(3,2,1) plt.figure(1) plt.plot(np.arange(-hM, hM), w, 'b') plt.axis([-hM, hM-1, 0, 1]) plt.xlabel('time (samples)') plt.ylabel('amplitude') plt.title('M=32') fftbuffer = np.zeros(N) fftbuffer[:hM] = w[hM:] fftbuffer[N-hM:] = w[:hM] X = fft(fftbuffer) mX = 20*np.log10(abs(fftshift(X))) plt.subplot(3,2,3) plt.plot(np.arange(-hN, hN), mX-max(mX), 'r') plt.axis([-hN/2,hN/2,-80,0]) plt.xlabel('frequency (bins)') plt.ylabel('amplitude (dB)')
gfiltpak.gfreqz(b, a, color = 'k', magfig = mag_p, angfig = ang_p) hold(True) from scipy import signal as si b = si.kaiser(N, 3) gfiltpak.gfreqz(b, a, color = 'm', magfig = mag_p, angfig = ang_p, label = "kaiser", threedb = True) hold(True) b = si.blackmanharris(N) gfiltpak.gfreqz(b, a, color = 'g', magfig = mag_p, angfig = ang_p, ylimmag = [-500, 0]) hold(True) b = si.blackman(N) gfiltpak.gfreqz(b, a, color = 'y', magfig = mag_p, angfig = ang_p) # Show mag_p.legend(('r', 'k', '3dB', 'b-h', 'b'), numpoints = 4, fancybox = True) ang_p.legend(('r', 'k', 'b-h', 'b'), numpoints = 2, fancybox = True) ############################################################## ## IIR filter c = 1 b = [1] root_r = 0.10 a = [1, -root_r] #[1, 1, 0.25] rep = 1
def main(*args): tr = {} #the object that is returned by this function - used to analyze the results tr['nyquist'] = 50000 #50 kHz is the nyquist frequncy since we have a sample rate of 100 kHz ### create the pulse template and save it to the return (template, python_template) = getTemplate() tr['template'] = python_template tr['templatepower'] = calculatePower(template) ### calculate the power pulseLength = len(python_template) #get the length from the template # get a noise pulse # save it to the return random.seed() noisepulse = getNoisePulse(pulseLength) wn = [] for i in range(pulseLength): wn.append(noisepulse[i]) tr['noise'] = wn tr['noisepower'] = calculatePower(noisepulse) ### calculate the power #create the signal by adding the template to the noise #save it to the return signal = createSignal(pulseLength, python_template, noisepulse, 500.) signalpy = [] for i in range(pulseLength): signalpy.append(signal[i]) tr['signal'] = signalpy tr['signalpower'] = calculatePower(signal) ### calculate the power #add a windowing function x = sig.blackman(3200) xx = KWindowDesign.GetBlackmanWindow(3200) x = np.zeros(3200) for i in range(3200): x[i] = xx[i] tr['window'] = x.tolist() addWindowFunction(signal, x, 6556) addWindowFunction(template, x, np.argmin(template)) tr['window_signal'] = [] tr['window_template'] = [] for i in range(len(signal)): tr['window_signal'].append(signal[i]) for i in range(len(template)): tr['window_template'].append(template[i]) #perform the filter (b,a) = sig.iirfilter(2,[0.001, 0.01]) filter = KIIRFourthOrder(a[1], a[2], a[3], a[4], b[0], b[1], b[2], b[3], b[4]) #here's the filter's frequency response function tr['b'] = b tr['a'] = a #for fun, pass the noise through the bandpass filter.SetInputPulse(noisepulse) filter.RunProcess() bp_noise = std.vector("double")() bp_noisepy = [] for i in range(pulseLength): bp_noise.push_back(filter.GetOutputPulse()[i]) bp_noisepy.append(filter.GetOutputPulse()[i]) tr['bp_noise'] = bp_noisepy tr['bp_noisepower'] = calculatePower(bp_noise) #pass the template through the bandpass filter.SetInputPulse(template) filter.RunProcess() bp_template = std.vector("double")() bp_templatepy = [] for i in range(pulseLength): bp_template.push_back(filter.GetOutputPulse()[i]) bp_templatepy.append(filter.GetOutputPulse()[i]) tr['bp_template'] = bp_templatepy tr['bp_templatepower'] = calculatePower(bp_template) #pass the signal through the bandpass filter.SetInputPulse(signal) filter.RunProcess() bp_signal = std.vector("double")() bp_signalpy = [] for i in range(pulseLength): bp_signal.push_back(filter.GetOutputPulse()[i]) bp_signalpy.append(filter.GetOutputPulse()[i]) tr['bp_signal'] = bp_signalpy tr['bp_signalpower'] = calculatePower(bp_signal) correlation = KCorrelation() #set the template as the response to the correlation function bp_tempLeft = shiftSignalRight(bp_template, 2090) bp_tempMiddle = shiftSignalRight(bp_template, 2095) bp_tempRight = shiftSignalRight(bp_template, 2100) bp_py = [] for i in range(len(bp_tempLeft)): bp_py.append(bp_tempLeft[i]) tr['bp_tempLeft'] = bp_py bp_py = [] for i in range(len(bp_tempMiddle)): bp_py.append(bp_tempMiddle[i]) tr['bp_tempMiddle'] = bp_py bp_py = [] for i in range(len(bp_tempRight)): bp_py.append(bp_tempRight[i]) tr['bp_tempRight'] = bp_py correlation.SetResponse(bp_tempLeft) correlation.SetInputPulse(bp_signal) correlation.RunProcess() corrOut = std.vector("double")() corrOutpy = [] for i in range(correlation.GetOutputPulseSize()): corrOut.push_back(correlation.GetOutputPulse()[i]) corrOutpy.append(correlation.GetOutputPulse()[i]) tr['corrLeft'] = corrOutpy correlation.SetResponse(bp_tempMiddle) correlation.SetInputPulse(bp_signal) correlation.RunProcess() corrOut = std.vector("double")() corrOutpy = [] for i in range(correlation.GetOutputPulseSize()): corrOut.push_back(correlation.GetOutputPulse()[i]) corrOutpy.append(correlation.GetOutputPulse()[i]) tr['corrMiddle'] = corrOutpy correlation.SetResponse(bp_tempRight) correlation.SetInputPulse(bp_signal) correlation.RunProcess() corrOut = std.vector("double")() corrOutpy = [] for i in range(correlation.GetOutputPulseSize()): corrOut.push_back(correlation.GetOutputPulse()[i]) corrOutpy.append(correlation.GetOutputPulse()[i]) tr['corrRight'] = corrOutpy return tr
def main(inputFile='../../sounds/orchestra.wav', Ws=(blackman(4095), hamming(2047), hamming(1023)), Ns=(4096, 2048, 1024), Bs=(1000, 5000, 22050), t=-80, minSineDur=0.02, maxnSines=150, freqDevOffset=10, freqDevSlope=0.001): """ Perform analysis/synthesis using the sinusoidal model inputFile: input sound file (monophonic with sampling rate of 44100) Ws: analysis windows M: analysis window size; N: fft size (power of two, bigger or equal than M) t: magnitude threshold of spectral peaks; minSineDur: minimum duration of sinusoidal tracks maxnSines: maximum number of parallel sinusoids freqDevOffset: frequency deviation allowed in the sinusoids from frame to frame at frequency 0 freqDevSlope: slope of the frequency deviation, higher frequencies have bigger deviation """ # size of fft used in synthesis sN = 512 # hop size (has to be 1/4 of sN) H = 128 # read input sound fs, x = UF.wavread(inputFile) # analyze the sound with the sinusoidal model tfreq, tmag, tphase = MR.sineModelMultiResAnal(x, fs, Ws, Ns, Bs, H, t, maxnSines, minSineDur, freqDevOffset, freqDevSlope) # synthesize the output sound from the sinusoidal representation y = SM.sineModelSynth(tfreq, tmag, tphase, sN, H, fs) # output sound file name outputFile = 'output_sounds/' + os.path.basename(inputFile)[:-4] + '_sineModelMulitRes.wav' # write the synthesized sound obtained from the sinusoidal synthesis UF.wavwrite(y, fs, outputFile) # create figure to show plots plt.figure(figsize=(12, 9)) # frequency range to plot maxplotfreq = 5000.0 # plot the input sound plt.subplot(3,1,1) plt.plot(np.arange(x.size)/float(fs), x) plt.axis([0, x.size/float(fs), min(x), max(x)]) plt.ylabel('amplitude') plt.xlabel('time (sec)') plt.title('input sound: x') # plot the sinusoidal frequencies plt.subplot(3,1,2) if (tfreq.shape[1] > 0): numFrames = tfreq.shape[0] frmTime = H*np.arange(numFrames)/float(fs) tfreq[tfreq<=0] = np.nan plt.plot(frmTime, tfreq) plt.axis([0, x.size/float(fs), 0, maxplotfreq]) plt.title('frequencies of sinusoidal tracks') # plot the output sound plt.subplot(3,1,3) plt.plot(np.arange(y.size)/float(fs), y) plt.axis([0, y.size/float(fs), min(y), max(y)]) plt.ylabel('amplitude') plt.xlabel('time (sec)') plt.title('output sound: y') plt.tight_layout() plt.show()
psd_window = np.blackman(NFFT) # and a 50% overlap: NOVL = NFFT/2 # define the complex template, common to both detectors: template = (template_p + template_c*1.j) # We will record the time where the data match the END of the template. etime = time+template_offset # the length and sampling rate of the template MUST match that of the data. datafreq = np.fft.fftfreq(template.size)*fs df = np.abs(datafreq[1] - datafreq[0]) # to remove effects at the beginning and end of the data stretch, window the data # https://en.wikipedia.org/wiki/Window_function#Tukey_window try: dwindow = signal.tukey(template.size, alpha=1./8) # Tukey window preferred, but requires recent scipy version except: dwindow = signal.blackman(template.size) # Blackman window OK if Tukey is not available # prepare the template fft. template_fft = np.fft.fft(template*dwindow) / fs # loop over the detectors dets = ['H1', 'L1'] for det in dets: if det is 'L1': data = strain_L1.copy() else: data = strain_H1.copy() # -- Calculate the PSD of the data. Also use an overlap, and window: data_psd, freqs = mlab.psd(data, Fs = fs, NFFT = NFFT, window=psd_window, noverlap=NOVL) # Take the Fourier Transform (FFT) of the data and the template (with dwindow)
import matplotlib.pyplot as plt import numpy as np from scipy.fftpack import fft from scipy import signal M = 64 N = 512 hN = N//2 hM = M//2 fftbuffer = np.zeros(N) mX1 = np.zeros(N) plt.figure(1, figsize=(7.5, 4)) fftbuffer[hN-hM:hN+hM]=signal.blackman(M) plt.subplot(2,1,1) plt.plot(np.arange(-hN, hN), fftbuffer, 'b', lw=1.5) plt.axis([-hN, hN, 0, 1.1]) X = fft(fftbuffer) mX = 20*np.log10(abs(X)) mX1[:hN] = mX[hN:] mX1[N-hN:] = mX[:hN] plt.subplot(2,1,2) plt.plot(np.arange(-hN, hN), mX1-max(mX), 'r', lw=1.5) plt.axis([-hN,hN,-80,0]) plt.tight_layout() plt.savefig('blackman.png') plt.show()
import scipy.fftpack as sfft from scipy.io import wavfile from scipy.signal import blackman import numpy as np import os parser = argparse.ArgumentParser( description='Convert audio from a folder to frequency domain feature vectors.') parser.add_argument('-i', '--input', default='wav') parser.add_argument('-m', '--maxfreq', type=int, default=500) parser.add_argument('-c', '--chunksize', type=int, default=2**14) args = parser.parse_args() n = args.chunksize print('{0} chunk size'.format(n)) window = blackman(n) vectors = [] labels = [] for f in os.listdir(args.input): path = os.path.join(args.input, f) sampleRate, data = wavfile.read(path) total = len(data) chunks = [data[i:i+n] for i in range(0, total-n, n)] label = f.split('.')[0] for i, chunk in enumerate(chunks): freq = sfft.fft(chunk * window) bins = len(freq)/2 usable = args.maxfreq * n / sampleRate if usable == 0: usable = bins amp = np.absolute(freq[:usable])
Error = (ErrorPM[0]/MaxNPM) + (rho*ErrorMP/MaxNMP) # total error f0index = np.argmin(Error) # get the smallest error f0 = f0c[f0index] # f0 with the smallest error return f0, ErrorPM, ErrorMP, Error (fs, x) = WIO.wavread('../../../sounds/piano.wav') start = .3*fs N = 2048 hN = N/2 M = 1501 t = -70 minf0 = 50 maxf0 = 800 w = blackman (M) x1 = x[start:start+M] mX, pX = dftAnal.dftAnal(x1, w, N) ploc = PP.peakDetection(mX, hN, t) iploc, ipmag, ipphase = PP.peakInterp(mX, pX, ploc) ipfreq = fs * iploc/N f0cand = np.arange(minf0, maxf0, 1.0) maxnpeaks = 10 f0, ErrorPM, ErrorMP, Error = TWM (ipfreq, ipmag, maxnpeaks, f0cand) freqaxis = fs*np.arange(N/2)/float(N) plt.figure(1) plt.subplot (2,1,1) plt.plot(freqaxis,mX,'r') plt.axis([100,5000,-90,max(mX)+1]) plt.plot(fs * iploc / N, ipmag, marker='x', color='b', linestyle='')
from scipy.fftpack import fft # Number of sample points N = 600 # sample spacing T = 1.0 / 800.0 x = np.linspace(0.0, N*T, N) y = np.sin(50.0 * 2.0*np.pi*x) + 0.5*np.sin(80.0 * 2.0*np.pi*x) yf = fft(y) from scipy.signal import blackman w = blackman(N) ywf = fft(y*w) xf = np.linspace(0.0, 1.0/(2.0*T), N/2) import matplotlib.pyplot as plt plt.semilogy(xf[1:N/2], 2.0/N * np.abs(yf[1:N/2]), '-b') plt.semilogy(xf[1:N/2], 2.0/N * np.abs(ywf[1:N/2]), '-r') plt.legend(['FFT', 'FFT w. window']) plt.grid() plt.show()
from OSC import OSCServer, OSCClient, OSCMessage import os from time import time N = 1024 p5.size(1024, 512) client = OSCClient() client.connect(('127.0.0.1', 9999)) recent = [] window = blackman(N) vectors = [] labels = [] def getAmplitude(data): freq = sfft.fft(data * window) nyquist = len(freq)/2 return np.absolute(freq[:nyquist]) clf = SVC(probability=True, kernel = 'rbf') model = lda.LDA(n_components=2) projection = [] p_min = None p_max = None predicted = None
p_mean_sub = p_mean - sigmoidalFunction(t, *popt) # Plot the result legend_data = [] for var in variables_legend: legend_data.append(combination[var]) legend_str = legend_format.format(*legend_data) # Plot absolute values line, = ax.plot(t, p_mean, label=legend_str) ax.plot(t, sigmoidalFunction(t, *popt), '--k') color = line.get_color() ax.fill_between(t, p_mean-p_std, p_mean+p_std, facecolor=color, alpha=0.3) # Plot FFT freq = np.fft.fftfreq(t.shape[-1])/dt w = blackman(n_steps) sp = np.fft.fft(p_mean_sub) ax3.plot(freq[0:n_steps*dt], np.abs(sp)[0:n_steps*dt]) contrib = np.abs(sp)[0:n_steps*dt] freq_max_val = np.average(freq[0:n_steps*dt], weights=contrib) freq_max.append(freq_max_val) ax_sub.plot(t, p_mean_sub) ax2.plot(variable, max_val) ax4.plot(variable, chract_time) slope, intercept, r_value, p_value, std_err = stats.linregress(np.array(variable),np.array(chract_time)) print(slope, r_value**2) print(freq_max)