def decodefft(finf,data, dropheights = False): #output: decoded data with the number of heights reduced #two variables are added to the finfo class: #deco_num_hei, deco_hrange #data must be arranged: # (channels,heights,times) (C-style, profs change faster) #fft along the entire(n=None) acquired heights(axis=1), stores in data num_chan = data.shape[0] num_ipps = data.shape[2] num_codes = finf.subcode.shape[0] num_bauds = finf.subcode.shape[1] NSA = finf.num_hei + num_bauds - 1 uppower = py.ceil(py.log2(NSA)) extra = int(2**uppower - finf.num_hei) NSA = int(2**uppower) fft_code = py.fft(finf.subcode,n = NSA,axis=1).conj() data = py.fft(data,n=NSA,axis=1) #n= None: no cropped data or padded zeros for ch in range(num_chan): for ipp in range(num_ipps): code_i = ipp % num_codes data[ch,:,ipp] = data[ch,:,ipp] * fft_code[code_i,:] data=py.ifft(data,n=NSA,axis=1) #fft along the heightsm if dropheights: return data[:,:-extra-(num_bauds-1),:] else: return data[:,:-extra,:]
def decodefft(finf, data, dropheights=False): #output: decoded data with the number of heights reduced #two variables are added to the finfo class: #deco_num_hei, deco_hrange #data must be arranged: # (channels,heights,times) (C-style, profs change faster) #fft along the entire(n=None) acquired heights(axis=1), stores in data num_chan = data.shape[0] num_ipps = data.shape[2] num_codes = finf.subcode.shape[0] num_bauds = finf.subcode.shape[1] NSA = finf.num_hei + num_bauds - 1 uppower = py.ceil(py.log2(NSA)) extra = int(2**uppower - finf.num_hei) NSA = int(2**uppower) fft_code = py.fft(finf.subcode, n=NSA, axis=1).conj() data = py.fft(data, n=NSA, axis=1) #n= None: no cropped data or padded zeros for ch in range(num_chan): for ipp in range(num_ipps): code_i = ipp % num_codes data[ch, :, ipp] = data[ch, :, ipp] * fft_code[code_i, :] data = py.ifft(data, n=NSA, axis=1) #fft along the heightsm if dropheights: return data[:, :-extra - (num_bauds - 1), :] else: return data[:, :-extra, :]
def f( t, *args ): for i,arg in enumerate(args): params[ free_params[i] ] = arg tshift = params[-1] ideal = fmodel( t, *args ) irf = cspline1d_eval( self.irf_generator, t-tshift, dx=self.irf_dt, x0=self.irf_t0 ) convoluted = pylab.real(pylab.ifft( pylab.fft(ideal)*pylab.fft(irf) )) # very small imaginary anyway return convoluted
def main(): pylab.ion(); ind = [0,]; ldft = [0,]; lfft = [0,]; lpfft = [0,] # plot a graph Dft vs Fft, lists just support size until 2**9 for i in range(1, 9, 1): t_before = time.clock(); dsprocessing.dspDft(rand(2**i).tolist()); dt = time.clock() - t_before; ldft.append(dt); print ("dft ", 2**i, dt); #pylab.plot([2**i,], [time.clock()-t_before,]); t_before = time.clock(); dsprocessing.dspFft(rand(2**i).tolist()); dt = time.clock() - t_before; print ("fft ", 2**i, dt); lfft.append(dt); #pylab.plot([2**i,], [time.clock()-t_before,]); ind.append(2**i); # python fft just to compare t_before = time.clock(); pylab.fft(rand(2**i).tolist()); dt = time.clock() - t_before; lpfft.append(dt); pylab.plot(ind, ldft); pylab.plot(ind, lfft); pylab.plot(ind, lpfft); pylab.show(); return [ind, ldft, lfft, lpfft];
def fast_fracdiff(x, d): T = len(x) np2 = int(2**np.ceil(np.log2(2 * T - 1))) k = np.arange(1, T) b = (1, ) + tuple(np.cumprod((k - d - 1) / k)) z = (0, ) * (np2 - T) z1 = b + z z2 = tuple(x) + z dx = pl.ifft(pl.fft(z1) * pl.fft(z2)) return np.real(dx[0:T])
def _ConvFft(signal, FilterKernel): """ Convolution with fft much faster approach works exactly as convolve(x,y) """ ss = numpy.size(signal); fs = numpy.size(FilterKernel) # padd zeros all until they have the size N+M-1 signal = numpy.append(signal, numpy.zeros(fs+ss-1-ss)); FilterKernel = numpy.append(FilterKernel, numpy.zeros(fs+ss-1-fs)); signal = pylab.real(pylab.ifft(pylab.fft(signal)*pylab.fft(FilterKernel))); return signal[:fs+ss-1];
def fast_fracdiff(x, cols, d): for col in cols: T = len(x[col]) np2 = int(2**np.ceil(np.log2(2 * T - 1))) k = np.arange(1, T) b = (1, ) + tuple(np.cumprod((k - d - 1) / k)) z = (0, ) * (np2 - T) z1 = b + z z2 = tuple(x[col]) + z dx = pl.ifft(pl.fft(z1) * pl.fft(z2)) x[col + "_frac"] = np.real(dx[0:T]) return x
def _ConvFft(signal, filterkernel): """ Convolution with fft much faster approach works exatcly as convolve(x,y) """ ss = numpy.size(signal) fs = numpy.size(filterkernel) # padd zeros all until they have the size N+M-1 signal = numpy.append(signal, numpy.zeros(fs + ss - 1 - ss)) filterkernel = numpy.append(filterkernel, numpy.zeros(fs + ss - 1 - fs)) signal = pylab.real(pylab.ifft( pylab.fft(signal) * pylab.fft(filterkernel))) return signal[:fs + ss - 1]
def calcFourier(self, yout, tspan): ''' Calculate FFT and return magnitude spectrum and frequencies freqs === Python array aMags === numpy array rMags === numpy array ''' ActEC = yout[:, 3] RepEC = yout[:, 9] freqs = fftfreq(len(tspan), tspan[1] - tspan[0]) aMags = array(abs((fft(ActEC)))) rMags = array(abs((fft(RepEC)))) return freqs, aMags, rMags
def compute_response(self, **kargs): """Compute the window data frequency response :param norm: True by default. normalised the frequency data. :param int NFFT: total length of the final data sets( 2048 by default. if less than data length, then NFFT is set to the data length*2). The response is stored in :attr:`response`. .. note:: Units are dB (20 log10) since we plot the frequency response) """ from pylab import fft, fftshift, log10 norm = kargs.get('norm', self.norm) # do some padding. Default is max(2048, data.len*2) NFFT = kargs.get('NFFT', 2048) if NFFT < len(self.data): NFFT = self.data.size * 2 # compute the fft modulus A = fft(self.data, NFFT) mag = abs(fftshift(A)) # do we want to normalise the data if norm is True: mag = mag / max(mag) response = 20. * log10(mag) # factor 20 we are looking at the response # not the powe #response = clip(response,mindB,100) self.__response = response
def PlotFftNAbs(y, dt=0.1 ): # plot the grah of fft (amplitude) of y with command plot """ Normalized version plot of FFT equal abs(FFT) * 2/y.length plot also just half spectrum (just positive frequencies), and from frequencys 1:N/2 the mean (DC component) is removed before fft """ N = numpy.size(y) #remove the DC component just the mean (could use a detrend function) y = y - numpy.mean(y) fund = 1 / (N * dt) # freq fundamental, as outras sao multiplas dessa f = range(N) for k in range(N - 1): f[k + 1] = fund * k #multiplas da fundamental yn = pylab.fft(y) # perfeito. se vpce colocar um seno de 30 e outro de 60, com aplitude 1 e 2 no espectro # de amplitude voce vai encontrar exatamente 1 e 2 absyn = 2 * numpy.abs(yn) / numpy.size(yn) pylab.plot(f[0:numpy.size(f) / 2], absyn[0:numpy.size(f) / 2]) return [f, absyn]
def PlotPowersSpectrumdB(y, dt=0.1): """ Try of power spectral density estimation not windowed no Welch yet. plot also just half spectrum (just positive frequencies), and from frequencys 0:N/2 the mean (DC component) is removed before fft """ # plot the grah of fft (amplitude) of y with command plot N = numpy.size(y) #remove the DC component just the mean (could use a detrend function) y = y - numpy.mean(y) fund = 1 / (N * dt) # freq fundamental, as outras sao multiplas dessa f = range(N) for k in range(N - 1): f[k + 1] = fund * k #multiplas da fundamental yn = pylab.fft(y) power = yn * numpy.conj(yn) / (numpy.sqrt(numpy.size(yn))) power = numpy.abs(power) # create decibel scale Lb = log10(P1/P0) where P0 is the maximum value P0 = max(power) power = numpy.log10(power / P0) #ignore Dc and the negative frequencies pylab.plot(f[0:numpy.size(f) / 2], power[0:numpy.size(f) / 2])
def performFourierDataReturn(self, wav_name, input_location=None): if input_location == None: input_location = '' if wav_name.endswith('.wav'): wav_file_name = os.path.join( os.path.join(__location__, input_location), wav_name) else: wav_file_name = os.path.join( os.path.join(__location__, input_location), wav_name) + '.wav' sampFreq, snd = wavfile.read(wav_file_name) # convert 16 bit values to be between -1 to 1 snd /= 2.0**15 # get average of data if more than 1 channels if self.channels > 1: s1 = self.getAverageData(snd) else: s1 = snd.T[0] n = len(s1) p = fft(s1) nUniquePts = int(ceil((n + 1) / 2.0)) p = p[0:nUniquePts] p = abs(p) p /= float(n) p **= 2 if n % 2 > 0: p[1:len(p)] = p[1:len(p)] * 2 else: p[1:len(p) - 1] = p[1:len(p) - 1] * 2 return sampFreq, nUniquePts, n, p
def hacerfft(channel): tamanho = len(channel) fdata = fft(channel) print('> FFT realizada') nUniquePts = int(ceil((tamanho)/2)) fdata = fdata[0:nUniquePts] fdata = abs(fdata) fdata = fdata/float(leng) fdata = fdata**2 if leng % 2 > 0: fdata[1:int(ceil(len(fdata)))] = fdata[1:int(ceil(len(fdata)))] * 2 else: fdata[1:int(ceil(len(fdata)))-1] = fdata[1:int(ceil(len(fdata)))-1] * 2 freqArray = arange(0, nUniquePts, 1.0)*(fs/tamanho) plot(freqArray/1000, 10*log10(fdata[0:tamanho:1])) xlabel('Frequency (kHz)') ylabel('Power (dB)') plt.show() print('> FFT graficada') return fdata
def time_fft(data2, samplerate=100., inverse=False,hann=False): ''' IF N_PARAMS() EQ 0 then begin print, 'time_fft, data, samplerate=samplerate, inverse=inverse,hann=hann' return, -1 ENDIF ''' data=data2 if hann: w1 = pl.hanning(len(data)) data = data*w1 #frequency axis: freqs = pl.arange(1+len(data)/2)/float(len(data)/2.0)*samplerate/2. # wut. if len(data) % 2 == 0 : freqs = pl.concatenate((freqs, -freqs[1:(len(freqs)-1)][::-1])) if len(data) % 2 != 0 : freqs = pl.concatenate((freqs, -freqs[1:len(freqs)][::-1])) response = pl.fft(data) if inverse : response = pl.ifft(data) out = {'freq': freqs, 'real': response.real, 'im': response.imag, 'abs': abs(response)} return out
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 f = pl.arange(0,N/2) bins = f*sr/N win = pl.hanning(N) scal = N*pl.sqrt(pl.mean(win**2)) sig = s[start:start+N] window = pl.fft(sig*win/max(sig)) mags = abs(window/scal) spec = 20*pl.log10(mags/max(mags)) pl.plot(bins,spec[0:N//2], '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 hacerfft(channel, texto=None): fdata = fft(channel) print('\t> FFT realizada') nUniquePts = int(ceil((leng) / 2)) fdata = fdata[0:nUniquePts] fdata = abs(fdata) fdata = fdata / float(leng) fdata = fdata**2 if leng % 2 > 0: fdata[1:int(ceil(len(fdata)))] = fdata[1:int(ceil(len(fdata)))] * 2 else: fdata[1:int(ceil(len(fdata))) - 1] = fdata[1:int(ceil(len(fdata))) - 1] * 2 freqArray = arange(0, nUniquePts, 1.0) * (fs / leng) plot(freqArray / 1000, 10 * log10(fdata[0:leng:1])) if texto == None: xlabel('Frequency (kHz)') else: xlabel('Frequency (kHz) | ' + str(texto)) ylabel('Power (dB)') plt.show() print('\t> FFT graficada') return fdata, freqArray
def hacerfft(channel, freq): # en Hz fdata = fft(channel) print('> FFT realizada: ' + str(freq)) nUniquePts = int(ceil((N) / 2)) fdata = fdata[0:nUniquePts] fdata = abs(fdata) fdata = fdata / float(N) fdata = fdata**2 if N % 2 > 0: fdata[1:int(ceil(len(fdata)))] = fdata[1:int(ceil(len(fdata)))] * 2 else: fdata[1:int(ceil(len(fdata))) - 1] = fdata[1:int(ceil(len(fdata))) - 1] * 2 freqArray = arange(0, nUniquePts, 1.0) * (fs / N) plot(freqArray, 10 * log10(fdata[0:int(N):1])) xlabel('Frequency (Hz)') ylabel('Power (dB)') plt.show() print('> FFT graficada ' + str(freq)) return fdata
def __init__(self, path, name=None): if name is None: path, name = os.path.split(path) self.name = name self.path = path self.nowPlaying = False # Read wav file self.sampFreq, self.tDomain = wavfile.read(path + '/' + name) # Get frequency domain fDomain = pylab.fft(self.tDomain) nPoints = len(self.tDomain) nUniquePoints = int(math.ceil((nPoints+1)/2.0)) fDomain = abs(fDomain[0:nUniquePoints]) # Normalize frequency domain fDomain = fDomain/float(nPoints) fDomain = fDomain ** 2 if nPoints % 2 > 0: fDomain[1:len(fDomain)] = fDomain[1:len(fDomain)] * 2 else: fDomain[1:len(fDomain)-1] = fDomain[1:len(fDomain)-1] * 2 # Get frequency values to go with magnitudes time = nPoints / float(self.sampFreq) frequencies = np.arange(nUniquePoints) / time # Store frequency domain as list of (frequency, magnitude) self.fDomain = zip(frequencies, fDomain) # Store sizes of arrays for later self.nPoints = nPoints self.nUniquePoints = nUniquePoints
def STA(pks, I, V, sampr, delay): currents = [] voltages = [] out = {} for i in range(len(pks)): if i == 0: if pks[i] > sampr * (delay + 1): currents.append(I[int(pks[i] - sampr):int(pks[i])]) voltages.append(V[int(pks[i] - sampr):int(pks[i])]) else: if (pks[i] - pks[i - 1]) > sampr: currents.append(I[int(pks[i] - sampr):int(pks[i])]) voltages.append(V[int(pks[i] - sampr):int(pks[i])]) if len(currents): currents = np.array(currents) avgI = np.mean(currents, axis=0) f_current = (fft(avgI) / len(avgI))[0:int(len(avgI) / 2)] Freq = np.linspace(0.0, sampr / 2.0, len(f_current)) out = { 'currents': currents, 'voltages': voltages, 'f_current': f_current, 'Freq': Freq } return out
def PlotPowersSpectrumdB(y, dt=0.1): """ Try of power spectral density estimation not windowed no Welch yet. plot also just half spectrum (just positive frequencies), and from frequencys 0:N/2 the mean (DC component) is removed before fft """ # plot the grah of fft (amplitude) of y with command plot N = numpy.size(y) #remove the DC component just the mean (could use a detrend function) y = y - numpy.mean(y) fund = 1/(N*dt) # freq fundamental, as outras sao multiplas dessa f=range(N) for k in range(N-1): f[k+1]=fund*k #multiplas da fundamental yn = pylab.fft(y) power = yn*numpy.conj(yn)/(numpy.sqrt(numpy.size(yn))) power = numpy.abs(power) # create decibel scale Lb = log10(P1/P0) where P0 is the maximum value P0 = max(power) power = numpy.log10(power/P0); #ignore Dc and the negative frequencies pylab.plot(f[0:numpy.size(f)/2], power[0:numpy.size(f)/2])
def fft_smoothing(input_signal, sigma): """smooth the fast transform Fourier Params : input_signal : audio signal sigma : relative to the length of the output signal Returns : a shorter and smoother signal """ size_signal = input_signal.size #shorten the signal new_size = int(floor(10.0 * size_signal * sigma)) half_new_size = new_size // 2 fftx = fft(input_signal) short_fftx = [] for ele in fftx[:half_new_size]: short_fftx.append(ele) for ele in fftx[-half_new_size:]: short_fftx.append(ele) apodization_coefficients = generate_apodization_coeffs( half_new_size, sigma, size_signal) #apply the apodization coefficients short_fftx[:half_new_size] *= apodization_coefficients short_fftx[half_new_size:] *= flipud(apodization_coefficients) realifftxw = ifft(short_fftx).real return realifftxw
def zonalWN_fourier(signal, lats, lons): """ Function to compute dominant zonal wavenumber at a latitude circle at each time step INPUT: signal (array like): Input signal array. Shape must be [time, lev, lat, lon]. lats: array with latitude values. lons: array with longitude values. OUTPUT: maxWN_mrunmean (array like) : Convolved signal with Hann window of constant width. Shape is [time, lev, lat, lon]. """ notime = signal.shape[0] nolev=signal.shape[1] # loop over all latitudes between lat1 and lat2 (descending in lat) n = (len(lons)+1)//2 A = np.zeros([notime, nolev, len(lats), len(lons)], dtype='complex') # complex array to hold the fourier transf of the input signal power = np.zeros([notime, nolev, len(lats),n]) #k=np.arange(1,n,1) # zonal wavenumber maxWN = np.zeros([notime,nolev, len(lats)]) #loop over time, isentropes and latitudes for t in range (0,notime): for l in range (0,nolev): for ilat in range(0,len(lats)): A[t,l,ilat,:] = pl.fft(signal[t,l,ilat,:]) # fourier transform of the signal (v) at each latitude for kk in range(0,n): # exclude wavenumber 0 power[t,l,ilat,kk] = 4*(A[t,l,ilat,kk].real**2 + A[t,l,ilat,kk].imag**2) maxWN[t,l,ilat] = power[t,l,ilat].argmax(axis=0) # the index at which the maximum in the power spectrum occurs, which is the maximum wavenumber ### Smoothing of the signal ### # fill the remaining latutues with the boundary values ext_lat=10 # extension of the additional boundaries in degrees of latitude res=int(abs(lats[1]-lats[0])) # resolution in lats N = ext_lat//res # window for the moving average in terms of index in the lats array!!! so N=5 is an extended 10 deg boundary for a 2*2 resolution # now apply some smoothing to avoid jumps between different integers wavenumers maxWN_mrunmean=np.zeros([notime, nolev, len(lats)]) for t in range (0,notime): for l in range (0,nolev): maxWN_mrunmean[t,l,:] = np.convolve(maxWN[t,l,:], np.ones((N,))/N, mode='same') maxWN_mrunmean=np.where(maxWN_mrunmean<1,1,maxWN_mrunmean) return maxWN_mrunmean
def compute_fft(self, start, end): dur = end - start fft = pl.fft(self.data[start:end]) real_range = np.ceil((dur+1)/2.0) fft = fft[0:real_range] fft = abs(fft) return fft * np.hanning(len(fft))
def QuasiSpace(self,ns,df,ls): #evaluates the quasi space value allqs=[] #at the moment, the most easy method(everything else failed...) #get the mean absolute value of the complete spectrum. works best for i in range(len(ns)): # xvalues=py.fftfreq(len(ns[i]),df)*c/4 QSr=py.fft(ns[i].real-py.mean(ns[i].real)) QSi=py.fft(ns[i].imag-py.mean(ns[i].real)) #naive cut: ix=range(3,int(len(QSr)/2-1)) QSr=QSr[ix] QSi=QSi[ix] allqs.append(py.mean(abs(QSr))+py.mean(abs(QSi))) return allqs
def main(nbits): """Main Program""" import pylab nbits = int(nbits) m = mls(nbits) fm = pylab.fft(m) fig, ax = pylab.subplots(2, sharex=True) ax[0].plot(20 * pylab.log10(numpy.abs(fm))) ax[1].plot(numpy.angle(fm))
def windowAndFFT(self,window,fftlength): if ( self.Length != len(window) ): raise Exception, 'size mismatch, length of data != that of window' if ( fftlength < self.Length ): raise ValueError, 'fftlength < length of data' z = numpy.zeros(fftlength - self.Length) Abar = pylab.fft( numpy.array( list(self.A*window) + list(z) ) ) Ebar = pylab.fft( numpy.array( list(self.E*window) + list(z) ) ) Tbar = pylab.fft( numpy.array( list(self.T*window) + list(z) ) ) Abar = Abar[ 0:numpy.floor( fftlength/2+1 ) ]*self.Cadence Ebar = Ebar[ 0:numpy.floor( fftlength/2+1 ) ]*self.Cadence Tbar = Tbar[ 0:numpy.floor( fftlength/2+1 ) ]*self.Cadence self.winfftA = Abar self.winfftE = Ebar self.winfftT = Tbar self.FreqOffset = 0 self.FreqCadence = 1./(self.Cadence*fftlength) self.FreqLength = len(Abar) return
def PlotFftPhase(signal, dt): N=numpy.size(signal) fund = 1/(N*dt) # freq fundamental, as outras sao multiplas dessa f=range(N) for k in range(N-1): f[k+1]=fund*k #multiplas da fundamental z=pylab.fft(signal) pylab.plot(f, numpy.angle(z, deg=True)) pylab.ylabel('Phase (degrees)') pylab.xlabel('Frequency (Hz)')
def windowAndFFT(self, window, fftlength): if (self.Length != len(window)): raise Exception, 'size mismatch, length of data != that of window' if (fftlength < self.Length): raise ValueError, 'fftlength < length of data' z = numpy.zeros(fftlength - self.Length) Abar = pylab.fft(numpy.array(list(self.A * window) + list(z))) Ebar = pylab.fft(numpy.array(list(self.E * window) + list(z))) Tbar = pylab.fft(numpy.array(list(self.T * window) + list(z))) Abar = Abar[0:numpy.floor(fftlength / 2 + 1)] * self.Cadence Ebar = Ebar[0:numpy.floor(fftlength / 2 + 1)] * self.Cadence Tbar = Tbar[0:numpy.floor(fftlength / 2 + 1)] * self.Cadence self.winfftA = Abar self.winfftE = Ebar self.winfftT = Tbar self.FreqOffset = 0 self.FreqCadence = 1. / (self.Cadence * fftlength) self.FreqLength = len(Abar) return
def PlotFftPhase(signal, dt): N = numpy.size(signal) fund = 1 / (N * dt) # freq fundamental, as outras sao multiplas dessa f = range(N) for k in range(N - 1): f[k + 1] = fund * k #multiplas da fundamental z = pylab.fft(signal) pylab.plot(f, numpy.angle(z, deg=True)) pylab.ylabel('Phase (degrees)') pylab.xlabel('Frequency (Hz)')
def my_transform(x,dir): # my_transform - perform either FFT with energy conservation. # Works on array of size (w,w,a,b) on the 2 first dimensions. w = np.shape(x)[0] if dir == 1 : y = np.transpose(pyl.fft(np.transpose(x)))/np.sqrt(w) else : y = np.transpose(pyl.ifft(np.transpose(x)*np.sqrt(w))) return y
def zMeasures(current, v, delay, sampr, f1, bwinsz=1): ## zero padding current = current[int(delay * sampr - 0.5 * sampr + 1):-int(delay * sampr - 0.5 * sampr)] current = np.hstack((np.repeat(current[0], int(delay * sampr)), current, np.repeat(current[-1], int(delay * sampr)))) current = current - np.mean(current) v = v[int(delay * sampr - 0.5 * sampr) + 1:-int(delay * sampr - 0.5 * sampr)] v = np.hstack((np.repeat(v[0], int(delay * sampr)), v, np.repeat(v[-1], int(delay * sampr)))) v = v - np.mean(v) ## input and transfer impedance f_current = (fft(current) / len(current))[0:int(len(current) / 2)] f_cis = (fft(v) / len(v))[0:int(len(v) / 2)] z = f_cis / f_current ## impedance measures Freq = np.linspace(0.0, sampr / 2.0, len(z)) zAmp = abs(z) zPhase = np.arctan2(np.imag(z), np.real(z)) zRes = np.real(z) zReact = np.imag(z) ## smoothing fblur = np.array([1.0 / bwinsz for i in range(bwinsz)]) zAmp = convolve(zAmp, fblur, 'same') zPhase = convolve(zPhase, fblur, 'same') ## trim mask = (Freq >= 0.5) & (Freq <= f1) Freq, zAmp, zPhase, zRes, zReact = Freq[mask], zAmp[mask], zPhase[ mask], zRes[mask], zReact[mask] ## resonance zResAmp = np.max(zAmp) zResFreq = Freq[np.argmax(zAmp)] Qfactor = zResAmp / zAmp[0] fVar = np.std(zAmp) / np.mean(zAmp) return Freq, zAmp, zPhase, zRes, zReact, zResAmp, zResFreq, Qfactor, fVar
def PlotFftAbs(signal, dt): N = numpy.size(signal) fund = 1 / (N * dt) # freq fundamental, as outras sao multiplas dessa f = range(N) for k in range(N - 1): f[k + 1] = fund * k #multiplas da fundamental z = pylab.fft(signal) z_real = abs(z) pylab.plot(f, z_real) pylab.ylabel('Amplitude') pylab.xlabel('Frequency (Hz)')
def fourierPower(signal): "Calculates the Fourier power spectrum of the signal" A = pl.fft(signal) n = (len(signal) + 1) / 2 power = pl.zeros(n) #+1) #power[0] = A[0].real**2 #for i in range(1,n+1): for i in range(n): power[i] = 4 * (A[i + 1].real**2 + A[i + 1].imag**2) return power
def FourierDerivative(f): """ this derivatie just works for periodic 2*pi multiple series have to figure out how to make that work for any function """ N = np.size(f) n = np.arange(0, N) # df discrete differential operator df = np.complex(0, 1) * py.fftshift(n - N / 2) dfdt = py.ifft(df * py.fft(f)) return py.real(dfdt)
def PlotFftAbs(signal, dt): N=numpy.size(signal) fund = 1/(N*dt) # freq fundamental, as outras sao multiplas dessa f=range(N) for k in range(N-1): f[k+1]=fund*k #multiplas da fundamental z=pylab.fft(signal) z_real=abs(z) pylab.plot(f, z_real) pylab.ylabel('Amplitude') pylab.xlabel('Frequency (Hz)')
def FourierDerivative(f): """ this derivatie just works for periodic 2*pi multiple series have to figure out how to make that work for any function """ N = np.size(f) n = np.arange(0,N) # df discrete differential operator df = np.complex(0,1)*py.fftshift(n-N/2) dfdt = py.ifft( df*py.fft(f) ) return py.real(dfdt)
def getDR(self): #this function should return the dynamic range #this should be the noiselevel of the fft noiselevel=py.sqrt(py.mean(abs(py.fft(self._tdData.getAllPrecNoise()[0]))**2)) #apply a moving average filter on log window_size=5 window=py.ones(int(window_size))/float(window_size) hlog=py.convolve(20*py.log10(self.getFAbs()), window, 'valid') one=py.ones((2,)) hlog=py.concatenate((hlog[0]*one,hlog,hlog[-1]*one)) return hlog-20*py.log10(noiselevel)
def freqVect(self,f): # FFT of cos(f) by doing FFT(cos(f)) x = N.zeros(self.winSize,N.double) for i in range(self.winSize): x[i] = N.cos( float(f)*(i+0.5)*N.pi*2.0 / self.freqT / (self.winSize)) X=P.fft(x) return X
def _calculate_spectra_fft(sx, sy, Q_x, Q_y, Q_s, n_lines): n_turns, n_files = sx.shape # Allocate memory for output. oxx, axx = plt.zeros((n_lines, n_files)), plt.zeros((n_lines, n_files)) oyy, ayy = plt.zeros((n_lines, n_files)), plt.zeros((n_lines, n_files)) for file_i in xrange(n_files): t = plt.linspace(0, 1, n_turns) ax = plt.absolute(plt.fft(sx[:, file_i])) ay = plt.absolute(plt.fft(sy[:, file_i])) # Amplitude normalisation ax /= plt.amax(ax, axis=0) ay /= plt.amax(ay, axis=0) # Tunes if file_i==0: tunexfft = t[plt.argmax(ax[:n_turns/2], axis=0)] tuneyfft = t[plt.argmax(ay[:n_turns/2], axis=0)] print "\n*** Tunes from FFT" print " tunex:", tunexfft, ", tuney:", tuneyfft, "\n" # Tune normalisation ox = (t - (Q_x[file_i] % 1)) / Q_s[file_i] oy = (t - (Q_y[file_i] % 1)) / Q_s[file_i] # Sort CX = plt.rec.fromarrays([ox, ax], names='ox, ax') CX.sort(order='ax') CY = plt.rec.fromarrays([oy, ay], names='oy, ay') CY.sort(order='ay') ox, ax, oy, ay = CX.ox[-n_lines:], CX.ax[-n_lines:], CY.oy[-n_lines:], CY.ay[-n_lines:] oxx[:,file_i], axx[:,file_i], oyy[:,file_i], ayy[:,file_i] = ox, ax, oy, ay spectra = {} spectra['horizontal'] = (oxx, axx) spectra['vertical'] = (oyy, ayy) return spectra
def main(): pylab.ion() ind = [ 0, ] ldft = [ 0, ] lfft = [ 0, ] lpfft = [ 0, ] # plot a graph Dft vs Fft, lists just support size until 2**9 for i in range(1, 9, 1): t_before = time.clock() dsprocessing.dspDft(rand(2**i).tolist()) dt = time.clock() - t_before ldft.append(dt) print("dft ", 2**i, dt) #pylab.plot([2**i,], [time.clock()-t_before,]); t_before = time.clock() dsprocessing.dspFft(rand(2**i).tolist()) dt = time.clock() - t_before print("fft ", 2**i, dt) lfft.append(dt) #pylab.plot([2**i,], [time.clock()-t_before,]); ind.append(2**i) # python fft just to compare t_before = time.clock() pylab.fft(rand(2**i).tolist()) dt = time.clock() - t_before lpfft.append(dt) pylab.plot(ind, ldft) pylab.plot(ind, lfft) pylab.plot(ind, lpfft) pylab.show() return [ind, ldft, lfft, lpfft]
def freqVectH(self,f,rads): # FFT of sin(wt).hann(t) by explicit FFT(sin(wt).hann(t)) x = N.zeros(self.winSize,N.double) for i in range(self.winSize): x[i] = N.sin(rads+float(f)*(i+0.5)*N.pi*2.0 / self.freqT / (self.winSize)) X=P.fft(x*self.hann) return X
def fourier(ts, xs): def safe_dB(x): abs_x = abs(x) if abs_x < 1e-10: return -200 return 20 * math.log10(abs_x) n = len(ts) dt = ts[1] - ts[0] fs = [float(k + 1) / (dt * n) for k in range(n / 2)] Xs = [safe_dB(X) for X in pylab.fft(xs)[:n / 2]] return fs, Xs
def fft_based(input_signal, filter_coefficients, boundary=0): """applied fft if the signal is too short to be splitted in windows Params : input_signal : the audio signal filter_coefficients : coefficients of the chirplet bank boundary : manage the bounds of the signal Returns : audio signal with application of fast Fourier transform """ num_coeffs = filter_coefficients.size half_size = num_coeffs//2 if boundary == 0:#ZERO PADDING input_signal = np.lib.pad(input_signal, (half_size, half_size), 'constant', constant_values=0) filter_coefficients = np.lib.pad(filter_coefficients, (0, input_signal.size-num_coeffs), 'constant', constant_values=0) newx = ifft(fft(input_signal)*fft(filter_coefficients)) return newx[num_coeffs-1:-1] elif boundary == 1:#symmetric input_signal = concatenate([flipud(input_signal[:half_size]), input_signal, flipud(input_signal[half_size:])]) filter_coefficients = np.lib.pad(filter_coefficients, (0, input_signal.size-num_coeffs), 'constant', constant_values=0) newx = ifft(fft(input_signal)*fft(filter_coefficients)) return newx[num_coeffs-1:-1] else:#periodic return roll(ifft(fft(input_signal)*fft(filter_coefficients, input_signal.size)), -half_size).real
def plot2piFft(self, func, Fs, L): ''' Fs is the sampling freq. L is length of signal list. This plot is for a func that has period of 2pi. If you found the time domain wave is not very accurate, that is because you set too small Fs, which leads to to big step Ts. ''' base_freq = 1.0/(2*np.pi) #频域横坐标除以基频,即以基频为单位,此处的基频为 2*pi rad/s Ts = 1.0/Fs t = [el*Ts for el in range(0,L)] x = [func(el) for el in t] # https://www.ritchievink.com/blog/2017/04/23/understanding-the-fourier-transform-by-example/ # 小明给的代码: # sampleF = Fs # print('小明:') # for f, Y in zip( # np.arange(0, len(x)*sampleF,1) * 1/len(x) * sampleF, # np.log10(np.abs(np.fft.fft(x) / len(x))) # ): # print('\t', f, Y) L_4pi = int(4*np.pi / Ts) +1 # 画前两个周期的 self.fig_plot2piFft = plt.figure(7) plt.subplot(211) plt.plot(t[:L_4pi], x[:L_4pi]) #title('Signal in Time Domain') #xlabel('Time / s') #ylabel('x(t)') plt.title('Winding Function') plt.xlabel('Angular location along air gap [mech. rad.]') plt.ylabel('Current Linkage by unit current [Ampere]') NFFT = 2**nextpow2(L) print('NFFT =', NFFT, '= 2^%g' % (nextpow2(L)), '>= L =', L) y = fft(x,NFFT) # y is a COMPLEX defined in numpy Y = [2 * el.__abs__() / L for el in y] # /L for spectrum aplitude consistent with actual signal. 2* for single-sided. abs for amplitude. f = Fs/2.0/base_freq*linspace(0,1,int(NFFT/2+1)) # unit is base_freq Hz #f = Fs/2.0*linspace(0,1,NFFT/2+1) # unit is Hz plt.subplot(212) plt.plot(f, Y[0:int(NFFT/2+1)]) plt.title('Single-Sided Amplitude Spectrum of x(t)') plt.xlabel('Frequency divided by base_freq [base freq * Hz]') #plt.ylabel('|Y(f)|') plt.ylabel('Amplitude [1]') plt.xlim([0,50])
def visualize (): sample_rate, snd = load_sample(".\\hh-closed\\dh9.WAV") print snd.dtype data = normalize(snd) print data.shape n = data.shape[0] length = float(n) print length / sample_rate, "s" timeArray = arange(0, length, 1) timeArray = timeArray / sample_rate timeArray = timeArray * 1000 #scale to milliseconds ion() if False: plot(timeArray, data, color='k') ylabel('Amplitude') xlabel('Time (ms)') raw_input("press enter") exit() p = fft(data) # take the fourier transform nUniquePts = ceil((n+1)/2.0) print nUniquePts p = p[0:nUniquePts] p = abs(p) p = p / float(n) # scale by the number of points so that # the magnitude does not depend on the length # of the signal or on its sampling frequency p = p**2 # square it to get the power # multiply by two (see technical document for details) # odd nfft excludes Nyquist point if n % 2 > 0: # we've got odd number of points fft p[1:len(p)] = p[1:len(p)] * 2 else: p[1:len(p) -1] = p[1:len(p) - 1] * 2 # we've got even number of points fft print p freqArray = arange(0, nUniquePts, 1.0) * (sample_rate / n); plot(freqArray/1000, 10*log10(p), color='k') xlabel('Frequency (kHz)') ylabel('Power (dB)') raw_input("press enter") m = average(freqArray, weights = p) v = average((freqArray - m)**2, weights= p) r = sqrt(mean(data**2)) s = var(data**2) print "mean freq", m #TODO: IMPORTANT: this is currently the mean *power*, not the mean freq. What we want is mean freq weighted by power print "var freq", v print "rms", r print "squared variance", s
def detrend(data,detrend_Kernel_Length = 10,sampling_Frequency = 100000,channels = 8): from pylab import fft, ifft, sin , cos,log,plot,show,conj,legend import random n=len(data[0]) detrend_fft_Length = (2**((log(detrend_Kernel_Length * sampling_Frequency)/log(2)))) ma = [1.0]*sampling_Frequency ma.extend([0.0]*(detrend_fft_Length - sampling_Frequency)) mafft = fft(ma) trend = [0.0]*n for nch in range(channels): count = 0 while count + detrend_fft_Length <= len(data[nch]): temp = data[nch][count:count+int(detrend_fft_Length)] y = fft(temp) z = ifft( conj(mafft)*y) for cc in xrange(count,count+(int(detrend_fft_Length)-sampling_Frequency)): trend[cc] = z[cc-count].real / sampling_Frequency count = count+(int(detrend_fft_Length)-sampling_Frequency) for cc in xrange(len(trend)): data[nch][cc] = data[nch][cc] - trend[cc]
def amplitude_spectrum(self, use_fft=True): N = len(self.values) if use_fft: transform = fft(self.values) else: transform = zeros(N, dtype=complex) for m in range(self.fs): sum = 0 for n in range(N): inner = -(2 * pi * n * m) / N sum += self.values[n] * (cos(inner) + 1j * sin(inner)) transform[m] = sum transform_abs = [abs(x) for x in transform] values = [transform_abs[f] / N for f in range(int(self.fs / 2) + 1)] return self.__class__(values)
def getFFT(s1, n): p = fft(s1) # take the fourier transform nUniquePts = ceil((n + 1) / 2.0) p = p[0:nUniquePts] p = abs(p) p = p / n # scale by the number of points so that # the magnitude does not depend on the length # of the signal or on its sampling frequency p = p ** 2 # square it to get the power # multiply by two (see technical document for details) # odd nfft excludes Nyquist point if n % 2 > 0: # we've got odd number of points fft p[1:len(p)] = p[1:len(p)] * 2 else: p[1:len(p) - 1] = p[1:len(p) - 1] * 2 # we've got even number of points fft return nUniquePts, p
def PlotFftRPhase(y, dt=0.1): # plot the grah of fft (fase) of y with command plot """ plot also just half spectrum (just positive frequencies), and from frequencys 1:N/2 """ N = numpy.size(y) fund = 1/(N*dt) # freq fundamental, as outras sao multiplas dessa f=range(N) for k in range(N-1): f[k+1]=fund*k #multiplas da fundamental yn = pylab.fft(y) angyn = numpy.angle(yn, deg=True) pylab.plot(f[0:numpy.size(f)/2], angyn[0:numpy.size(f)/2])
def fft(self): self.sortx(); xmin=min(self['x']); xmax=max(self['x']); dx=numpy.fabs(numpy.mean(diff(self['x']))); Nx=(xmax-xmin)/dx; xnew=numpy.linspace(xmin,xmax,Nx+1); spect=self.copyxy(); spect['x']=xnew; spect['y']=xnew; spect1=self.copyxy(); spect1.mapx(spect); newy=pylab.fft(spect1['y']); newx=arange(len(spect1['x']))/float(len(spect1['x']))/dx; spect1['x']=newx; spect1['y']=newy.real; return spect1;
def freqz(sosmat, nsamples=44100, sample_rate=44100, plot=True): """Plots Frequency response of sosmat.""" from pylab import np, plt, fft, fftfreq x = np.zeros(nsamples) x[nsamples/2] = 0.999 y, states = sosfilter_double_c(x, sosmat) Y = fft(y) f = fftfreq(len(x), 1.0/sample_rate) if plot: plt.grid(True) plt.axis([0, sample_rate / 2, -100, 5]) L = 20*np.log10(np.abs(Y[:len(x)/2]) + 1e-17) plt.semilogx(f[:len(x)/2], L, lw=0.5) plt.hold(True) plt.title('freqz sos filter') plt.xlabel('Frequency / Hz') plt.ylabel('Damping /dB(FS)') plt.xlim((10, sample_rate/2)) plt.hold(False) return x, y, f, Y
def process_window(sample_rate, data): # print "processing window" # print data.dtype # print data.shape n = data.shape[0] length = float(n) # print length / sample_rate, "s" p = fft(data) # take the fourier transform nUniquePts = ceil((n+1)/2.0) p = p[0:nUniquePts] p = abs(p) p = p / float(n) # scale by the number of points so that # the magnitude does not depend on the length # of the signal or on its sampling frequency p = p**2 # square it to get the power # multiply by two (see technical document for details) # odd nfft excludes Nyquist point if n % 2 > 0: # we've got odd number of points fft p[1:len(p)] = p[1:len(p)] * 2 else: p[1:len(p) -1] = p[1:len(p) - 1] * 2 # we've got even number of points fft freqArray = arange(0, nUniquePts, 1.0) * (sample_rate / n); if sum(p) == 0: raise Silence m = average(freqArray, weights = p) v = sqrt(average((freqArray - m)**2, weights= p)) r = sqrt(mean(data**2)) s = var(data**2) print "mean freq", m #TODO: IMPORTANT: this is currently the mean *power*, not the mean freq. What we want is mean freq weighted by power # print freqArray # print (freqArray - m) # print p print "var freq", v print "rms", r print "squared variance", s return [m, v, r, s]
def __gauss(sacobj, Tn, alpha): """ Return envelope and gaussian filtered data """ import pylab as pl data = pl.array(sacobj.data) delta = sacobj.delta Wn = 1 / float(Tn) Nyq = 1 / (2 * delta) old_size = data.size pad_size = 2**(int(pl.log2(old_size))+1) data.resize(pad_size) spec = pl.fft(data) spec.resize(pad_size) W = pl.array(pl.linspace(0, Nyq, pad_size)) Hn = spec * pl.exp(-1 * alpha * ((W-Wn)/Wn)**2) Qn = complex(0,1) * Hn.real - Hn.imag hn = pl.ifft(Hn).real qn = pl.ifft(Qn).real an = pl.sqrt(hn**2 + qn**2) an.resize(old_size) hn = hn[0:old_size] return(an, hn)
def PlotFftNAbs(y, dt=0.1): # plot the grah of fft (amplitude) of y with command plot """ Normalized version plot of FFT equal abs(FFT) * 2/y.length plot also just half spectrum (just positive frequencies), and from frequencys 1:N/2 the mean (DC component) is removed before fft """ N = numpy.size(y) #remove the DC component just the mean (could use a detrend function) y = y - numpy.mean(y) fund = 1/(N*dt) # freq fundamental, as outras sao multiplas dessa f=range(N) for k in range(N-1): f[k+1]=fund*k #multiplas da fundamental yn = pylab.fft(y) # perfeito. se vpce colocar um seno de 30 e outro de 60, com aplitude 1 e 2 no espectro # de amplitude voce vai encontrar exatamente 1 e 2 absyn=2*numpy.abs(yn)/numpy.size(yn); pylab.plot(f[0:numpy.size(f)/2], absyn[0:numpy.size(f)/2]) return [f, absyn]
def _calculatefdData(self,tdData): #no need to copy it before (access member variable is ugly but shorter) #calculate the fft of the X channel fd=py.fft(tdData.getEX()) #calculate absolute and phase values fdabs=abs(fd) fdph=abs(py.unwrap(py.angle(fd))) #calculate frequency axis dfreq=py.fftfreq(tdData.num_points,tdData.dt) #extrapolate phase to 0 and 0 frequency fdph=self.removePhaseOffset(dfreq,fdph) #set up the fdData array t=py.column_stack((dfreq,fd.real,fd.imag,fdabs,fdph)) #this is so not nice! self.fdData=t unc=self.calculateFDunc() t=self.getcroppedData(t,0,unc[-1,0]) #interpolate uncertainty intpunc=interp1d(unc[:,0],unc[:,1:],axis=0) unc=intpunc(t[:,0]) return py.column_stack((t,unc))
def main(): # get all files, sorted by temp os.chdir('./data') files = sorted(glob.glob("*obdm*") and glob.glob("*dat*"))[::-1] if files == []: print 'no files located' sys.exit() os.chdir('..') BECfrac = pl.array([]) Temps = pl.array([]) # compute zero frequency FFT term for each file for fileName in files: # get header line estFile = open('./data/'+fileName,'r') estLines = estFile.readlines(); pimcid = estLines[0] headers = estLines[1].split() estFile.close() headers.pop(0) headers = pl.array(headers).astype(float) rawData = pl.loadtxt('./data/'+fileName) avgs = pl.array([]) Ncol = 1.0*rawData.size/rawData[0].size for j in range(int(Ncol)): for i in range(rawData[j].size): if j == 0: avgs = pl.append(avgs, rawData[j][i]) else: avgs[i] += rawData[j][i] avgs /= Ncol # compute FFT f = pl.fft(avgs) BECfrac = pl.append(BECfrac, f[0].real) Temps = pl.append(Temps, (fileName[9:15])) print '=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=' print 'Zero Frequency FFT term: ',f[0].real print '=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=' # plotting #pl.plot(headers, avgs, marker='o', linewidth=0, markerfacecolor='None', # markeredgecolor='Indigo') #pl.ylabel(r'$\langle \hat{\Psi}^{\dagger}(r)\ \hat{\Psi}(r\') \rangle$', # fontsize=20) pl.plot(Temps, BECfrac, marker='o', linewidth=0, markerfacecolor='None', markeredgecolor='Indigo') pl.ylabel('Condensate Fraction', fontsize=20) pl.xlabel(r'$T\ [K]$', fontsize=20) pl.title('BEC Fraction') pl.grid(True) pl.show()