def calculate_FROG(self): self.FROGxmin = self.t[0] self.FROGxmax = self.t[-1] self.FROGdeltax = (self.t[-1]-self.t[0])/self.NT self.FROGymin = self.frequencies[0] self.FROGymax = self.frequencies[-1] self.FROGdeltay = (self.frequencies[-1]-self.frequencies[0])/self.NT return #negative delay for i in xrange(self.NT/2): self.field = zeros((self.NT)) self.field[i:] = (self.ElectricField[:self.NT-i]*self.ElectricField[i:])**2 self.field_fft = fft(self.field) self.field_fft[:self.NT/2] = zeros((self.NT/2)) #no negative freq self.FROG[:,self.NT/2-i] = abs(self.field_fft[self.NT/2:])**2#fftshift(abs(self.field_fft[self.NT/2:])**2) #positive delay for i in xrange(self.NT/2): self.field = zeros((self.NT)) self.field[i:] = (self.ElectricField[i:]*self.ElectricField[:self.NT-i])**2 self.field_fft = fft(self.field) self.field_fft[:self.NT/2] = zeros((self.NT/2)) #no negative freq self.FROG[:,self.NT/2+i] = abs(self.field_fft[self.NT/2:])**2#fftshift(abs(self.field_fft[self.NT/2:])**2) self.FROG /= ma.max(abs(self.FROG))
def length_shift(signalin, tscale): L = len(signalin) # signal blocks for processing and output phi = zeros(N) out = zeros(N, dtype=complex) sigout = zeros(L/tscale+N) # max input amp, window amp = max(signalin) win = hanning(N) p = 0 pp = 0 while p < L-(N+H): print p, ',', (L-N-H) # take the spectra of two consecutive windows p1 = int(p) spec1 = fft(win*signalin[p1:p1+N]) spec2 = fft(win*signalin[p1+H:p1+N+H]) # take their phase difference and integrate phi += (angle(spec2) - angle(spec1)) # bring the phase back to between pi and -pi for i in phi: while i < -pi: i += 2*pi while i >= pi: i -= 2*pi out.real, out.imag = cos(phi), sin(phi) # inverse FFT and overlap-add sigout[pp:pp+N] += (win*ifft(abs(spec2)*out)).real pp += H p += H*tscale return array(amp * sigout / max(sigout))
def calculate_FROG(self): self.FROGxmin = self.t[0] self.FROGxmax = self.t[-1] self.FROGymin = self.get_frequencies()[0] self.FROGymax = self.get_frequencies()[-1] ElectricField = real(self.ElectricField) # complex field #negative delay for i in xrange(self.NT/2): self.field = zeros((self.NT)) self.field[i:] = (ElectricField[:self.NT-i]*ElectricField[i:])**2 self.field_fft = fft(self.field) self.FROG[:,self.NT/2-i] = fftshift(abs(self.field_fft)**2) #positive delay for i in xrange(self.NT/2): self.field = zeros((self.NT)) self.field[i:] = (ElectricField[i:]*ElectricField[:self.NT-i])**2 self.field_fft = fft(self.field) self.FROG[:,self.NT/2+i] = fftshift(abs(self.field_fft)**2) self.FROG /= ma.max(abs(self.FROG))
def process2ch(self,inputbuffers,timestamp): if not self.update() : return None fftsize = self.m_blockSize audioSamples0 = inputbuffers[0] audioSamples1 = inputbuffers[1] complexSpectrum0 = fft(self.window*audioSamples0,fftsize) complexSpectrum1 = fft(self.window*audioSamples1,fftsize) magnitudeSpectrum0 = abs(complexSpectrum0)[0:fftsize/2] / (fftsize/2) magnitudeSpectrum1 = abs(complexSpectrum1)[0:fftsize/2] / (fftsize/2) # do the computation melSpectrum0 = self.warpSpectrum(magnitudeSpectrum0) melCepstrum0 = self.getMFCCs(melSpectrum0,cn=True) melSpectrum1 = self.warpSpectrum(magnitudeSpectrum1) melCepstrum1 = self.getMFCCs(melSpectrum1,cn=True) outputs = FeatureSet() outputs[0] = Feature(hstack((melCepstrum1[self.cnull:],melCepstrum0[self.cnull:]))) outputs[1] = Feature(hstack((melSpectrum1,melSpectrum0))) return outputs
def phi(entry): # Likelihood fonction A = MesFonctions.matrice_A(entry[0:size].reshape((NbLigne, NbColonne)), methode="3") x_ = ( floue.reshape(size) - MesFonctions.conv_matrices(A, entry[size:2 * size].reshape((NbLigne, NbColonne)), "vecteur", "coin")) likelihood = np.dot(np.dot(x_, C_noise_inv), x_.transpose()) # Regularization term image_ = entry[0:size] # /sum(sum(im)) PSF_ = entry[size:2 * size] # /sum(sum(PSF)) if regularization == "spectral": fy_ = np.fft(image_) y_ = 0 for i in range(0, size): y_ = y_ + i * i * abs(fy_[i]) * abs(fy_[i]) regularization_im = y_ fz_ = np.fft(PSF_) z_ = 0 for i in range(0, size): z_ = z_ + i * i * abs(fz_[i]) * abs(fz_[i]) regularization_PSF = z_ elif regularization == "Tikhonov": y_ = sum(image_ * image_) regularization_im = math.sqrt(y_) z_ = sum(PSF_ * PSF_) regularization_PSF = math.sqrt(z_) t_ = likelihood + regularization_im + regularization_PSF return t_
def fft_covariance(sample): ''' returns the covariance matrix and index of each item for a dimension-list of sample-lists [d0, d1, ...,dd] where d0 is the first dimension containing n samples. n.b. numpy 1.7rc1 has numpy.pad to pad array. currently running 1.6.2 (released version) so imported rc1 version. ''' A = numpy.array(sample) d, n = A.shape Q = numpy.ones(1) if(d==2) else numpy.ones((d, d)) idx = [[1]] if(d==2) else [list([1.] * d) for i in range(d)] nm1 = float(n - 1) #prep for fft A = (A.transpose() - numpy.mean(A, axis=1)).transpose() A = npp.pad(A,(0,len(pad(n))), 'constant', constant_values=(0,0))[:d, : ] #2x2return if (d == 2): corr = ifft(fft(A[0, :]) * np.conjugate(fft(A[1, :]))) maxcorr = getmax(corr) Q[0] = maxcorr[0] / nm1 idx[0] = maxcorr[1] else: for i in range(d): for j in range(i, d): corr = ifft(fft(A[i, :]) * np.conjugate(fft(A[j, : ]))) maxcorr = getmax(corr) Q[i][j] = maxcorr[0] / nm1 idx[i][j] = maxcorr[1] if i != j: Q[j][i] = Q[i][j] return Q, idx
def myFFT(self,x): tt,xx,uu = self.Traj(x,U=1,fast=0) n,gn=len(tt),len(uu) grsU = [TGraph(n,tt,uu[i]) for i in range(5)] ffts = [fft(uu[i]).real for i in range(5)] ffts2= [fft(uu[i]).imag for i in range(5)] fftUt = [array('d') for i in range(5)] fftUt2 = [array('d') for i in range(5)] for i in range(5): for j in range(n): fftUt[i].append(ffts[i][j]**2+ffts2[i][j]**2) fftUt2[i].append(ffts[i][j]) fftUr = [TGraph(n,tt,fftUt[i]) for i in range(5)] fftUi = [TGraph(n,tt,fftUt2[i]) for i in range(5)] c1 = TCanvas() c1.Divide(3,2) for i in range(5): c1.cd(i+1) fftUi[i].Draw("APE") fftsx1 = [fft(xx[i]).real for i in range(3)] fftsx2= [fft(xx[i]).imag for i in range(3)] fftsxA = [array('d') for i in range(3)] for i in range(3): for j in range(n): fftsxA[i].append(fftsx1[i][j]) fftxr = [TGraph(n,tt,fftsxA[i]) for i in range(3)] c2 = TCanvas() c2.Divide(3) for i in range(3): c2.cd(i+1) fftxr[i].Draw("APE") zwom = input("numbers continue")
def fft_sheet(f, t): # Transform along y fk = fft(f, axis=0) # Phase shift (to make periodic in x) fk *= exp(1j * S * t * ky * x) # Transform along x return fft(fk, axis=1)
def FFT_Correlation(x,y): """ FFT-based correlation, much faster than numpy autocorr. x and y are row-based vectors of arbitrary lengths. This is a vectorized implementation of O(N*log(N)) flops. """ lengthx = x.shape[0] lengthy = y.shape[0] x = np.reshape(x,(1,lengthx)) y = np.reshape(y,(1,lengthy)) length = np.array([lengthx, lengthy]).min() x = x[:length] y = y[:length] fftx = fft(x, 2 * length - 1, axis=1) #pad with zeros ffty = fft(y, 2 * length - 1, axis=1) corr_xy = fft.ifft(fftx * np.conjugate(ffty), axis=1) corr_xy = np.real(fft.fftshift(corr_xy, axes=1)) #should be no imaginary part corr_yx = fft.ifft(ffty * np.conjugate(fftx), axis=1) corr_yx = np.real(fft.fftshift(corr_yx, axes=1)) corr = 0.5 * (corr_xy[:,length:] + corr_yx[:,length:]) / range(1,length)[::-1] return np.reshape(corr,corr.shape[1])
def diff_spectrum(self, ref_mic): ref_signal = self.microphones[ref_mic[0]][ref_mic[1]].signal min_sig_len = min(ref_signal.shape[0], self.signal.shape[0]) wnd = 0.54 - 0.46*numpy.cos(2*pi*numpy.arange(min_sig_len)/min_sig_len) fft_sum = fftshift(fft(self.signal[0:min_sig_len]*wnd))/min_sig_len fft_ref = fftshift(fft(ref_signal[0:min_sig_len]*wnd))/min_sig_len fft_rel = (fft_sum / fft_ref).real fft_freq = numpy.linspace(-self.samplerate/2, self.samplerate/2, min_sig_len); return {"x":fft_freq, "y":fft_rel}
def fftconv(x, y): """ Convolution of x and y using the FFT convolution theorem. """ N = len(x) n = int(2 ** np.ceil(np.log2(N))) + 1 X, Y, x_y = fft(x, n), fft(y, n), [] for i in range(n): x_y.append(X[i] * Y[i]) # Returns the inverse Fourier transform with padding correction return fft.ifft(x_y)[4:N+4]
def conv(x,y): x1=np.zeros(x.size) x1[0:x.size]=x #added zeros y1=np.zeros(y.size) y1[0:y.size]=y #added zeros x1ft=np.fft(x1) y1ft=np.fft(y1) vect1=np.real(np.ifft(x1ft*y1ft)) return vect1[0:x.size]
def my_fft(sample, inverse=False): n = len(sample) if n == 1: return sample else: Feven = fft([sample[i] for i in xrange(0, n, 2)]) Fodd = fft([sample[i] for i in xrange(1, n, 2)]) combined = [0] * n for m in xrange(n/2): combined[m] = Feven[m] + omega(n, -m, inverse) * Fodd[m] combined[m + n/2] = Feven[m] - omega(n, -m, inverse) * Fodd[m] return combined
def solve(self, x, rho): Nx, = rho.shape k = fftfreq(Nx) * 2*np.pi*Nx k[0] = 1.0 rhohat = fft(rho) rhobar = rhohat[0] / rho.size phihat = rhohat / -k**2 + fft(0.5 * rhobar * x**2) gphhat = 1.j * k * phihat phi = ifft(phihat).real gph = ifft(1.j * k * phihat).real soln = np.zeros(rho.shape + (4,)) soln[:,0] = phi soln[:,1] = gph return soln
def getHNR(y, Fs, F0, Nfreqs): print 'holla' NBins = len(y) N0 = round(Fs/F0) N0_delta = round(N0 * 0.1) y = [x*z for x,z in zip(np.hamming(len(y)),y)] fftY = np.fft(y, NBins) aY = np.log10(abs(fftY)) ay = np.ifft(aY) peakinx = np.zeros(np.floor(len(y))/2/N0) for k in range(1, len(peakinx)): ayseg = ay[k*N0 - N0_delta : k*N0 + N0_delta] val, inx = max(abs(ayseg)) #MAX does not behave the same - doesn't return inx?? peakinx[k] = inx + (k * N0) - N0_delta - 1 s_ayseg = np.sign(np.diff(ayseg)) l_inx = inx - np.find((np.sign(s_ayseg[inx-1:-1:1]) != np.sign(inx)))[0] + 1 r_inx = inx + np.find(np.sign(s_ayseg[inx+1:]) == np.sign(inx))[0] l_inx = l_inx + k*N0 - N0_delta - 1 r_inx = r_inx + k*N0 - N0_delta - 1 for num in range(l_inx, r_inx): ay[num] = 0 midL = round(len(y)/2)+1 ay[midL:] = ay[midL-1: -1 : midL-1-(len(ay)-midL)] Nap = np.real(np.fft(ay)) N = Nap #???? why? Ha = aY - Nap #change these names ffs Hdelta = F0/Fs * len(y) for f in [num+0.0001 for num in range(Hdelta, round(len(y)/2), Hdelta)]: fstart = np.ceil(f - Hdelta) Bdf = abs(min(Ha[fstart:round(f)])) N[fstart:round(f)] = N[fstart:round(f)] - Bdf H = aY - N n = np.zeros(len(Nfreqs)) for k in range(1, len(Nfreqs)): Ef = round(Nfreqs[k] / Fs * len(y)) n[k] = (20 * np.mean(H[1:Ef])) - (20 * np.mean(N[1:Ef])) return n
def spectrum(signal): """ Returns Fourier-Series coefficients, assuming that 'signal' represents one period of an infinitely extended periodic signal. """ # A_{n, FourierSeries} = 1/L*A_{n, FFT} return fft(signal)/len(signal)
def fourier_projection(self, density): ft_density = np.fft(density) # -m wraps around array, but that should be OK.... # --> self._A_ell_expt[l] is shape (2l+1) x n_q = (m x q) # ft_coefficients[:,l,:] is shape n_q x (2l+1) = (q x m) (tranposed later) ft_coefficients = self._sph_harm_projector(ft_density) # zero out the array, use it to store the next iter ft_density[:,:,:] = 0.0 + 1j * 0.0 for l in range(self.order_cutoff): A_ell_model = ft_coefficients[:,l,:].T # (2l+1) x n_q = (m x q) # find U that rotates the experimental vectors into as close # agreement as possible as the model vectors U = math2.kabsch(self._A_ell_expt[l], A_ell_model) # update: k --> k+1 A_ell_prime = np.dot(self._A_ell_expt[l], U) ft_density_prime += self._sph_harm_projector.expand_sph_harm_order(A_ell_prime, l) updated_density = np.ifft(ft_density) return updated_density
def processN(self,membuffer,frameSampleStart): # recalculate the filter and DCT matrices if needed if not self.update() : return [] fftsize = self.m_blockSize audioSamples = frombuffer(membuffer[0],float32) complexSpectrum = fft(self.window*audioSamples,fftsize) #complexSpectrum = frombuffer(membuffer[0],complex64,-1,8) magnitudeSpectrum = abs(complexSpectrum)[0:fftsize/2] / (fftsize/2) melSpectrum = self.warpSpectrum(magnitudeSpectrum) melCepstrum = self.getMFCCs(melSpectrum,cn=True) output_melCepstrum = [{ 'hasTimestamp':False, 'values':melCepstrum[self.cnull:].tolist() }] output_melSpectrum = [{ 'hasTimestamp':False, 'values':melSpectrum.tolist() }] return [output_melCepstrum,output_melSpectrum,[]]
def showResponse(x, f, a, w0, Q): fmax = 200.0 # smooth it out with averaging: df = 1.0 fatf = arange(0,fmax,df) n = len(fatf) fatX = zeros(n) print '\nfft\'ing to find the frequency response...' X = fft(x) for i in range(n): fslice = where(abs(f-fatf[i])<df/2)[0] fatX[i] = mean(abs(X[fslice])) norm = mean(fatX[0:10]) fatX = fatX/norm # plot the response with the theoretical curve overlaid: plot(fatf, fatX, 'k.', label = 'simulated data') title('response of damping system') xlabel('frequency (Hz)') ylabel('abs(fft(x)) normalized to low f') Omega = 2*pi*fatf/w0 zeta = 1.0/2.0/Q theory = 1/sqrt( (1-Omega**2)**2 + (2*zeta*Omega)**2 ) semilogy(fatf, theory, label = 'theory') legend() show()
def process_wav(file, truncate=None, window_size = 2**12): """ spectrum : |windows| by window_size |frequencies| = window_size |windows| / 2 * |frequencies| ~ |seconds| * sample_rate """ print 'processing %s...' % file audio, sample_rate = audio_wav(file, truncate=truncate) hanning_window = hanning(window_size) nWindows = int32(audio.size/window_size *2) # double <- overlap windows spectrum = zeros((nWindows,window_size)) for i in xrange(0,nWindows-1): t = int32(i* window_size/2) window = audio[t : t+window_size] * hanning_window # elemwise mult spectrum[i,:] = fft(window) """ not invertible, sounds like noise iaudio = zeros((int(nWindows/2)-1, window_size)) hanning_window[hanning_window==0]=min(hanning_window[hanning_window!=0]/4) for i in xrange(0,int(nWindows/2)-1): iaudio[i,:] = 1/hanning_window * abs(ifft(spectrum[2*i,:])) iaudio.dtype='int16' wavfile.write('inverse.wav', sample_rate, iaudio) """ return spectrum, sample_rate
def make_unitary(self): fft_val = np.fft(self.v) fft_imag = fft_val.imag fft_real = fft_val.real fft_norms = [sqrt(fft_imag[n]**2 + fft_real[n]**2) for n in range(len(self.v))] fft_unit = fft_val / fft_norms self.v = (np.ifft(fft_unit)).real
def dst(x,axis=-1): """Discrete Sine Transform (DST-I) Implemented using 2(N+1)-point FFT xsym = r_[0,x,0,-x[::-1]] DST = (-imag(fft(xsym))/2)[1:(N+1)] adjusted to work over an arbitrary axis for entire n-dim array """ n = len(x.shape) N = x.shape[axis] slices = [None]*3 for k in range(3): slices[k] = [] for j in range(n): slices[k].append(slice(None)) newshape = list(x.shape) newshape[axis] = 2*(N+1) xtilde = np.zeros(newshape,np.float64) slices[0][axis] = slice(1,N+1) slices[1][axis] = slice(N+2,None) slices[2][axis] = slice(None,None,-1) for k in range(3): slices[k] = tuple(slices[k]) xtilde[slices[0]] = x xtilde[slices[1]] = -x[slices[2]] Xt = np.fft(xtilde,axis=axis) return (-np.imag(Xt)/2)[slices[0]]
def processBuffer(self, bounds): self.param1 = bounds.height/65536.0 self.param2 = bounds.height/2.0 if(self.stop==False): Fs = 48000 nfft= 65536 self.newest_buffer=self.newest_buffer[0:256] self.fftx = fft(self.newest_buffer, 256,-1) self.fftx=self.fftx[0:self.freq_range*2] self.draw_interval=bounds.width/(self.freq_range*2.) NumUniquePts = ceil((nfft+1)/2) self.buffers=abs(self.fftx)*0.02 self.y_mag_bias_multiplier=0.1 self.scaleX = "hz" self.scaleY = "" if(len(self.buffers)==0): return False # Scaling the values val = [] for i in self.buffers: temp_val_float = float(self.param1*i*self.y_mag) + self.y_mag_bias_multiplier * self.param2 if(temp_val_float >= bounds.height): temp_val_float = bounds.height-25 if(temp_val_float <= 0): temp_val_float = 25 val.append( temp_val_float ) self.peaks = val
def find_frequency(x,y): # Returns the fundamental frequency using FFT tx,ty = fft(y, x[1]-x[0]) index = find_peak(ty) if index == 0: return None else: return tx[index]
def process(self,inputbuffers,timestamp): if self.m_channels == 2 and self.two_ch : return self.process2ch(inputbuffers,timestamp) # calculate the filter and DCT matrices, check # if they are computable given a set of parameters # (we only do this once, when the process is called first) if not self.update() : return None fftsize = self.m_blockSize if self.m_channels > 1 : audioSamples = (inputbuffers[0]+inputbuffers[1])/2 else : audioSamples = inputbuffers[0] #complexSpectrum = frombuffer(membuffer[0],complex64,-1,8) complexSpectrum = fft(self.window*audioSamples,fftsize) magnitudeSpectrum = abs(complexSpectrum)[0:fftsize/2] / (fftsize/2) # do the computation melSpectrum = self.warpSpectrum(magnitudeSpectrum) melCepstrum = self.getMFCCs(melSpectrum,cn=True) # output feature set (the builtin dict type can also be used) outputs = FeatureSet() outputs[0] = Feature(melCepstrum[self.cnull:]) outputs[1] = Feature(melSpectrum) return outputs
def newcomplexsmoothing(x, samplerate, width = 1./3, b = .54, onset_safeguard = 0): ''' slightly different version where the linear delay is removed from the phase. onset_safeguard kwdargs is IGNORED still going back to the time domain doesn't work ''' N = x.shape[0] # first step: remove linear part of the phase # estimation of the impulse response lag onset = onset_detection(x) x_ft = fft(x.flatten()) x_phases = np.angle(x_ft) linearpart = fftfreq(len(x_ft))*onset x_newphases = exp(1j*(x_phases-linearpart)) # second step: we compute the smoothed amplitudes amps = nonuniform_spectralsmoothing(np.abs(x_ft), samplerate, width = width, b = b) # third step: we compute the phases # new phases computations phases = nonuniform_spectralsmoothing(x_newphases, samplerate, width = width, b = b) # and set all the amplitudes to phasepart = np.exp(1j*phases) # fourth step: the result res_ft = amps*phasepart res_ft = complete_toneg(res_ft) res = ifft(res_ft).real return res, onset
def fft_squid(path): squid_model = model.NoisySquid(path) squid_model.getContext().setClock(3, 20e-3, 0) squid_model.currentInjection.min = 0.0e-6 squid_model.currentInjection.max = 0.1e-6 squid_model.getContext().reset() squid_model.run(200e-3) signal = array(squid_model.vmTable) squid_model.save_all_plots() # savetxt('vm.plot', signal) transform = fft(signal) xx = array(range(len(transform))) ax1 = subplot(121) #plot(xx / 10.0 , signal * 1e3, 'r') savetxt("t_series.plot", xx/10.0) # ax1 = axis([0, 0, 0.5, 0.8]) # xlabel("time (ms)") # ylabel("membrane potential (mV)") # ax2 = twinx() # plot(xx / 10.0 , array(squid_model.iInjectTable) * 1e9, 'b--') # ylabel("injection current (nA)") # ax2.yaxis.tick_right() # title("(A)", fontname="Times New Roman", fontsize=10, fontweight="bold") # show() # savefig("Vm.jpg", dpi=600) savetxt('fftreal.plot', transform.real, fmt="%13.12G") savetxt('fftimag.plot', transform.imag, fmt="%13.12G")
def run(self): schema = schemas.Sensor(many=True) ref = self.database.db.accelerometres.find({'ref': ObjectId(self.params.uuid)}) self.data, errors = schema.dump(ref) x = np.array(self.data) y = np.fft(x) return y
def Run(self): i = 0 while self.keepGoing: i += 1 data =self.stream.read(chunk) if (i>2): # if (i>self.skip): i = 0 #print unpack('B',data[0]) buff = array(unpack_from('1024h',data)) #e = buff.std() #print "Energy: %f" % e #sys.stdout.flush() ## use stdev to calculate energy in this buffer (root sum of squared mag) #csum.append(buff.std()) fourier = fft(buff) ## calculate log mag of fft logmag = hypot(fourier.real[0:chunk/2],fourier.imag[0:chunk/2]) if False: self.lmfile=open("logmag.txt","w") logmag.tofile(self.lmfile, sep=" ", format="%s") self.lmfile.close() bdata = [] i = 0 for b in self.bands: # sum energy in this band bdata.append(logmag[b].mean()*self.scale[i]) i += 1 # normalize so max energy is 1.0 localmax = [] localmax.append(max(bdata)) localmax.append(self.bmax) self.bmax = max(localmax) for i in range(len(bdata)): bdata[i] = (bdata[i])*self.gain/self.bmax evt = self.UpdateAudioEvent(bands=bdata, value = int(localmax[0]*self.gain/50000)) #print localmax[0] if True: time.sleep(0.01) wx.PostEvent(self.win, evt) if True: time.sleep(0.01) #self.bwfile=open("bands.txt","w") #self.bwfile.write(str(bdata)) #self.bwfile.close() #bands = logmag[0:chunk/4] #nbands = 16 #bwidth = chunk/(4*nbands) #bsum = mean(bands.reshape(nbands,bwidth),axis=1) #line.set_ydata(logmag) ## convert to 2d array and append to running show. #logmag2 = array(logmag.tolist(),ndmin=2) self.running = False
def fourier_genome(seq): xA=[0 for i in range(0,len(seq))] xT=[0 for i in range(0,len(seq))] xG=[0 for i in range(0,len(seq))] xC=[0 for i in range(0,len(seq))] for i in range(0,len(seq)): if seq[i]=="A":xA[i]=1 if seq[i]=="T":xT[i]=1 if seq[i]=="G":xG[i]=1 if seq[i]=="C":xC[i]=1 xhatA=abs(fft(xA)) xhatG=abs(fft(xG)) xhatT=abs(fft(xT)) xhatC=abs(fft(xC)) xhat=[(xhatA[i]**2+xhatT[i]**2+xhatC[i]**2+xhatG[i]**2)*2/len(seq) for i in range(len(xhatA)/2,len(xhatA))] return xhat,[float(i)/len(xhat) for i in range(0,len(xhat))]
def EstimateReference(x, N, alpha=1., eps=1e-6): # X = fft(concatenate((zeros(len(x)),x))) X = fft(x) # R = X * conj(X) R = R + max(abs(R)) * eps # R = fft(correlate(x,x)) # plot(ifft(R)) # show() # R[abs(R)<1e-6] U = log(R) # U = concatenate((array([0.+0j]),log(R[1::]))) UU = ifft(U) # plot(real(UU)) # # show() i0 = int(floor(len(UU) / 2)) + 1 UU[1:i0] = 2 * UU[1:i0] UU[i0::] = 0. + 0j # W = exp(real(fft(UU))/2) W = exp(fft(UU) / 2) w = fftshift(real(ifft(W))) a = argmax(abs(w)) - int(N / 2) w = w[a:a + N] * tukey(N, alpha) return w
def real_imaginary_freq_domain(samples): ''' Apply fft on the samples and return the real and imaginary parts in separate ''' freq_domain = fft(samples) freq_domain_real = [abs(x.real) for x in freq_domain] freq_domain_imag = [abs(x.imag) for x in freq_domain] return freq_domain_real, freq_domain_imag
def psd(self): el = dle.DataLoaderEmotiv() #DataLoaderEmotiv() dic = {} dic = el.edf_loader() for k in dic: if k == "F3": x = np.fft(dic[k]) plt.plot(abs(x)) pl.show()
def real_imaginary_freq_domain(samples): """ Apply fft on the samples and return the real and imaginary parts in separate """ freq_domain = fft(samples) freq_domain_real = np_array([abs(x.real) for x in freq_domain]) freq_domain_imag = np_array([abs(x.imag) for x in freq_domain]) return freq_domain_real, freq_domain_imag
def _signal_psd_from_arma(ar=None, ma=None, rho=1., sampling_rate=1000, nfft=None, side="one-sided"): if ar is None and ma is None: raise ValueError("Either AR or MA model must be provided") psd = np.zeros(nfft, dtype=complex) if ar is not None: ip = len(ar) den = np.zeros(nfft, dtype=complex) den[0] = 1.0 + 0j for k in range(0, ip): den[k + 1] = ar[k] denf = np.fft.fft(den, nfft) if ma is not None: iq = len(ma) num = np.zeros(nfft, dtype=complex) num[0] = 1.0 + 0j for k in range(0, iq): num[k + 1] = ma[k] numf = np.fft(num, nfft) if ar is not None and ma is not None: psd = rho / sampling_rate * abs(numf)**2.0 / abs(denf)**2.0 elif ar is not None: psd = rho / sampling_rate / abs(denf)**2.0 elif ma is not None: psd = rho / sampling_rate * abs(numf)**2.0 psd = np.real(psd) # The PSD is a twosided PSD. # convert to one-sided if side == "one-sided": assert len(psd) % 2 == 0 one_side_psd = np.array(psd[0:len(psd) // 2 + 1]) * 2.0 one_side_psd[0] /= 2.0 # one_side_psd[-1] = psd[-1] psd = one_side_psd # convert to centerdc elif side == "centerdc": first_half = psd[0:len(psd) // 2] second_half = psd[len(psd) // 2:] rotate_second_half = second_half[-1:] + second_half[:-1] center_psd = np.concatenate((rotate_second_half, first_half)) center_psd[0] = psd[-1] psd = center_psd return psd
def feature_dft(self, img, pos): xlim = (max(pos[0] - self.window_size, 0), min(pos[0] + self.window_size, img.shape[1])) ylim = (max(pos[1] - self.window_size, 0), min(pos[1] + self.window_size, img.shape[0])) patch = img[ylim[0]:ylim[1], xlim[0]:xlim[1]] l = (2 * self.window_size + 1)**2 #return all zeros for now if we're at the edge if patch.shape[0] * patch.shape[1] != l: return np.zeros(l) return np.abs(np.fft(patch.flatten()))
def cross_correlation_using_fft(x, y): """ Performs Fourier Phase Shift between signals x and y Parameters ---------- x: numpy.ndarray Reference Signal y: numpy.ndarray Comparison Signal Returns ------- fourier_phase_shift: int Shift Index """ f1 = fft(x) f2 = fft(np.flipud(y)) cc = np.real(ifft(f1 * f2)) return fftshift(cc)
def MFCC(signal): numCoefficients = 13 # choose the sive of mfcc array minHz = 0 maxHz = 22.000 complexSpectrum = numpy.fft(signal) powerSpectrum = abs(complexSpectrum)**2 filteredSpectrum = numpy.dot(powerSpectrum, melFilterBank()) logSpectrum = numpy.log(filteredSpectrum) dctSpectrum = dct(logSpectrum, type=2) # MFCC :) return dctSpectrum
def bin_power(X,Band,Fs): C = fft(X) C = abs(C) # Check this code Power =zeros(len(Band)-1); for Freq_Index in xrange(0,len(Band)-1): Freq = float(Band[Freq_Index]) Next_Freq = float(Band[Freq_Index+1]) Power[Freq_Index] = sum(C[floor(Freq/Fs*len(X)):floor(Next_Freq/Fs*len(X))]) Power_Ratio = Power/sum(Power) return Power, Power_Ratio
def test_size_accuracy(self): # Sanity check for the accuracy for prime and non-prime sized inputs if self.rdt == np.float32: rtol = 1e-5 elif self.rdt == np.float64: rtol = 1e-10 for size in LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES: np.random.seed(1234) x = np.random.rand(size).astype(self.rdt) y = ifft(fft(x)) _assert_close_in_norm(x, y, rtol, size, self.rdt) y = fft(ifft(x)) _assert_close_in_norm(x, y, rtol, size, self.rdt) x = (x + 1j * np.random.rand(size)).astype(self.cdt) y = ifft(fft(x)) _assert_close_in_norm(x, y, rtol, size, self.rdt) y = fft(ifft(x)) _assert_close_in_norm(x, y, rtol, size, self.rdt)
def smoothGaussian1dMirror(array,sigma): array_reversed = list(array.copy()) array_reversed.reverse() array_reversed = numpy.array(array_reversed) array_mirrored = numpy.zeros(2*len(array)) array_mirrored[:len(array)] = array[:] array_mirrored[len(array):] = array_reversed[:] array_smoothed = numpy.ifft(numpy.fft(array_mirrored)*1/numpy.sqrt(2*numpy.pi)/sigma*numpy.exp(numpy.arange(0,len(array_mirrored),1.0)**2/2.0/sigma**2) ) array_smoothed = array_smoothed[:len(array)] print array_smoothed return array_smoothed
def mwave_fft(t, signal, fs, fa, K, t0, t1): """ FFT-based wavelet transform """ t = np.linspace(t0, t1, int((t1 - t0) * fs)) L = len(t) N = int(2**nextpow2(L)) fut = (fs / 2) * np.linspace(0, 1, int(N / 2)) data_f = fft(signal, N) return np.abs(ifft(data_f * kwave(K, fa, fs, t)))
def tiempo_feecuencia():##funcion que expone los pulsos en el dominio de su tiempo y frecuencia ##pulsos en el tiempo plt.subplot(2,1,1) plt.title('Funcion sinc en el tiempo') plt.xlabel('Tiempo(s)') plt.ylabel('Amplitud') plt.grid(True) plt.plot(t1,sinc, 'r') plt.subplot(2,1,2) plt.title('Funcion coseno alzado en el tiempo en el tiempo') plt.xlabel('Tiempo(s)') plt.ylabel('Amplitud') plt.grid(True) plt.plot(t1,coseno_alzado, 'b') plt.show() ##pulsos en la frecuencia transformada_sinc = abs(fft(sinc))/len(sinc) transformada_coseno_alzado = abs(fft(coseno_alzado))/len(coseno_alzado) k = np.fft.fftfreq(len(sinc),1) k2 = np.fft.fftfreq(len(coseno_alzado),1) plt.subplot(2,1,1) plt.title('Funcion sinc en su frecuencia') plt.xlabel('Freq (Hz)') plt.ylabel('|Y(freq)|') plt.grid(True) plt.plot(k,transformada_sinc/max(transformada_sinc), 'r') plt.subplot(2,1,2) plt.title('Funcion coseno alzado en su frecuencia') plt.xlabel('Freq (Hz)') plt.ylabel('|Y(freq)|') plt.plot(k,transformada_coseno_alzado/max(transformada_coseno_alzado),'b') plt.grid(True) plt.show()
def plot_pspec(history): #need to modify field=history['field'] rho=history['rho'] detune=history['detune'] plt.figure() fieldFFT = np.fftshift(np.fft(field.T)) # unconjugate complex transpose by .' Pspec=fieldFFT*np.conj(fieldFFT) plt.plot(detune*2*rho,Pspec) plt.axis([-0.06,+0.01,0,1.2*np.max(Pspec)]) plt.xlabel('{(\Delta\omega)/\omega_r}') plt.ylabel('{output spectral power} (a.u.)')
def generateIntensityTrace(df: float, noise: float): dx = (xMax - xMin) / N x = np.linspace(xMin, xMax, N) noise = random.exponential() * 0.05 y = 1 + np.cos(2 * np.pi / 0.6328 * x) + noise spectrum = fft(y) dx = x[1] - x[0] # on obtient dx, on suppose equidistant N = len(x) # on obtient N directement des données frequencies = fftfreq(N, dx) # Cette fonction est fournie par numpy wavelengths = 1 / frequencies # Les fréquences en µm^-1 sont moins utiles que lambda en µm return (wavelengths, frequencies, spectrum)
def testSinewaveFFT(self): N = 1024 xs = np.linspace(0, 6.28, N) # sine of frequency 1 array = np.sin(xs) spectrum = fft(array) self.assertTrue(np.argmax(abs(spectrum)) == 1) self.assertAlmostEqual(abs(spectrum[1]), abs(spectrum[-1]), places=6) self.assertAlmostEqual(np.angle(spectrum[1]), -np.angle(spectrum[-1]), places=6) self.assertAlmostEqual(np.angle(spectrum[1]), -np.pi / 2, places=2)
def some_visualisation(): spectrum_loc1 = spectrum[2] spectrum_trace = spectrum_loc1[10] l = np.shape(spectrum[2]) # Частотная характеристика ядра свертки по оси частот в отсчетах fft_h = abs(fft(kernel, l[1])**2) shape_kernel = np.shape(kernel) n_control = int(shape_kernel[0] // 2) axes = plt.subplots() plt.plot(spectrum_trace_control) plt.plot(spectrum_trace) plt.show() signal1 = np.abs(fft(spectrum_trace, l[1])**2) signal2 = np.abs(fft(spectrum_trace_control, l[1])**2) axes = plt.subplots() plt.plot(signal1) plt.plot(signal2) plt.plot(fft_h[n_control]) plt.show()
def adjust_w_vs_phi_plot(wpr, colorpower='log', logrange=6, hival=60, dirstr="1/", prefix="", savefigs=False,theme='hls'): [phidat,tdat,dipdat]=datfromfile(dirstr+"phase_vs_t.dat") phiarray,tarray,diparray=dattoarrays(phidat,tdat,dipdat) diparray*=exp(-1j*(wpr/Hrt)*tarray) ftdiparray=fft(diparray,axis=1) ftdiparray=fftshift(ftdiparray,axes=[1]) warray=warrayfromtarray(tarray) fig1=imshowplot_hsv(phiarray, warray, ftdiparray, colorpower, logrange, theme=theme, ymultfactor=Hrt) fig1a=imshowplot_fun(phiarray, warray, ftdiparray, colorpower, logrange, theme=theme, ymultfactor=Hrt,arrayfunction=logz)
def fourier_genome(seq): xA = [0 for i in range(0, len(seq))] xT = [0 for i in range(0, len(seq))] xG = [0 for i in range(0, len(seq))] xC = [0 for i in range(0, len(seq))] for i in range(0, len(seq)): if seq[i] == "A": xA[i] = 1 if seq[i] == "T": xT[i] = 1 if seq[i] == "G": xG[i] = 1 if seq[i] == "C": xC[i] = 1 xhatA = abs(fft(xA)) xhatG = abs(fft(xG)) xhatT = abs(fft(xT)) xhatC = abs(fft(xC)) xhat = [ (xhatA[i]**2 + xhatT[i]**2 + xhatC[i]**2 + xhatG[i]**2) * 2 / len(seq) for i in range(len(xhatA) / 2, len(xhatA)) ] return xhat, [float(i) / len(xhat) for i in range(0, len(xhat))]
def testHeneLongEquipe2Interferogram(self): N = 10500 dx = 0.2 xs = np.linspace(-N * dx / 2, N * dx / 2, N, endpoint=False) array = 10 + 0.5 * np.cos(2 * 3.14 / 0.6328 * xs) array = np.multiply(array, np.random.uniform(low=0.99, high=1.01, size=N)) self.saveInterferogram(xs, array, "hene-equipe2.txt") plt.plot(array, '-') plt.show() spectrum = fft(array) frequencies = fftfreq(N, dx)
def testHeneLongInterferogram(self): N = 1024 xs = np.linspace(-100, 100, N) # sine of frequency 1 dx = xs[1] - xs[0] array = 10 + 0.5 * np.cos(2 * 3.14 / 0.6328 * xs) array = np.multiply(array, np.random.uniform(low=0.99, high=1.01, size=N)) self.saveInterferogram(xs, array, "hene-long.txt") # plt.plot(array, '-') # plt.show() spectrum = fft(array) frequencies = fftfreq(N, dx)
def nsigtf_real(*args): nargin = len(args) if nargin < 4: raiseValueError('Not enough input arguments') # iscell if iscell(c) == 0: if np.ndims(c) == 2: N, chan_len = c.shape CH = 1 # c = mat2cell(c.',chan_len,ones(1,N)).') else: N, chan_len, CH = c.shape ctemp = mat2cell(np.permute(c,[2,1,3]),chan_len,np.ones((1,N)),np.ones((1,CH))) c = np.permute(ctemp,[2,3,1]) else: CH, N = c.shape posit = np.cumsum(shift) NN = posit[-1] posit = posit - shift[1] fr = np.zeros((NN,CH)) for ii in range(N): Lg = len(g[ii]) win_range = (posit[ii]+(-np.floor(Lg/2):math.ceil(Lg/2)-1)) % NN + 1 temp = np.fft(c[ii], [], 1) * len(c[ii]) if phasemode == 'global': fsNewBins = c[ii].shape[0] fkBins = posit[ii] displace = fkBins - np.floor(fkBins/fsNewBins) * fsNewBins temp = np.roll(temp, -displace) # temp = temp[] fr[win_range,:] = fr[win_Range,:] + temp * g[ii][Lg-np.floor(Lg/2)+1:Lg, 1:np.ceil(Lg/2)] nyqBin = np.floor(Ls/2) + 1 # fr[nyqBin+1:end] = conj( fr(nyqBin - (~logical(mod(Ls,2))) : -1 : 2) ) fr = np.real(np.fft.ifft(fr)) return fr
def testMercuryLampEquipe2Interferogram(self): N = 5000 dx = 0.2 xs = np.linspace(-N * dx / 2, N * dx / 2, N, endpoint=False) array = 10 + 0.5 * np.cos(2 * 3.14 / 0.579 * xs) + 0.8 * np.cos( 2 * 3.14 / 0.546 * xs) + 1.0 * np.cos(2 * 3.14 / 0.436 * xs) array = np.multiply(array, np.random.uniform(low=0.99, high=1.01, size=N)) self.saveInterferogram(xs, array, "mercure-equipe2.txt") plt.plot(array, '-') plt.show() spectrum = fft(array) frequencies = fftfreq(N, dx)
def testSodiumLampInterferogram(self): N = 30000 dx = 0.05 xs = np.linspace(0, N * dx, N) # sine of frequency 1 array = 2 + 0.5 * np.cos(3.14 / 0.589 * xs) + 0.5 * np.cos( 3.14 / 0.5896 * xs) array = np.multiply(array, np.random.uniform(low=0.99, high=1.01, size=N)) self.saveInterferogram(xs, array, "sodium-short.txt") # plt.plot(array, '-') # plt.show() spectrum = fft(array) frequencies = fftfreq(N, dx)
def getFourier(vec, freq): vec = vec - mean(vec) nframes = len(vec) ft = fft(vec) ft = ft[0:int(fix(nframes / 2))] ampFT = 2 * abs(ft) / nframes amp = ampFT[freq] co = zeros(size(amp)) sumAmp = sqrt(sum(ampFT**2)) co = amp / sumAmp ph = -(pi / 2) - angle(ft[freq]) if ph < 0: ph = ph + pi * 2 return array([co, ph])
def fourier_derivative_2nd(f, dx): # Length of vector f nx = f.size # Initialize k vector up to Nyquist wavenumber kmax = np.pi / dx dk = kmax / (nx / 2) k = np.arange(float(nx)) k[:nx / 2] = k[:nx / 2] * dk k[nx / 2:] = k[:nx / 2] - kmax # Fourier derivative ff = (1j * k)**2 * fft(f) df_num = ifft(ff).real return df_num
def stimulus_fft(type, wl, ratio): # STIMULUS_FFT uses fast fourier transform to plot the amplitude spectrum of a potential stimulus pattern # Inputs: # type - type of stimulus, e.g. 'bar'/'dog'/'square'/'log' (see below for full list) # wl - wavelength of stimulus in degrees (definition depends on stimulus stype) # ratio - ratio between black and white areas; usually ratio of amplitudes, but definition depends on stimulus type # example usage: stimulus_fft('dog', 10, 1) # Written by Jochen Smolka and John D. Kirwan, Lund University, 2017 # This file is published as supplementary to the following article: # John D. Kirwan, Michael J. Bok, Jochen Smolka, James J. Foster, José Carlos Hernández, Dan-Eric Nilsson (2017) # The sea urchin Diadema africanum uses low resolution vision to find shelter and deter enemies. Journal of Experimental Biology. import numpy as np import matplotlib.pyplot as plt ## set defaults if ratio == None: ratio=1; if wl == None: wl = 10; if type == None: type = 'bar'; va = np.arange(-180,179.99,0.1).tolist(); Fs = len(va); # Simulation resolution (points per 360 degrees) azi = np.linspace(0,Fs-1)/Fs * 360 - 180; # azimuth vector # check indexing 0 or 1 above S = stimulus_create(type, wl, va, ratio); # *so far, empty array* plt.figure(1); plt.clf(); plt.plot(azi,S) plt.title( print('%s, wl=%d', type, wl)) plt.xlabel('azimuth (\circ)') plt.ylabel('intensity') plt.axis([-180, 180, -1.1, 1.1]) Y = np.fft(S); P2 = abs(Y/Fs); P1 = P2(np.linspace(1,Fs/2+1,1)); #P2(1:Fs/2+1); P1[1:-1] = 2*P1(np.linspace(2,-1,1)); #Pythonic indexing f = Fs*(np.linspace(0,Fs/2,1))/Fs/360; plt.figure(2); plt.clf(); plt.plot(f, P1) plt.title( print(wl=%d', type, wl, format(5))) plt.xlabel('f (cycles / deg)') plt.ylabel('|P1(f)|') plt.xlim([0, 1]) ## Matlab is 1 indexed, while Python is zero indexed! Need to change all
def testMercuryLampInterferogram(self): N = 1024 xs = np.linspace(-100, 100, N) # sine of frequency 1 dx = xs[1] - xs[0] array = 10 + 0.5 * np.cos(2 * 3.14 / 0.579 * xs) + 0.8 * np.cos( 2 * 3.14 / 0.546 * xs) + 1.0 * np.cos(2 * 3.14 / 0.436 * xs) array = np.multiply(array, np.random.uniform(low=0.9, high=1.1, size=N)) self.saveInterferogram(xs, array, "mercure.txt") # plt.plot(array, '-') # plt.show() spectrum = fft(array) frequencies = fftfreq(N, dx)
def find_peak_phi(self, cross_corr=False, img=None): """ RMClean.find_peak_phi(cross_corr=False, img=None) Finds the index of the phi value at the peak of the residual image (or the image passed to the function). The peak can be found by a simple search algorithm, or by first cross correlating the image with the RMSF. Inputs: cross_corr- Perform a cross correlation between RMSF and res. map prior to seeking for the peak ala Heald 09 img- Image to search through. If none is given, the current residual image will be used. Outputs: 1- The pixel index of the phi value at the map peak """ phi_ndx = -1 peak_res = 0. if img is None: img = self.residual_map if not cross_corr: for i in range(len(img)): if (abs(img[i]) > peak_res): phi_ndx = i peak_res = abs(img[i]) else: temp_map_fft = numpy.fft(img) temp_map = numpy.ifft(temp_map_fft.conjugate() * numpy.fft(self.synth.rmsf)) phi_ndx = self.find_peak_phi(img=temp_map) return phi_ndx
def specdet1(signal, N): y = fft(signal, N) Py = abs(y) n_vect = arange(0, 4 * N) dsp = zeros(len(n_vect)) #périodisation du spectre sur [-2,2] for n in range(4): dsp[n * N:(n + 1) * N] = Py # affichage N_dsp = len(dsp) f = 4 * np.arange(-N_dsp / 2, N_dsp / 2) / N_dsp plot(f, dsp) xlabel('frequences normalisees f=F/Fe') ylabel('spectre d' 'amplitude') ylim([0, int(max(dsp)) + 1])