def _stft(self): if not self._have_x: print "Error: You need to load a sound file first: use self.load_audio('filename.wav')" return False fp = self._check_feature_params() num_frames = len(self.x) self.STFT = P.zeros((self.nfft/2+1, num_frames), dtype='complex') self.win = P.ones(self.wfft) if self.window=='rect' else P.np.sqrt(P.hanning(self.wfft)) x = P.zeros(self.wfft) buf_frames = 0 for k, nex in enumerate(self.x): x = self._shift_insert(x, nex, self.nhop) if self.nhop >= self.wfft - k*self.nhop : # align buffer on start of audio self.STFT[:,k-buf_frames]=P.rfft(self.win*x, self.nfft).T else: buf_frames+=1 self.STFT = self.STFT / self.nfft self._fftfrqs = P.arange(0,self.nfft/2+1) * self.sample_rate/float(self.nfft) self._have_stft=True if self.verbosity: print "Extracted STFT: nfft=%d, hop=%d" %(self.nfft, self.nhop) self.inverse=self._istftm self.X = abs(self.STFT) if not self.magnitude: self.X = self.X**2 return True
def _stft(self): if not self._have_x: print( "Error: You need to load a sound file first: use self.load_audio('filename.wav')" ) return False fp = self._check_feature_params() num_frames = len(self.x) self.STFT = P.zeros((int(self.nfft / 2 + 1), num_frames), dtype='complex') self.win = P.ones(self.wfft) if self.window == 'rect' else P.np.sqrt( P.hanning(self.wfft)) x = P.zeros(self.wfft) buf_frames = 0 for k, nex in enumerate(self.x): x = self._shift_insert(x, nex, self.nhop) # align buffer on start of audio if self.nhop >= self.wfft - k * self.nhop: self.STFT[:, k - buf_frames] = P.rfft(self.win * x, self.nfft).T else: buf_frames += 1 self.STFT = self.STFT / self.nfft self._fftfrqs = P.arange( 0, self.nfft / 2 + 1) * self.sample_rate / float(self.nfft) self._have_stft = True if self.verbosity: print("Extracted STFT: nfft=%d, hop=%d" % (self.nfft, self.nhop)) self.inverse = self._istftm self.X = abs(self.STFT) if not self.magnitude: self.X = self.X**2 return True
def plot_signal(s,sr,start=0,end=440,N=32768): '''plots the waveform and spectrum of a signal s with sampling rate sr, from a start to an end position (waveform), and from a start position with a N-point DFT (spectrum)''' pl.figure(figsize=(8,5)) pl.subplot(211) sig = s[start:end] time = pl.arange(0,len(sig))/sr pl.plot(time,sig, 'k-') pl.ylim(-1.1,1.1) pl.xlabel("time (s)") pl.subplot(212) N = 32768 win = pl.hanning(N) scal = N*pl.sqrt(pl.mean(win**2)) sig = s[start:start+N] window = pl.rfft(sig*win/max(sig)) f = pl.arange(0,len(window)) bins = f*sr/N mags = abs(window/scal) spec = 20*pl.log10(mags/max(mags)) pl.plot(bins,spec, 'k-') pl.ylim(-60, 1) pl.ylabel("amp (dB)", size=16) pl.xlabel("freq (Hz)", size=16) pl.yticks() pl.xticks() pl.xlim(0,sr/2) pl.tight_layout() pl.show()
def spec_env(frame, coefs): mags = abs(frame) N = len(mags) ceps = pl.rfft(pl.log(mags[:N - 1])) ceps[coefs:] = 0 mags[:N - 1] = pl.exp(pl.irfft(ceps)) return mags
def pconv(input, ir, S=1024): N = len(ir) L = len(input) M = S * 2 P = int(pl.ceil(N / S)) H = pl.zeros((P, M // 2 + 1)) + 0j X = pl.zeros((P, M // 2 + 1)) + 0j x = pl.zeros(M) o = pl.zeros(M) s = pl.zeros(S) for i in range(0, P): p = (P - 1 - i) * S ll = len(ir[p:p + S]) x[:ll] = ir[p:p + S] H[i] = pl.rfft(x) y = pl.zeros(L + N - 1) n = S i = 0 for p in range(0, L + N - S, S): if p > L: x = pl.zeros(M) else: if n + p > L: n = L - p x[n:] = pl.zeros(M - n) x[:n] = input[p:p + n] X[i] = pl.rfft(x) i = (i + 1) % P O = pl.zeros(M // 2 + 1) + 0j for j in range(0, P): k = (j + i) % P O += H[j] * X[k] o = pl.irfft(O) y[p:p + S] = o[:S] + s s = o[S:] return y
def _stft(self): if not self._have_x: print "Error: You need to load a sound file first: use self.load_audio('filename.wav')" return False fp = self._check_feature_params() WX = self._win_mtx(self.x, fp['wfft'], fp['nhop'], fp['nsamples']) self.STFT=pylab.rfft(WX, fp['nfft']).T self.STFT/=fp['nfft'] self._have_stft=True if fp['verbosity']: print "Extracted STFT: nfft=%d, hop=%d" %(fp['nfft'], fp['nhop']) return True
def conv(input, ir): N = len(ir) L = len(input) M = 2 while (M <= 2 * N - 1): M *= 2 h = pl.zeros(M) x = pl.zeros(M) y = pl.zeros(L + N - 1) h[0:N] = ir H = pl.rfft(h) n = N for p in range(0, L, N): if p + n > L: n = L - p x[n:] = pl.zeros(M - n) x[0:n] = input[p:p + n] y[p:p + 2 * n - 1] += pl.irfft(H * pl.rfft(x))[0:2 * n - 1] return y
def TemporalSpectPlot(self, d,wmin,wmax): self.fig.clear() sp = Axes3D(self.fig) ndav, int_step, cc = self.more_opts_extr() ll = len(d[0])-1 for i in ll-np.arange(ll): y=i*np.ones(len(d)/2) sp.plot(fftfreq(len(d), (d[1,0]-d[0,0])/(ndav/cc))[:len(d)/2], y ,abs(rfft(d[:,i]))[:-1]) sp.set_xlim3d(wmin,wmax) sp.set_xlabel(r'$\omega/\omega_0$',fontsize=14) sp.set_ylabel('node index',fontsize=14) sp.set_zlabel(r'$\langle E_z \rangle_\omega$',fontsize=14) self.canvas.show()
def run_WN(photoreceptor, I): Z_dictionary = {} V_dictionary = {} Vl_dictionary = {} I_dictionary = {} for i, V in enumerate(Vr): DepolarisePhotoreceptor.WithLight(photoreceptor, V) ## Filtering signal print("Processing V=", V, " mV") ## Run HH print("Running HH...") Vm, g = Experiment.inject_current(photoreceptor, I, dt) Vl = Linearise.inject_current(photoreceptor, I, dt) print("Variance of voltage is ", var(Vm), "mV2") ## Calculate impedance Vmm = (Vm - mean(Vm)) #without DC CPSD = zeros(round(len(time) / 2 + 1), dtype=complex_) PSD = zeros(round(len(time) / 2 + 1)) window = hamming(len(time)) print("len(window)", len(window)) for ii in range(repetitions): I_cut = I[ii * len(time):(ii + 1) * len(time)] V_cut = Vmm[ii * len(time):(ii + 1) * len(time)] PSD += power(absolute(rfft(I_cut * window)), 2) CPSD += rfft(V_cut * window) * rfft(I_cut * window).conjugate() Z = CPSD / PSD #MOhm Z_dictionary[V] = Z I_dictionary[V] = I[sample * len(time):(sample + 1) * len(time)] V_dictionary[V] = Vm[sample * len(time):(sample + 1) * len(time)] Vl_dictionary[V] = Vl[sample * len(time):(sample + 1) * len(time)] return (Z_dictionary, V_dictionary, Vl_dictionary, I_dictionary)
def true_spec_env(frame, coefs, thresh): N = len(frame) form = pl.zeros(N) lmags = pl.log(abs(frame[:N - 1])) mags = lmags go = True while (go): ceps = pl.rfft(lmags) ceps[coefs:] = 0 form[:N - 1] = pl.irfft(ceps) go = False for i in range(0, N - 1): if lmags[i] < form[i]: lmags[i] = form[i] diff = mags[i] - form[i] if diff > thresh: go = True return pl.exp(form)
def true_spec_env(amps,coefs,thresh): N = len(amps) sm = 10e-15 form = pl.zeros(N) lmags = pl.log(amps[:N-1]+sm) mags = lmags check = True while(check): ceps = pl.rfft(lmags) ceps[coefs:] = 0 form[:N-1] = pl.irfft(ceps) for i in range(0,N-1): if lmags[i] < form[i]: lmags[i] = form[i] diff = mags[i] - form[i] if diff > thresh: check = True else: check = False return pl.exp(form)+sm
def fft_filter(time, signal, result, window_func=pl.hanning, \ samp_freq=8, freq_limit = (0.0033, 0.04)): """ Applies an Band Pass filter to signal in the frequency domain and returns filterd PSD. In: time : ndarray, relative R occurance times vector signal : ndarray, HRV vector result : dict, current fragment info (see process function) samp_freq : int, signal sample frequency freq_limit : tuple, (min, max) frequencies for band pass filter Out: freq_filt_log : ndarray, frequency in logarithm scale spec_filt_log : ndarray, PSD in logarithm scale """ window = window_func(len(signal)) # window signal_wed = signal * window n = len(signal)/2 spec = (pl.absolute(pl.rfft(signal_wed))[:-1]/(n))**2 # entering to frequency domain freq = pl.fftfreq(len(signal), 1.0/samp_freq)[:n] # get freqs axis values spec_filt = pl.zeros(spec.shape, dtype='float') freq_filt = pl.zeros(freq.shape, dtype='float') # same for filtered for i in range(n): # filter by frequency if pl.logical_and(freq_limit[0] <= abs(freq[i]), abs(freq[i]) <= freq_limit[1]): freq_filt[i] = freq[i] spec_filt[i] = spec[i] else: freq_filt[i] = 0 # fill invalid frequencies with 0 value spec_filt[i] = 0 spec_filt = pl.ma.masked_equal(spec_filt,0) # cutt off invalid values spec_filt = pl.ma.compressed(spec_filt) freq_filt = pl.ma.masked_equal(freq_filt,0) freq_filt = pl.ma.compressed(freq_filt) spec_filt_log = pl.log10(spec_filt) # for output freq_filt_log = pl.log10(freq_filt) return freq_filt_log, spec_filt_log
def SpecEvolPlot(self, d,windwidth,step,wmin,wmax, rowind): dd=np.array([]) ndav, int_step, cc = self.more_opts_extr() Tim=np.arange(windwidth, len(d)-windwidth,step) for n in Tim: dd=np.append(dd, np.abs(rfft(d[n-windwidth:n+windwidth,rowind]))[:-1]) Freq=fftfreq(2*windwidth, (d[1,0]-d[0,0])/(ndav/cc))[:windwidth] if wmax!=0: nFrqMax= int(wmax/(Freq[1]-Freq[0])) else: nFrqMax=len (Freq) nFrqMin= int(wmin/(Freq[1]-Freq[0])) dd=dd.reshape(len(Tim),len(Freq))[:,nFrqMin:nFrqMax].transpose() self.fig.clear() sp = self.fig.add_subplot(111) pplt = sp.imshow(dd, origin='lower',aspect='auto',extent=[d[Tim[0],0]/(ndav/cc), d[Tim[-1],0]/(ndav/cc),Freq[nFrqMin],Freq[nFrqMax]]) sp.set_xlabel(r'$t/\tau_0$',fontsize=14) sp.set_ylabel(r'$\omega/\omega_0$',fontsize=14) self.fig.colorbar(pplt) self.canvas.show() return
#! /usr/bin/env python from pylab import figure, loadtxt, arange, ones, fftfreq, rfft from mpl_toolkits.mplot3d import Axes3D fig = figure() ax = Axes3D(fig) inp = raw_input("input xfel_xx number xx and node index:").split(' ') xx = inp[0] node = inp[1] d = loadtxt('../xfel_' + xx + '/etc/fld_00' + node + '_000') ll = len(d[0]) - 1 for i in ll - arange(ll): y = i * ones(len(d) / 2) ax.plot(fftfreq(len(d), 0.04)[:len(d) / 2], y, abs(rfft(d[:, i]))[:-1]) ax.set_xlim3d(0.9, 1.1) fig.show() fig.show() raw_input("Press Enter to continue...")
import pylab as pl pi = pl.pi T = 1000 t = pl.arange(0, T) x = 0.51 - 0.49 * pl.cos(2 * pi * t / T) y = pl.sin(2 * pi * 10 * t / T) X = pl.rfft(y * x) pl.plot(pl.irfft(X)) pl.show()
import pylab as pl T = 64 t = pl.arange(0, T) env = pl.zeros(T) pl.figure(figsize=(8, 3)) sig = pl.sin(2 * pl.pi * (T / 4) * t / T) * pl.hanning(T) pl.ylim(0, 1.1) pl.xlim(0, T // 2) pl.xticks([x for x in range(0, T // 2 + 1, 4)]) pl.stem(t[0:T // 2], abs(pl.rfft(sig) / (T / 4))[0:T // 2], 'k-', linewidth=1) pl.tight_layout() pl.show()
def speriodogram(x, NFFT=None, detrend=True, sampling=1., scale_by_freq=True, window='hamming', axis=0): """Simple periodogram, but matrices accepted. :param x: an array or matrix of data samples. :param NFFT: length of the data before FFT is computed (zero padding) :param bool detrend: detrend the data before co,puteing the FFT :param float sampling: sampling frequency of the input :attr:`data`. :param scale_by_freq: :param str window: :return: 2-sided PSD if complex data, 1-sided if real. if a matrix is provided (using numpy.matrix), then a periodogram is computed for each row. The returned matrix has the same shape as the input matrix. The mean of the input data is also removed from the data before computing the psd. .. plot:: :width: 80% :include-source: from pylab import * from spectrum import * data = data_cosine(N=1024, A=0.1, sampling=1024, freq=200) semilogy(speriodogram(data, detrend=False, sampling=1024), marker='o') grid(True) .. plot:: :width: 80% :include-source: from spectrum import * from pylab import * # create N data sets and make the frequency dependent on the time N = 100 m = numpy.concatenate([data_cosine(N=1024, A=0.1, sampling=1024, freq=x) for x in range(1, N)]); m.resize(N, 1024) res = speriodogram(m) figure(1) semilogy(res) figure(2) imshow(res.transpose(), aspect='auto') .. todo:: a proper spectrogram class/function that takes care of normalisation """ x = array(x) # array with 1 dimension case if x.ndim == 1: axis = 0 r = x.shape[0] w = Window(r, window) #same size as input data # matrix case elif x.ndim == 2: print('2D array. each row is a 1D array') [r, c] = x.shape if r==1: r = c w = Window(x.size, window) #same size as input data else: w = Window(c, window) #same size as input data if NFFT is None: NFFT = len(x) isreal = numpy.isrealobj(x) if detrend == True: m = mean(x, axis=axis) else: m = 0 if isreal == True: res = (abs (rfft (x*w.data - m, NFFT))) ** 2. / r else: res = (abs (fft (x*w.data - m, NFFT ))) ** 2. / r if scale_by_freq is True: df = sampling / float(NFFT) res*= 2*pi/df return res.transpose()
def stft(x, w, n): N = len(w) X = pl.rfft(w * x) k = pl.arange(0, N / 2 + 1) return X * pl.exp(2 * pl.pi * 1j * k * n / N)
sampling_frequency = wf.GetSamplingFrequency() sampling_period = wf.GetSamplingPeriod() if wf3count == 0 and channel == OPPI3ChannelNumber: avgwf3.MakeSimilarTo(rawwf) if wf4count == 0 and channel == OPPI4ChannelNumber: avgwf4.MakeSimilarTo(rawwf) if goodOPPI3Waveform: rawwf.MakeSimilarTo(avgwf3) avgwf3 += rawwf # Sample baseline from baseline window a3base = numpy.ndarray( int(baselineAverageTime / sampling_period), dtype="float", buffer=rawwf.GetData() ) a3base = a3base / a3base.max() if wf3count == 0: a3bFFT = pylab.rfft(a3base) else: a3bFFT += pylab.rfft(a3base) print a3bFFT * pylab.conj(a3bFFT) raw_input("Press Enter to continue") pylab.subplot(2, 1, 1) X3 = numpy.arange(0, numpy.size(a3bFFT)) pylab.plot(X3, sampling_period * sampling_period * a3bFFT * pylab.conj(a3bFFT), label="OPPI3") pylab.subplot(2, 1, 2) pylab.psd(a3base, Fs=100e6) fig.canvas.draw() # pylab.plot(X3,a3bFFT,label='OPPI3') # print "OPPI3 ", eventTime , avgwf3.GetLength(), a3.size , a3 wf3count += 1 if goodOPPI4Waveform: rawwf.MakeSimilarTo(avgwf4)
import pylab as pl import numpy as np import seaborn as sns WD721 = np.loadtxt("/home/russell/Desktop/matplotlib/WaveData721.csv", skiprows = 3, delimiter = ',') pl.figure() pl.clf() fx2 = np.arange(0, 2001) fx2 = fx2/0.02 #scaling factor sns.set_context("notebook", rc={"lines.linewidth": 1.5}) sns.set_style("darkgrid") sns.set_palette("husl") wave = WD721[0:4000, 1] #The wave off the osciliscope pl.subplot(2,2,1) pl.title("Wave") pl.plot(wave) #Plotting The Wave pl.xlim([1050, 1600]) pl.subplot(2,2,2) pl.title("Square of wave") pl.plot(wave**2) #Plotting the square of The Wave pl.xlim([1050, 1600]) pl.subplot(2,2,3) pl.title("Spectrum of wave") pl.plot(fx2, abs(pl.rfft(wave))) #Plotting the Fourier transform of The Wave pl.xlim([36000, 44000]) pl.xlabel("frequency") pl.subplot(2,2,4) pl.title("Spectrum of wave^2") pl.plot(fx2, abs(pl.rfft(wave**2))) pl.xlim([-100, 4500]) pl.xlabel("frequency") pl.tight_layout()
pl.figure(figsize=(8, 5)) pl.subplot(211) pl.title('waveform') end = N t = pl.arange(0, end) / float(sr) pl.xlim(0, t[end - 1]) pl.ylim(-1.1, 1.1) pl.xlabel("time (s)") pl.plot(t, sig[0:end], 'k') pl.subplot(212) pl.title('spectral envelope') x = pl.arange(0, N / 2) bins = x * sr / N spec = pl.fft(sig / max(sig)) mags = abs(spec / N) logm = pl.log(mags) ceps = pl.rfft(logm) ceps2 = pl.zeros(len(ceps)) ceps2[0:50] = ceps[0:50] specenv = pl.exp(pl.irfft(ceps2)) spec1 = 20 * pl.log10(mags / max(mags)) pl.ylim(-40, 1) pl.ylabel("amp (dB)") pl.xlabel("freq (Hz)") pl.xlim(0, 2000) pl.tight_layout() pl.plot(bins[0:N / 2], spec1[0:N / 2], 'k-', linewidth=2) pl.show()
def stft(x, w): X = pl.rfft(x * w) return X
#! /usr/bin/env python from pylab import figure, loadtxt, arange, ones,fftfreq, rfft from mpl_toolkits.mplot3d import Axes3D fig = figure() ax = Axes3D(fig) inp = raw_input("input xfel_xx number xx and node index:").split(' ') xx = inp[0] node=inp[1] d = loadtxt('../xfel_'+xx+'/etc/fld_00'+node+'_000') ll = len(d[0])-1 for i in ll-arange(ll): y=i*ones(len(d)/2) ax.plot(fftfreq(len(d), 0.04)[:len(d)/2], y ,abs(rfft(d[:,i]))[:-1]) ax.set_xlim3d(0.9,1.1) fig.show() fig.show() raw_input("Press Enter to continue...")
def SpectSpacePlotter(self,f,Res, reg, TIM = None, out_name = None, flag3D='2D', frmt='png'): Nx, Ny, Lx, Ly, N_nodes = self.OptsExtr() ndav, int_step, cc = self.more_opts_extr() actual_time = int(TIM)*int_step/ndav Nx1, Nx2, Ny1, Ny2, Fmin, Fmax, res, res_x, res_y, clrmap, freq_min, freq_max,freq2_min, freq2_max, ax = Res res, res_x, res_y, Nx1, Nx2, Ny1, Ny2,freq_max = int(res), int(res_x), int(res_y), float(Nx1),float(Nx2),float(Ny1),float(Ny2), float(freq_max) Nx1=int(np.rint(Nx1*Nx/Lx));Nx2=int(np.rint(Nx2*Nx/Lx)) Ny1=int(np.rint(Ny1*Ny/Ly));Ny2=int(np.rint(Ny2*Ny/Ly)) dX=Lx/Nx dY=Ly/Ny X=np.linspace(0,Lx,Nx) Y=np.linspace(0,Ly,Ny) dx, dy = self.StepDef(Res[:-5]) if Fmin == 0.: Fmin = None if Fmax == 0.: Fmax= None if Nx2==0: Nx2 = Nx-1 if Ny2==0: Ny2 = Ny-1 if ax=='x': Nn1=Nx Nn2=Ny Xx=X Yy=Y Ll=Ly ddx=int(np.ceil(dx/2.)) ddy=dy freq_min, freq_max = freq_min, freq_max elif ax=='y': f=f.transpose() Nn1=np.shape(f)[1] Nn2=Nx Xx=Y Yy=X Ll=Lx ddx=int(np.ceil(dy/2.)) ddy=dx freq_min, freq_max = freq2_min, freq2_max datFFT = np.zeros((Nn2, Nn1/2+1)) XFFT = abs(fftfreq( Nn1, Xx[1])[:Nn1/2+1]) for j in np.arange(Nn2): datFFT[j] = abs(rfft(f[j])) myextent=[XFFT[0],XFFT[-1],Yy[0],Yy[-1]] self.fig.clear() if flag3D == '3D': XX, YY = np.meshgrid(XFFT, Yy) sp = Axes3D(self.fig, title='time step = '+str(actual_time)+r'$ \tau_0$') sp.plot_surface(XX,YY,datFFT, cmap = clrmap, linewidth=0) sp.set_zlim3d(Fmin,Fmax) if flag3D == '2D': sp = self.fig.add_subplot(111, title='time step = '+str(actual_time)+r'$ \tau_0$') if ax=='x': sp.set_ylabel(r'$y/\lambda_0$',fontsize=14) sp.set_xlabel(r'$k_x/k_0$',fontsize=14) elif ax=='y': sp.set_ylabel(r'$x/\lambda_0$',fontsize=14) sp.set_xlabel(r'$k_y/k_0$', fontsize=14) pplt = sp.imshow(datFFT[::ddy,::ddx],extent=myextent, aspect = 'auto', interpolation=intrp,origin='lower',vmin=Fmin, vmax=Fmax, cmap = clrmap) sp.axis((freq_min,freq_max,0,Ll)) self.fig.colorbar(pplt) self.canvas.show() if reg == 'wrt': self.fig.savefig('./img/'+self.out_name_add+'_'+out_name+'_s'+ax+'_'+TIM+'.'+frmt) clf() return