def problem4(): # read in tada.wav rate, tada = wavfile.read('tada.wav') # upon inspection, we find that tada.wav is a stereo audio file. # we create stereo white noise that lasts 10 seconds L_white = sp.int16(sp.random.randint(-32767,32767,rate*10)) R_white = sp.int16(sp.random.randint(-32767,32767,rate*10)) white = sp.zeros((len(L_white),2)) white[:,0] = L_white white[:,1] = R_white # pad tada signal with zeros padded_tada = sp.zeros_like(white) padded_tada[:len(tada)] = tada ptada = padded_tada # fourier transforms ftada = sp.fft(ptada,axis=0) fwhite = sp.fft(white,axis=0) # inverse transform of convolution out = sp.ifft((ftada*fwhite),axis=0) # prepping output and writing file out = sp.real(out) scaled = sp.int16(out / sp.absolute(out).max() * 32767) wavfile.write('my_tada_conv.wav',rate,scaled)
def XIntegralsFFT(GF_A,Bubble_A,Lambda,BubZero): ''' calculate X integral to susceptibilities using FFT ''' N = int((len(En_A)-1)/2) Kappa_A = TwoParticleBubble(GF_A,GF_A**2,'eh') Bubble_A = TwoParticleBubble(GF_A,GF_A,'eh') #print(Kappa_A[N],Bubble_A[N]) V_A = 1.0/(1.0+Lambda*Bubble_A) KV_A = Lambda*Kappa_A*V_A**2 KmV_A = Lambda*sp.flipud(sp.conj(Kappa_A))*V_A**2 ## zero-padding the arrays exFD_A = sp.concatenate([FD_A[N:],sp.zeros(2*N+2),FD_A[:N+1]]) ImGF_A = sp.concatenate([sp.imag(GF_A[N:]),sp.zeros(2*N+2),sp.imag(GF_A[:N+1])]) ImGF2_A = sp.concatenate([sp.imag(GF_A[N:]**2),sp.zeros(2*N+2),sp.imag(GF_A[:N+1]**2)]) ImV_A = sp.concatenate([sp.imag(V_A[N:]),sp.zeros(2*N+2),sp.imag(V_A[:N+1])]) ImKV_A = sp.concatenate([sp.imag(KV_A[N:]),sp.zeros(2*N+2),sp.imag(KV_A[:N+1])]) ImKmV_A = sp.concatenate([sp.imag(KmV_A[N:]),sp.zeros(2*N+2),sp.imag(KmV_A[:N+1])]) ## performing the convolution ftImX11_A = -sp.conj(fft(exFD_A*ImV_A))*fft(ImGF2_A)*dE ftImX12_A = fft(exFD_A*ImGF2_A)*sp.conj(fft(ImV_A))*dE ftImX21_A = -sp.conj(fft(exFD_A*ImKV_A))*fft(ImGF_A)*dE ftImX22_A = fft(exFD_A*ImGF_A)*sp.conj(fft(ImKV_A))*dE ftImX31_A = -sp.conj(fft(exFD_A*ImKmV_A))*fft(ImGF_A)*dE ftImX32_A = fft(exFD_A*ImGF_A)*sp.conj(fft(ImKmV_A))*dE ## inverse transform ImX1_A = sp.real(ifft(ftImX11_A+ftImX12_A))/sp.pi ImX2_A = sp.real(ifft(ftImX21_A+ftImX22_A))/sp.pi ImX3_A = -sp.real(ifft(ftImX31_A+ftImX32_A))/sp.pi ImX1_A = sp.concatenate([ImX1_A[3*N+4:],ImX1_A[:N+1]]) ImX2_A = sp.concatenate([ImX2_A[3*N+4:],ImX2_A[:N+1]]) ImX3_A = sp.concatenate([ImX3_A[3*N+4:],ImX3_A[:N+1]]) ## getting real part from imaginary X1_A = KramersKronigFFT(ImX1_A) + 1.0j*ImX1_A + BubZero # constant part !!! X2_A = KramersKronigFFT(ImX2_A) + 1.0j*ImX2_A X3_A = KramersKronigFFT(ImX3_A) + 1.0j*ImX3_A return [X1_A,X2_A,X3_A]
def prettymat(mat,fmt='%0.5g',eps=1e-14): # pdb.set_trace() if fmt[0]=='%': ifmt='%+'+fmt[1:] else: ifmt='%+'+fmt fmt='%'+fmt nc=scipy.shape(mat)[1] # print('[') outstr='[' # fmtstr=fmt +(nc-1)*(' & ' +fmt)+'\\\\' for currow in mat.tolist(): # curtuple=tuple(currow) # rowstr=fmtstr%curtuple rowstr='[' for x,ent in enumerate(currow): if abs(scipy.real(ent))>eps: realstr=fmt%scipy.real(ent) else: realstr='0' if abs(scipy.imag(ent))>eps: imagstr=ifmt%scipy.imag(ent)+'j' else: imagstr='' rowstr+=realstr+imagstr if x<(len(currow)-1): rowstr+=', ' if x==(len(currow)-1): rowstr+='],\n' outstr+=rowstr if outstr[-1]=='\n': outstr=outstr[0:-1] outstr+=']' print(outstr)
def add_shape(self, f): #Create shape S = Shape(f, self.R, self.SHAPE_R) #Add to shape list S.shape_num = len(self.shape_list) self.shape_list.append(S) row = [] for k in range(len(self.shape_list)): T = self.shape_list[k] ift = real(ipfft(pft_mult(pft_rotate(S.pft, 2.*pi/6.), T.pft), 2*self.SHAPE_R+1,2*self.SHAPE_R+1)) Spad = imrotate(cpad(S.indicator, array([2*self.SHAPE_R+1,2*self.SHAPE_R+1])), 360./6.) Tpad = cpad(T.indicator, array([2*self.SHAPE_R+1,2*self.SHAPE_R+1])) pind = real(fftconvolve(Spad, Tpad, mode='same')) imshow(pind) imshow(ift) obst = to_ind(pind, 0.001) imshow(obst) cutoff = best_cutoff(ift, obst, S.radius + T.radius) print cutoff imshow(to_ind(ift, cutoff)) row.append(cutoff * self.tarea) self.cutoff_matrix.append(row) return S
def rlsloo_ll1( V, D, Y, lambd): """ Computes cs and the actual LOO errors for a single value of lambda. (lambd) """ n = V.shape[0] cl = Y.shape[1] inner = 1/(D + lambd) inner = inner.conj() VtY = sp.dot(V.T, Y) VtY = VtY.conj() # Because of signs of D are flipped (scipy.linalg.eig returns # flipped signs for complex part of the eigenvalues) in_dot = sp.ones((n,1)) * inner ViD = V * in_dot cs = sp.dot(ViD, VtY) dGi = sp.sum(ViD*V, axis = 1) # -- till here works fine #check matrix dimensions looerrs = cs.ravel()/sp.real(dGi.ravel()) looerrs = sp.real(looerrs) cs = sp.real(cs.transpose()) return cs.ravel(), looerrs
def ipfft(pft, xs, ys): if(xs > 2 * len(pft) + 1 and ys > 2 * len(pft) + 1): return fftshift(real(ifft2(fftshift(polar2rect(pft, xs, ys))))) t = fftshift(real(ifft2(fftshift(polar2rect(pft, 2*len(pft)+1, 2*len(pft)+1))))) tx = len(pft) - xs / 2 ty = len(pft) - ys / 2 return t[tx:(tx+xs),ty:(ty+ys)]
def root_locus(sys, kvect, xlim=None, ylim=None, plotstr='-', Plot=True, PrintGain=True): """Calculate the root locus by finding the roots of 1+k*TF(s) where TF is self.num(s)/self.den(s) and each k is an element of kvect. Parameters ---------- sys : linsys Linear input/output systems (SISO only, for now) kvect : gain_range (default = None) List of gains to use in computing diagram Plot : boolean (default = True) If True, plot magnitude and phase PrintGain: boolean (default = True) If True, report mouse clicks when close to the root-locus branches, calculate gain, damping and print Return values ------------- rlist : list of computed root locations """ # Convert numerator and denominator to polynomials if they aren't (nump, denp) = _systopoly1d(sys); # Compute out the loci mymat = _RLFindRoots(sys, kvect) mymat = _RLSortRoots(sys, mymat) # Create the plot if (Plot): f = pylab.figure() if PrintGain: cid = f.canvas.mpl_connect( 'button_release_event', partial(_RLFeedbackClicks, sys=sys)) ax = pylab.axes(); # plot open loop poles poles = array(denp.r) ax.plot(real(poles), imag(poles), 'x') # plot open loop zeros zeros = array(nump.r) if zeros.any(): ax.plot(real(zeros), imag(zeros), 'o') # Now plot the loci for col in mymat.T: ax.plot(real(col), imag(col), plotstr) # Set up plot axes and labels if xlim: ax.set_xlim(xlim) if ylim: ax.set_ylim(ylim) ax.set_xlabel('Real') ax.set_ylabel('Imaginary') return mymat
def confMap(shape,mapfunc): shapemapped = [None]*len(shape) for i in range(0,len(shape)): shapemapped[i] = mapfunc(shape[i]) plt.scatter(sp.real(shape),sp.imag(shape),color='r') plt.scatter(sp.real(shapemapped),sp.imag(shapemapped),color='b') plt . show ()
def monitor_limitedFrames_MP(self, i): if self.centroid==True: fit_func = correlateFrames.cent else: fit_func = correlateFrames.fitCorrGaussian_v2 corr_func = correlateFrames.corr xdim_fft, ydim_fft = self.fft_target.shape #i = 0 #print "Dry Run? ", self.dry_run if (i<self.frames) and (not self.quit): self.active=True time.sleep(self.monitorDelay) self.times.append(time.clock()) if self.fr_change>0 and i>(self.unactive_until + self.initialFrames-1): ind = int(scipy.floor(i/self.fr_change)) self.conversion = self.conversions[ind] self.stage_zs.append(self.piezo.getPosition(3)-self.zoffset) target_gs_ht, defocus_ht_diff, target_xval, target_yval = self.getImage_doCorrs_inThread() self.target_signal.append(target_gs_ht) self.defocus_signal.append(defocus_ht_diff) latestSig = defocus_ht_diff / target_gs_ht self.xdrift.append(scipy.real(target_xval) - self.gaussFitRegion) self.ydrift.append(scipy.real(target_yval) - self.gaussFitRegion) if True: if i>(self.unactive_until + self.initialFrames-1): if i==self.unactive_until + self.initialFrames: self.initial_ds = scipy.mean(self.defocus_signal[self.unactive_until:]) self.initial_z = scipy.mean(self.stage_zs) self.initial_ts = scipy.mean(self.target_signal[self.unactive_until:]) self.sig0 = self.initial_ds/self.initial_ts print self.initial_z if i>(self.unactive_until+self.initialFrames): if self.use_multiplane and self.newplane>0: mp = int(i)/int(self.newplane) else: mp = 0 if not self.dry_run: self.react_z(self.initial_ds, self.initial_ts, self.initial_z, toprint=False, multiplane=mp) self.react_xy(rolling_av=self.rollingAvXY, toprint=False) initialSigFound = True else: initialSigFound = False if initialSigFound: return self.stage_zs[-1], self.xdrift[-1], self.ydrift[-1], self.sig0, latestSig else: return self.stage_zs[-1], self.xdrift[-1], self.ydrift[-1], -1, latestSig return 0,0,0,0,0
def rceps(x): y = sp.real(ifft(sp.log(sp.absolute(fft(x))))) n = len(x) if (n%2) == 1: ym = np.hstack((y[0], 2*y[1:n/2], np.zeros(n/2-1))) else: ym = np.hstack((y[0], 2*y[1:n/2], y[n/2+1], np.zeros(n/2-1))) ym = sp.real(ifft(sp.exp(fft(ym)))) return (y, ym)
def pltFunction (cavity1,cavity2,cavity3,plotType): if (plotType==0): return sp.absolute(cavity1[:])**2,sp.absolute(cavity2[:])**2,sp.absolute(cavity3[:])**2 elif (plotType==1): return sp.real(cavity1[:]),sp.real(cavity2[:]),sp.real(cavity3[:]) elif (plotType==2): return sp.imag(cavity1[:]),sp.imag(cavity2[:]),sp.imag(cavity3[:]) else: return cavity1, cavity2, cavity3
def sphericalPot(x,y,shift=0,radius=1,scale=1): from scipy import real,sqrt size_x = x.max() size_y = y.max() Vbottom = 0 x = x-size_x/2 left_sphere = real(sqrt(radius**2-(x**2+(y-shift)**2)))*heaviside(y-shift)+real(sqrt(radius**2-x**2))*heaviside(-(y-shift)) right_sphere = real(sqrt(radius**2-(x**2+(y-size_y+shift)**2)))*heaviside(-(y-size_y+shift))+real(sqrt(radius**2-x**2))*heaviside((y-size_y+shift)) V = Vbottom +scale*(left_sphere+right_sphere) return V
def RenormalizeFactor(excfile,gsfile,channel=None,Nsamp=1,O=None,q=None): if not type(excfile)==list: excfile=[excfile] if not type(gsfile)==list: gsfile=[gsfile] exat=GetAttr(excfile[0]) gsat=GetAttr(gsfile[0]) L=exat['L'] if q==None: q=sc.array([exat['qx'],exat['qy']]) if 'phasex' in exat.keys(): shift=sc.array([exat['phasex']/2.0,exat['phasey']/2.0]) else: shift=sc.array([exat['phase_shift_x']/2.0,exat['phase_shift_y']/2.0]) phi=exat['phi'] neel=exat['neel'] qx,qy,Sq=GetSq(gsfile) kx,ky=sf.fermisea(L,L,shift) qidx=ml.find((qx==q[0])*(qy==q[1])) if O==None: _,O,_,_=GetEigSys(excfile,Nsamp) pk=None sqq=None if channel==None: channel=exat['channel'] if channel=='trans': pk=sc.squeeze(sf.phiktrans(kx,ky,q[0]/L,q[1]/L,[phi,neel])) sqq=sc.real(0.5*(Sq[0,1,qidx]+Sq[0,2,qidx])) elif channel=='long': pkup=sc.squeeze(sf.phiklong(kx,ky,q[0]/L,q[1]/L,1,[phi,neel])) pkdo=sc.squeeze(sf.phiklong(kx,ky,q[0]/L,q[1]/L,-1,[phi,neel])) if (q[0]/L==0.5 and q[1]/L==0.5) or (q[0]/L==0 and q[1]/L==0): pk=sc.zeros(2*sc.shape(pkup)[0]+1,complex) else: pk=sc.zeros(2*sc.shape(pkup)[0],complex) pk[0:2*sc.shape(pkup)[0]:2]=pkup pk[1:2*sc.shape(pkdo)[0]:2]=pkdo if (qx[0]/L==0.5 and q[1]/L==0.5) or (q[0]/L==0 and q[1]/L==0): if neel==0: pk[-1]=0 else: pk[-1]=sum(neel/sf.omega(kx,ky,[phi,neel])) sqq=Sq[0,0,qidx] else: raise(InputFileError('In file \''+excfile+'\', channel=\''+str(channel)+'\'. Should be \'trans\' or \'long\'')) sqe=sc.einsum('i,jik,k->j',sc.conj(pk),O,pk) out=sc.zeros(Nsamp) for n in range(Nsamp): if abs(sqq)<1e-6 or abs(sqe[n])<1e-6: warnings.warn('Probably ill-defined renormalization, returns 1 for sample {0} out of {1}'.format(n,Nsamp),UserWarning) out[n]=1 else: out[n]=sc.real(sqq/sqe[n]) return out
def predictor_step(phi,args,direction): assert abs(direction)==1 Q = field_to_quasidensity(phi,args.L) Lambda = sp.exp(-args.t)*args.Delta + diags(Q,0) rho = sp.real(spsolve(Lambda, args.R-Q)) delta_t = direction*args.epsilon/sp.real(sp.sqrt(sp.sum(rho*Q*rho))) delta_phi = phi + delta_t*rho return [delta_phi, delta_t]
def grad(self, A, B, q): #Compute relative transformation pr = norm(q.x) if(pr >= A.radius + B.radius ): return array([0., 0., 0., 0.]) #Load shape parameters fa = A.pft fb = B.pft da = A.pdft db = B.pdft ea = A.energy eb = B.energy #Estimate cutoff threshold cutoff = self.__get_cutoff(A, B) #Compute coordinate coefficients m = 2.j * pi / (2. * self.SHAPE_R + 1) * pr phi = atan2(q.x[1], q.x[0]) #Set up initial sums s_0 = real(fa[0][0] * fb[0][0]) s_x = 0. s_y = 0. s_ta = 0. s_tb = 0. for r in range(1, self.R): #Compute theta terms dtheta = 2. * pi / len(fa[r]) theta = arange(len(fa[r])) * dtheta #Construct multiplier / v mult = exp((m * r) * cos(theta + phi)) * r * dtheta u = pds.shift(conjugate(fb[r]), q.theta) * mult v = fa[r] * u #Check for early out s_0 += sum(real(v)) if(s_0 + min(ea[r], eb[r]) <= cutoff): return array([0.,0.,0.,0.]) #Sum up gradient vectors v = real(1.j * v) s_x -= sum(v * sin(theta + phi) ) s_y -= sum(v * cos(theta + phi) ) s_t += sum(real(da[r] * u)) if(s_0 <= cutoff): return array([0., 0., 0., 0.]) return array([s_x, s_y, s_ta, s_tb, s_0])
def wigner(psi,xvec,yvec,g=sqrt(2)): """Wigner function for a state vector or density matrix at points xvec+i*yvec. Parameters ---------- state : qobj A state vector or density matrix. xvec : array_like x-coordinates at which to calculate the Wigner function. yvec : array_like y-coordinates at which to calculate the Wigner function. g : float Scaling factor for a = 0.5*g*(x+iy), default g=sqrt(2). Returns -------- W : array Values representing the Wigner function calculated over the specified range [xvec,yvec]. """ if psi.type=='ket' or psi.type=='oper': M=prod(psi.shape[0]) elif psi.type=='bra': M=prod(psi.shape[1]) else: raise TypeError('Input state is not a valid operator.') X,Y = meshgrid(xvec, yvec) amat = 0.5*g*(X + 1.0j*Y) wmat=zeros(shape(amat)) Wlist=array([zeros(shape(amat),dtype=complex) for k in range(M)]) Wlist[0]=exp(-2.0*abs(amat)**2)/pi if psi.type=='ket' or psi.type=='bra': psi=ket2dm(psi) wmat=real(psi[0,0])*real(Wlist[0]) for n in range(1,M): Wlist[n]=(2.0*amat*Wlist[n-1])/sqrt(n) wmat+= 2.0*real(psi[0,n]*Wlist[n]) for m in range(M-1): temp=copy(Wlist[m+1]) Wlist[m+1]=(2.0*conj(amat)*temp-sqrt(m+1)*Wlist[m])/sqrt(m+1) for n in range(m+1,M-1): temp2=(2.0*amat*Wlist[n]-sqrt(m+1)*temp)/sqrt(n+1) temp=copy(Wlist[n+1]) Wlist[n+1]=temp2 wmat+=real(psi[m+1,m+1]*Wlist[m+1]) for k in range(m+2,M): wmat+=2.0*real(psi[m+1,k]*Wlist[k]) return 0.5*wmat*g**2
def sliceFieldArr(Ein,NX,NY,NZ,SliceX,SliceY,SliceZ,figNum,fieldName): """ Visualizing field with slices """ vxy1=Ein[:,:,SliceZ,0] vxy2=Ein[:,:,SliceZ,1] vxy3=Ein[:,:,SliceZ,2] vyz1=Ein[SliceX,:,:,0] vyz2=Ein[SliceX,:,:,1] vyz3=Ein[SliceX,:,:,2] vxz1=Ein[:,SliceY,:,0] vxz2=Ein[:,SliceY,:,1] vxz3=Ein[:,SliceY,:,2] plt.ion() fig=plt.figure(figNum) fig.clear() plt.subplot(331) plt.imshow(sci.real(vxy1)) plt.title('real($'+fieldName+'_{x}$), xy-plane') plt.colorbar() plt.subplot(332) plt.imshow(sci.real(sci.swapaxes(vxz1,0,1))) plt.title('real($'+fieldName+'_{x}$), xz-plane') plt.colorbar() plt.subplot(333) plt.imshow(sci.real(sci.swapaxes(vyz1,0,1))) plt.title('real($'+fieldName+'_{x}$), yz-plane') plt.colorbar() plt.subplot(334) plt.imshow(sci.real(vxy2)) plt.title('real($'+fieldName+'_{y}$), xy-plane') plt.colorbar() plt.subplot(335) plt.imshow(sci.real(sci.swapaxes(vxz2,0,1))) plt.title('real($'+fieldName+'_{y}$), xz-plane') plt.colorbar() plt.subplot(336) plt.imshow(sci.real(sci.swapaxes(vyz2,0,1))) plt.title('real($'+fieldName+'_{y}$), yz-plane') plt.colorbar() plt.subplot(337) plt.imshow(sci.real(vxy3)) plt.title('real($'+fieldName+'_{z}$), xy-plane') plt.colorbar() plt.subplot(338) plt.imshow(sci.real(sci.swapaxes(vxz3,0,1))) plt.title('real($'+fieldName+'_{z}$), xz-plane') plt.colorbar() plt.subplot(339) plt.imshow(sci.real(sci.swapaxes(vyz3,0,1))) plt.title('real($'+fieldName+'_{z}$), yz-plane') plt.colorbar() fig.canvas.draw() plt.ioff() return
def _wigner_laguerre(rho, xvec, yvec, g, parallel): """ Using Laguerre polynomials from scipy to evaluate the Wigner function for the density matrices :math:`|m><n|`, :math:`W_{mn}`. The total Wigner function is calculated as :math:`W = \sum_{mn} \\rho_{mn} W_{mn}`. """ M = np.prod(rho.shape[0]) X, Y = meshgrid(xvec, yvec) A = 0.5 * g * (X + 1.0j * Y) W = zeros(np.shape(A)) # compute wigner functions for density matrices |m><n| and # weight by all the elements in the density matrix B = 4 * abs(A) ** 2 if sp.isspmatrix_csr(rho.data): # for compress sparse row matrices if parallel: iterator = ( (m, rho, A, B) for m in range(len(rho.data.indptr) - 1)) W1_out = parfor(_par_wig_eval, iterator) W += sum(W1_out) else: for m in range(len(rho.data.indptr) - 1): for jj in range(rho.data.indptr[m], rho.data.indptr[m + 1]): n = rho.data.indices[jj] if m == n: W += real(rho[m, m] * (-1) ** m * genlaguerre(m, 0)(B)) elif n > m: W += 2.0 * real(rho[m, n] * (-1) ** m * (2 * A) ** (n - m) * sqrt(factorial(m) / factorial(n)) * genlaguerre(m, n - m)(B)) else: # for dense density matrices B = 4 * abs(A) ** 2 for m in range(M): if abs(rho[m, m]) > 0.0: W += real(rho[m, m] * (-1) ** m * genlaguerre(m, 0)(B)) for n in range(m + 1, M): if abs(rho[m, n]) > 0.0: W += 2.0 * real(rho[m, n] * (-1) ** m * (2 * A) ** (n - m) * sqrt(factorial(m) / factorial(n)) * genlaguerre(m, n - m)(B)) return 0.5 * W * g ** 2 * np.exp(-B / 2) / pi
def istft(X, chunk_size, hop, w=None): """ Naively inverts the short time fourier transform using an overlap and add method. The overlap is defined by hop Args: X: STFT windows to invert, overlap and add. chunk_size: size of analysis window. hop: hop distance between analysis windows w: windowing function to apply. Must be of length chunk_size Returns: ISTFT of X using an overlap and add method. Windowing used to smooth. Raises: ValueError if window w is not of size chunk_size """ if not w: w = sp.hanning(chunk_size) else: if len(w) != chunk_size: raise ValueError("window w is not of the correct length {0}.".format(chunk_size)) x = sp.zeros(len(X) * (hop)) i_p = 0 for n, i in enumerate(range(0, len(x)-chunk_size, hop)): x[i:i+chunk_size] += w*sp.real(sp.ifft(X[n])) return x
def __init__(self, output='out', input='in', \ mag=None, phase=None, coh=None, \ freqlim=[], maglim=[], phaselim=[], \ averaged='not specified', \ seedfreq=-1, seedphase=0, labels=[], legloc=-1, compin=[]): self.output = output self.input = input if len(compin) > 0: if mag is None: self.mag = squeeze(colwise(abs(compin))) if phase is None: self.phase = squeeze(colwise(arctan2(imag(compin),real(compin))*180.0/pi)) else: self.mag = squeeze(mag) self.phase = squeeze(phase) self.coh = coh self.averaged = averaged self.seedfreq = seedfreq self.seedphase = seedphase self.freqlim = freqlim self.maglim = maglim self.phaselim = phaselim self.labels = labels self.legloc = legloc
def bulk_bands_calculator(self,s,sub,kx,ky,kz): ''' Calculate the band energies for the specified kx, ky, and kz values. The 3x3 Hamiltonian for wurtzite crystals is used for the valence, while a 1x1 Hamiltonian is used for the conduction band. The model is from the chapter by Vurgaftman and Meyer in the book by Piprek. ''' E = scipy.zeros((4,len(s.Eg0))) E[0,:] = s.Eg0+s.delcr+s.delso/3+\ hbar**2/(2*s.mepara)*(kx**2+ky**2)+\ hbar**2/(2*s.meperp)*(kz**2)+\ (s.a1+s.D1)*s.epszz+(s.a2+s.D2)*(s.epsxx+s.epsyy) L = hbar**2/(2*m0)*(s.A1*kz**2+s.A2*(kx+ky)**2)+\ s.D1*s.epszz+s.D2*(s.epsxx+s.epsyy) T = hbar**2/(2*m0)*(s.A3*kz**2+s.A4*(kx+ky)**2)+\ s.D3*s.epszz+s.D4*(s.epsxx+s.epsyy) F = s.delcr+s.delso/3+L+T G = s.delcr-s.delso/3+L+T K = hbar**2/(2*m0)*s.A5*(kx+1j*ky)**2+s.D5*(s.epsxx-s.epsyy) H = hbar**2/(2*m0)*s.A6*(kx+1j*ky)*kz+s.D6*(s.epsxz) d = scipy.sqrt(2)*s.delso/3 for ii in range(len(s.Eg0)): mat = scipy.matrix([[ F[ii], K[ii], -1j*H[ii] ], [ K[ii], G[ii], -1j*H[ii]+d[ii]], [-1j*H[ii], -1j*H[ii]+d[ii], L[ii] ]]) w,v = scipy.linalg.eig(mat) E[1:,ii] = scipy.flipud(scipy.sort(scipy.real(w))) return E
def gabor2d(gsw, gsh, gx0, gy0, wfreq, worient, wphase, shape): """ Generate a gabor 2d array Inputs: gsw -- standard deviation of the gaussian envelope (width) gsh -- standard deviation of the gaussian envelope (height) gx0 -- x indice of center of the gaussian envelope gy0 -- y indice of center of the gaussian envelope wfreq -- frequency of the 2d wave worient -- orientation of the 2d wave wphase -- phase of the 2d wave shape -- shape tuple (height, width) Outputs: gabor -- 2d gabor with zero-mean and unit-variance """ height, width = shape y, x = N.mgrid[0:height, 0:width] X = x * N.cos(worient) * wfreq Y = y * N.sin(worient) * wfreq env = N.exp( -.5 * ( ((x-gx0)**2./gsw**2.) + ((y-gy0)**2./gsh**2.) ) ) wave = N.exp( 1j*(2*N.pi*(X+Y) + wphase) ) gabor = N.real(env * wave) gabor -= gabor.mean() gabor /= fastnorm(gabor) return gabor
def calc_a_coef(self): a = self.a nu = self.nu k = self.k arc_R = self.arc_R M = self.M fft_a_coef = self.get_expected_a_coef() if self.acheat: self.a_coef = fft_a_coef else: eval_phi0 = self.problem.eval_phi0 def eval_bc0(th): r = self.boundary.eval_r(th) return eval_phi0(th) - self.v_interp(r, th) a_coef, singvals = abcoef.calc_a_coef(self.problem, self.boundary, eval_bc0, self.M, self.problem.get_m1()) self.a_coef = a_coef np.set_printoptions(precision=4) if self.boundary.name == 'arc': error = np.abs(self.a_coef - fft_a_coef) print('a_coef error:', error) print() elif self.problem.name == 'iz-bessel': print('a_coef:', scipy.real(a_coef)) print()
def HolsteinPrimakoff( generation, lattice = "cactus", periodic = True ): """ Given a generation we want to build the cactus out to construct the matrix and return the eigenvalues. We will do this in the semi-roundabout way proposed by Mucciolo, Castro Neto, and Chamon in PRB 69 (214424), so what is returned is the true eigenspectrum and an eigenvalue matrix representing the rotations of a boguliobov-type transformation. """ if lattice == "cactus": H = HusimiHamiltonian( generation, periodic ) elif lattice == "triangle": H = TriangleHamiltonian( generation ) else: raise ValueError, "Options are 'cactus' and 'triangle'" l = H.shape[0] / 2 K = H[:l, :l] L = H[:l, l:] squaredDiff = scipy.dot(K, K) - scipy.dot(L, L) commutator = scipy.dot(L,K) - scipy.dot(K,L) if scipy.sum(commutator) == 0.0: eigVals, eigVects = scipy.linalg.eigh( squaredDiff ) else: eigVals, eigVects = scipy.linalg.eig( squaredDiff - commutator ) # The 'real' is not a cheat -- zero values could be negative as a result # of roundoff, this takes that into account. eigVals = scipy.real( scipy.sqrt( eigVals ) ) return eigVals, eigVects
def construct(phi1, phi2, nomod = 0, amp1 =[], amp2=[], eta = 0, ampout= 0): #does ampout need to be there? if len(amp1) > 0 or len(amp2) > 0: tempshape = phi1.shape w = tempshape[1] h = tempshape[0] if len(amp1) == 0: temp1 = np.ones(w) temp2 = np.ones(h) for r in temp2: amp1 += [temp1] if len(amp2) == 0: temp1 = np.ones(w) temp2 = np.ones(h) for r in temp2: amp2 += [temp1] psi1 = amp1 * np.exp(1j*phi1) psi2 = amp2 * np.exp(1j*phi2) psi = psi1 * psi2 psi = np.array(psi) apsi = abs(psi) psi = psi/(np.amax(abs(psi))) phi = np.arctan2(sp.real(psi),sp.imag(psi)) phi -= np.amin(phi) phi = phi % (2.*np.pi) eta = 2*np.median(abs(psi)) randarray = np.array([[random.random() for i in range(w)] for j in range(h)]) shape = (abs(psi) >= (eta*randarray)) index = np.where(shape == False) phi[index] = 0 ampout = abs(psi) else: phi = phi1 + phi2 phi = phi - np.amin(phi) phi = phi % (2.*np.pi) return phi
def bb_step(sys,X0=None,Tf=None,Ts=0.001): """Plot the step response of the continous system sys Call: y=bb_step(sys [,Tf=final time] [,Ts=time step]) Parameters ---------- sys : Continous System in State Space form X0: Initial state vector (not used yet) Ts : sympling time Tf : Final simulation time Returns ------- Nothing """ if Tf==None: vals = eigvals(sys.A) r = min(abs(real(vals))) if r < 1e-10: r = 0.1 Tf = 7.0 / r sysd=c2d(sys,Ts) dstep(sysd,Tf=Tf)
def fidelity(A,B): """ Calculates the fidelity (pseudo-metric) between two density matricies. See: Nielsen & Chuang, "Quantum Computation and Quantum Information" Parameters ---------- A : qobj Density matrix B : qobj Density matrix with same dimensions as A. Returns ------- fid : float Fidelity pseudo-metric between A and B. Examples -------- >>> x=fock_dm(5,3) >>> y=coherent_dm(5,1) >>> fidelity(x,y) 0.24104350624628332 """ if A.dims!=B.dims: raise TypeError('Density matricies do not have same dimensions.') else: A=A.sqrtm() return float(real((A*(B*A)).sqrtm().tr()))
def _par_wig_eval(args): """ Private function for calculating terms of Laguerre Wigner function in parfor. """ m,rho,A,B=args W1 = zeros(shape(A)) for jj in range(rho.data.indptr[m], rho.data.indptr[m+1]): n = rho.data.indices[jj] if m == n: W1 += real(rho[m,m] * (-1)**m * genlaguerre(m,0)(B)) elif n > m: W1 += 2.0 * real(rho[m,n] * (-1)**m * (2*A)**(n-m) * \ sqrt(factorial(m)/factorial(n)) * genlaguerre(m,n-m)(B)) return W1
def KramersKronigFFT(ImX_A): ''' Hilbert transform used to calculate real part of a function from its imaginary part uses piecewise cubic interpolated integral kernel of the Hilbert transform use only if len(ImX_A)=2**m-1, uses fft from scipy.fftpack ''' X_A = sp.copy(ImX_A) N = int(len(X_A)) ## be careful with the data type, orherwise it fails for large N if N > 3e6: A = sp.arange(3,N+1,dtype='float64') else: A = sp.arange(3,N+1) X1 = 4.0*sp.log(1.5) X2 = 10.0*sp.log(4.0/3.0)-6.0*sp.log(1.5) ## filling the kernel if N > 3e6: Kernel_A = sp.zeros(N-2,dtype='float64') else: Kernel_A = sp.zeros(N-2) Kernel_A = (1-A**2)*((A-2)*sp.arctanh(1.0/(1-2*A))+(A+2)*sp.arctanh(1.0/(1+2*A)))\ +((A**3-6*A**2+11*A-6)*sp.arctanh(1.0/(3-2*A))+(A+3)*(A**2+3*A+2)*sp.arctanh(1.0/(2*A+3)))/3.0 Kernel_A = sp.concatenate([-sp.flipud(Kernel_A),sp.array([-X2,-X1,0.0,X1,X2]),Kernel_A])/sp.pi ## zero-padding the functions for fft ImXExt_A = sp.concatenate([X_A[int((N-1)/2):],sp.zeros(N+2),X_A[:int((N-1)/2)]]) KernelExt_A = sp.concatenate([Kernel_A[N:],sp.zeros(1),Kernel_A[:N]]) ## performing the fft ftReXExt_A = -fft(ImXExt_A)*fft(KernelExt_A) ReXExt_A = sp.real(ifft(ftReXExt_A)) ReX_A = sp.concatenate([ReXExt_A[int((3*N+3)/2+1):],ReXExt_A[:int((N-1)/2+1)]]) return ReX_A
def acker(A,B,poles): """Pole placemenmt using Ackermann method Call: k=acker(A,B,poles) Parameters ---------- A, B : State and input matrix of the system poles: desired poles Returns ------- k: matrix State feedback gains """ a=mat(A) b=mat(B) p=real(poly(poles)) ct=ctrb(A,B) if det(ct)==0: k=0 print "Pole placement invalid" else: n=size(p) pmat=p[n-1]*a**0 for i in arange(1,n): pmat=pmat+p[n-i-1]*a**i k=inv(ct)*pmat k=k[-1][:] return k
def export(self, filename): # Casting as reals and absolute maximum? scaled = sp.real(self.wave) scaled = sp.int16(scaled * 32676. / scaled.max()) wavfile.write(filename, self.rate, scaled)
def real_func(x): return real(func(x))
def computePCA(matrix=None): #compute eigen values and vectors [eigen_values, eigen_vectors] = linalg.eig(matrix) #sort eigen vectors in decreasing order based on eigen values indices = sp.argsort(-eigen_values) return [sp.real(eigen_values[indices]), eigen_vectors[indices]]
import matplotlib.pyplot as plt import scipy from SloppyCell.ReactionNetworks import * from geodesic import geodesic, InitialVelocity import model18_fit x = np.log(model18_fit.popt) # Calculate jtj approximation to hessian (in log params) and plot eigenvalue # spectrum j = model18_fit.m.jacobian_log_params_sens(np.log(model18_fit.popt)) jtj = np.dot(np.transpose(j), j) np.savetxt('hessian18.dat', jtj) e, v = Utility.eig(jtj) e = scipy.real(e) Plotting.figure(1) l = Plotting.plot_eigval_spectrum(e, offset=0.15, widths=0.7, lw=2) ## Reduce func = lambda logp: np.array(model18_fit.m.res_log_params(logp)) jacobian = lambda logp: np.array( model18_fit.m.jacobian_log_params_sens(logp).values()) M = jacobian(x).shape[0] N = jacobian(x).shape[1] print(M) print(N)
def tdo_fft(inputfile, outputfile): ''' Perform Fourier transform and return frequency evolution ''' # Input parameters fourier_le = 1024 # Fourier length time_le = 1024 # timewindow dfmin = 0.01 # Frequency resolution dt = 2e-8 # timestep of acquisition load_balancing = 1 # Lecture du fichier fid = open(inputfile, 'rb') fid.seek(512) # Skip useless header V = fromfile(fid, int16, -1, '') fid.close() pstart = 1 # First timewindow pend = int(floor( (len(V) - 4 * fourier_le) / time_le)) + 1 # Last timewindow t = arange(0, fourier_le) * dt # Approximation of main frequency Vf = abs(real(fft(V[0:fourier_le]))) tf = fftfreq(fourier_le, dt) fmax = zeros((pend + 2 - pstart, 2)) fmax[0, 1] = tf[argmax(Vf[0:int(fourier_le / 2)])] fmax[0, 0] = time_le * dt / 2 # Calculation of constants expon = -2j * pi * t deltaf0 = tf[1] / 1000 if deltaf0 < dfmin: deltaf0 = 10 * dfmin # Start jobs job_server = pp.Server() ncpus = int(job_server.get_ncpus()) serv_jobs = [] # Load-balancing # Last processes are faster # If nprocess = ncpus, half of the core remains mostly idle if load_balancing == 1: nprocess = ncpus * 4 else: nprocess = ncpus pstart_b = pstart for i in range(0, nprocess): if nprocess == 1: pend_b = pend else: pend_b = int(pstart_b + floor(pend / nprocess)) print(pstart_b, pend_b) args_tuple = (pstart_b, pend_b+1, \ V[pstart_b*time_le:(pend_b+1)*time_le+fourier_le], \ dt, dfmin, deltaf0, expon, fourier_le, time_le,) serv_jobs.append(job_server.submit(find_freq, args_tuple, \ (local_trapz,))) pstart_b = pend_b pstart_b = pstart for i in range(0, nprocess): if nprocess == 1: pend_b = pend else: pend_b = int(pstart_b + floor(pend / nprocess)) fmax[pstart_b:pend_b, :] = serv_jobs[i]() pstart_b = pend_b # Save calculation in file savetxt(outputfile, fmax) job_server.print_stats()
def find_freq(ps, pe, V, dt, dfmin, deltaf0, expon, fourier_le, time_le): '''Perform DFT of signal and return main frequency''' from scipy import zeros, real, fft, argmax, exp, arange, cos, pi, mean from scipy.fftpack import fftfreq Vf = abs(real(fft(V[0:fourier_le] - mean(V[0:fourier_le])))) tf = fftfreq(fourier_le, dt) fmax = zeros((pe - ps, 2)) fmax[0, 1] = tf[argmax(Vf[0:int(fourier_le / 2)])] fmax[0, 0] = (ps * time_le + fourier_le / 2) * dt # Rectangular #window = ones(fourier_le) # Cosinus window = arange(0, fourier_le) window = 1 - cos(window * 2 * pi / (fourier_le - 1)) for i in xrange(1, pe - ps): # Utilisation de la dernière valeur comme point de depart a = fmax[i - 1, 1] V_temp = window * V[i * time_le:i * time_le + fourier_le] # Previous frequency spectral weight # Complex exponential time consuming # Need a smarter way to perform this calculations deltaf = deltaf0 essaimax = abs(local_trapz(V_temp * exp(expon * a))) # Calculation of local derivative of Fourier transform # If derivative positive, then search for frequency in growing direction if abs(local_trapz(V_temp * exp(expon * (a + deltaf)))) > essaimax: while abs(deltaf) > dfmin: F = abs(local_trapz(V_temp * exp(expon * (a + deltaf)))) if F > essaimax: essaimax = F a += deltaf else: deltaf = -deltaf / 5 if (abs(deltaf) < dfmin) and (abs(deltaf) > dfmin * 4.9): deltaf = deltaf / abs(deltaf) * 1.01 * dfmin # Store frequency fmax[i, 0:2] = [((i + ps) * time_le + fourier_le / 2) * dt, a - 2.5 * deltaf] # Lower frequency otherwise else: while abs(deltaf) > dfmin: F = abs(local_trapz(V_temp * exp(expon * (a - deltaf)))) if F > essaimax: essaimax = F a -= deltaf else: deltaf = -deltaf / 5 if (abs(deltaf) < dfmin) and (abs(deltaf) > dfmin * 4.9): deltaf = deltaf / abs(deltaf) * 1.01 * dfmin # Store frequency fmax[i, 0:2] = [((i + ps) * time_le + fourier_le / 2) * dt, a + 2.5 * deltaf] return fmax[1:, :]
def preproc(): img = cv2.imread('5DnwY.jpg', 0) # Number of rows and columns [cols, rows] = img.shape # Remove some columns from the beginning and end img = img[:, 59:cols - 20] # Convert image to 0 to 1, then do log(1 + I) imgLog = np.log1p(np.array(img, dtype="float") / 255) # Create Gaussian mask of sigma = 10 M = 2 * rows + 1 N = 2 * cols + 1 sigma = 10 (X, Y) = np.meshgrid(np.linspace(0, N - 1, N), np.linspace(0, M - 1, M)) centerX = np.ceil(N / 2) centerY = np.ceil(M / 2) gaussianNumerator = (X - centerX)**2 + (Y - centerY)**2 # Low pass and high pass filters Hlow = np.exp(-gaussianNumerator / (2 * sigma * sigma)) Hhigh = 1 - Hlow # Move origin of filters so that it's at the top left corner to # match with the input image HlowShift = scipy.fftpack.ifftshift(Hlow.copy()) HhighShift = scipy.fftpack.ifftshift(Hhigh.copy()) # Filter the image and crop If = scipy.fftpack.fft2(imgLog.copy(), (M, N)) Ioutlow = scipy.real(scipy.fftpack.ifft2(If.copy() * HlowShift, (M, N))) Iouthigh = scipy.real(scipy.fftpack.ifft2(If.copy() * HhighShift, (M, N))) # Set scaling factors and add gamma1 = 0.3 gamma2 = 1.5 Iout = gamma1 * Ioutlow[0:rows, 0:cols] + gamma2 * Iouthigh[0:rows, 0:cols] # Anti-log then rescale to [0,1] Ihmf = np.expm1(Iout) Ihmf = (Ihmf - np.min(Ihmf)) / (np.max(Ihmf) - np.min(Ihmf)) Ihmf2 = np.array(255 * Ihmf, dtype="uint8") # Threshold the image - Anything below intensity 65 gets set to white Ithresh = Ihmf2 < 65 Ithresh = 255 * Ithresh.astype("uint8") # Clear off the border. Choose a border radius of 5 pixels Iclear = imclearborder(Ithresh, 5) # Eliminate regions that have areas below 120 pixels Iopen = bwareaopen(Iclear, 120) # Show all images cv2.imshow('Original Image', img) cv2.imshow('Homomorphic Filtered Result', Ihmf2) cv2.imshow('Thresholded Result', Ithresh) cv2.imshow('Opened Result', Iopen) cv2.waitKey(0) cv2.destroyAllWindows()
# Initialize vortex omega, p = nst.vortex_pair(nx, ny, dx, dy) # Gradient operators in Fourier domain for x- and y-direction Kx, Ky = nst.Spectral_Gradient(nx, ny, lx, ly) # 2D Laplace operator and 2D inverse Laplace operator in Fourier domain K2, K2inv = nst.Spectral_Laplace(nx, ny, Kx, Ky) # Simulation time #T_simu = 0.165 T_simu = 0.01 # Set discrete time step by choosing CFL number (condition: CFL <= 1) CFL = 1 u = sc.real(ifft2(-Ky * K2inv * fft2(omega))) v = sc.real(ifft2(Kx * K2inv * fft2(omega))) u_max = sc.amax(sc.absolute(u)) v_max = sc.amax(sc.absolute(v)) t_step = (CFL * dx * dy) / (u_max * dy + v_max * dx) # Delete (if existent) "Data.txt" before writing new data if os.path.exists("Data"): os.remove("Data") # Open file file = open("Data", "ab") # Start Simulation t_sum = 0 i = 0
def real_func(x): return scipy.real(func(x))
def real_func(x, y): return scipy.real(func(x, y))
m1 = Im1[it_m1] # c1 = sp.special.jn(m1, b * x_net) * x_net c1 = c1_coefs[it_m1, :] for it_h1 in range(len(Ih1)): h1 = Ih1[it_h1] c2 = c2_coefs[it_h1, :] * c1 # c2 = sp.special.jn(h1, b * x_net) * c1 for it_mm in range(len(Imm)): mm = Imm[it_mm] coef = 2 * np.pi * np.exp(1j * (h1 + mm) * eps) # Fm = FBT(pol1, m1+h1+mm, x_net, u_net, theta_net) # Fm_arr[it_m1 + it_h1 + it_mm] = Fm Fm = Fm_arr[it_m1 + it_h1 + it_mm] Gm = Gm_arr[it_mm] func = Fm * np.conj(Gm) * c2 Tf[it_m1, it_h1, it_mm] = np.trapz(sp.real(func), x_net) \ + 1j*np.trapz(sp.imag(func), x_net) Tf[it_m1, it_h1, it_mm] *= coef # for it_m1 in tqdm.tqdm(range(len(Im1))): # m1 = Im1[it_m1] # c1 = sp.special.jn(m1, b * x_net) * x_net # for it_h1 in range(len(Ih1)): # h1 = Ih1[it_h1] # # c2 = c2_coefs[it_m1, it_h1, :] # c2 = sp.special.jn(h1, b * x_net) * c1 # for it_mm in range(len(Imm)): # mm = Imm[it_mm] # coef = 2*np.pi * np.exp(1j*(h1+mm)*eps) # # Fm = FBT(pol1, m1+h1+mm, x_net, u_net, theta_net) # # Fm_arr[it_m1 + it_h1 + it_mm] = Fm