def damp(A): # Original Author: Kai P. Mueller <*****@*****.**> for Octave # Created: September 29, 1997. print("............... Eigenvalue ........... Damping Frequency") print("--------[re]---------[im]--------[abs]----------------------[Hz]") e, _ = la.eig(A) for i in range(len(e)): pole = e[i] d0 = -sp.cos(math.atan2(sp.imag(pole), sp.real(pole))) f0 = 0.5 / sp.pi * abs(pole) if (abs(sp.imag(pole)) < abs(sp.real(pole))): print( ' {:.3f} {:.3f} {:.3f} {:.3f}' .format(float(sp.real(pole)), float(abs(pole)), float(d0), float(f0))) else: print( ' {:.3f} {:+.3f} {:.3f} {:.3f} {:.3f}' .format(float(sp.real(pole)), float(sp.imag(pole)), float(abs(pole)), float(d0), float(f0)))
def SelfEnergyD_sc(Gup_A, Gdn_A, GTup_A, GTdn_A, Lambda, spin): ''' dynamic self-energy, calculates the complex function from FFT ''' if spin == 'up': BubbleD_A = BubbleD(GTup_A, GTdn_A, Lambda, spin) GF_A = sp.copy(Gdn_A) Det_A = DeterminantGD(Lambda, GTup_A, GTdn_A) else: ## spin='dn' BubbleD_A = BubbleD(GTdn_A, GTup_A, Lambda, spin) GF_A = sp.copy(Gup_A) Det_A = sp.flipud(sp.conj(DeterminantGD(Lambda, GTup_A, GTdn_A))) Kernel_A = U * BubbleD_A / Det_A ## zero-padding the arrays FDex_A = sp.concatenate( [FD_A[Nhalf:], sp.zeros(2 * Nhalf + 3), FD_A[:Nhalf]]) BEex_A = sp.concatenate( [BE_A[Nhalf:], sp.zeros(2 * Nhalf + 3), BE_A[:Nhalf]]) GFex_A = sp.concatenate( [GF_A[Nhalf:], sp.zeros(2 * Nhalf + 3), GF_A[:Nhalf]]) Kernelex_A = sp.concatenate( [Kernel_A[Nhalf:], sp.zeros(2 * Nhalf + 3), Kernel_A[:Nhalf]]) ## performing the convolution ftSE1_A = -sp.conj(fft(BEex_A * sp.imag(Kernelex_A))) * fft(GFex_A) * dE ftSE2_A = +fft(FDex_A * sp.imag(GFex_A)) * sp.conj(fft(Kernelex_A)) * dE SE_A = ifft(ftSE1_A + ftSE2_A) / sp.pi SE_A = sp.concatenate([SE_A[3 * Nhalf + 4:], SE_A[:Nhalf + 1]]) return SE_A
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 SusceptibilityHF(U,GF_A,X_A): ''' susceptibility calculated from the full spectral self-energy derivative ''' Int1_A = FD_A*sp.imag(GF_A**2*(1.0-U*X_A)) Int2_A = FD_A*sp.imag(GF_A**2*X_A) I1 = simps(Int1_A,En_A)/sp.pi I2 = simps(Int2_A,En_A)/sp.pi return 2.0*I1/(1.0+U**2*I2)
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 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 draw(): global t_counter global point_counter background(255) translate((width/2) - SCALE*scipy.real(lines[0][1]), (height/2) - SCALE*scipy.imag(lines[0][1])) scale(SCALE, SCALE) stroke(165, 0, 0) for x1, y1 in points: point(x1, y1) stroke(0, 0, 0) x = 0 y = 0 for num, l in enumerate(lines): part = l[1]*scipy.exp(l[0]*2*scipy.pi*1j*t_counter) if mouse_toggle: line((x, y), (x + scipy.real(part), y + scipy.imag(part))) circle((x, y), dist((x, y), (x + scipy.real(part), y + scipy.imag(part))), mode='RADIUS') x, y = (x + scipy.real(part), y + scipy.imag(part)) if num == len(lines)-1 and point_counter < 1: points.append((x, y)) t_counter += SPEED point_counter += SPEED if t_counter >= 1: t_counter = 0
def Ht_real(z,t): if(abs(scipy.imag(z))>0 or abs(scipy.imag(t))>0): print ("complex values not allowed for this function") return "error" z,t = scipy.real(z),scipy.real(t) #return quad(Ht_real_integrand, 0, np.inf, args=(z,t)) #causing overflow errors so np.inf replaced with 10 return quad(Ht_real_integrand, 0, 10, args=(z,t))
def SelfEnergyD(Gup_A, Gdn_A, Lambda, spin): ''' dynamic self-energy, uses Kramers-Kronig relations to calculate the real part ''' if spin == 'up': BubbleD_A = BubbleD(Gup_A, Gdn_A, Lambda, spin) GF_A = sp.copy(Gdn_A) Det_A = DeterminantGD(Lambda, Gup_A, Gdn_A) else: ## spin='dn' BubbleD_A = BubbleD(Gdn_A, Gup_A, Lambda, spin) GF_A = sp.copy(Gup_A) Det_A = sp.flipud(sp.conj(DeterminantGD(Lambda, Gup_A, Gdn_A))) Kernel_A = U * BubbleD_A / Det_A ## zero-padding the arrays FDex_A = sp.concatenate([FD_A[Nhalf:], sp.zeros(2 * N + 3), FD_A[:Nhalf]]) BEex_A = sp.concatenate([BE_A[Nhalf:], sp.zeros(2 * N + 3), BE_A[:Nhalf]]) ImGF_A = sp.concatenate([ sp.imag(GF_A[Nhalf:]), sp.zeros(2 * Nhalf + 3), sp.imag(GF_A[:Nhalf]) ]) ImKernel_A = sp.concatenate([ sp.imag(Kernel_A[Nhalf:]), sp.zeros(2 * Nhalf + 3), sp.imag(Kernel_A[:Nhalf]) ]) ## performing the convolution ftImSE1_A = -sp.conj(fft(BEex_A * ImKernel_A)) * fft(ImGF_A) * dE ftImSE2_A = -fft(FDex_A * ImGF_A) * sp.conj(fft(ImKernel_A)) * dE ImSE_A = sp.real(ifft(ftImSE1_A + ftImSE2_A)) / sp.pi ImSE_A = sp.concatenate([ImSE_A[3 * Nhalf + 4:], ImSE_A[:Nhalf + 1]]) Sigma_A = KramersKronigFFT(ImSE_A) + 1.0j * ImSE_A return Sigma_A
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 solve_P(F,G,H): """This function takes arguments for F,G,H and solves the matrix quadratic given by F*P^2+G*P+H=0. Note F, G, and H must be square. The function returns the matrix P and the resulting matrix, given by F*P^2+G*P+H which should be close to zero. The algorithm used to solve for P is outlined in 'A Toolkit for Analyzing Nonlinear Dynamic Stochastic Models Easily' by Harald Uhlig. """ m=sp.shape(F)[0] Xi=sp.concatenate((-G,-H), axis=1) second=sp.concatenate((sp.eye(m,m),sp.zeros((m,m))),axis=1) Xi=sp.concatenate((Xi,second)) Delta=sp.concatenate((F,sp.zeros((m,m))),axis=1) second=sp.concatenate((sp.zeros((m,m)),sp.eye(m,m)),axis=1) Delta=sp.concatenate((Delta,second)) (L,V) = la.eig(Xi,Delta) boolean = sp.zeros(len(L)) trueCount =0 for i in range(len(L)): if L[i]<1 and L[i]>-1 and sp.imag(L[i])==0 and trueCount<m: boolean[i] = True trueCount+=1 #display(L, boolean) if trueCount<m: print "Imaginary eigenvalues being used" for i in range(len(L)): if math.sqrt(real(L[i])**2+imag(L[i])**2)<1 and trueCount<m: boolean[i]=True trueCount+=1 #display(boolean) if trueCount==m: print "true count is m" Omega=sp.zeros((m,m)) diagonal=[] count =0 for i in range(len(L)): if boolean[i]==1: Omega[:,count]=sp.real(V[m:2*m,i])+sp.imag(V[m:2*m,i]) diagonal.append(L[i]) count+=1 Lambda=sp.diag(diagonal) try: P=sp.dot(sp.dot(Omega,Lambda),la.inv(Omega)) except: print 'Omega not invertable' P=sp.zeros((m,m)) diff=sp.dot(F,sp.dot(P,P))+sp.dot(G,P)+H return P,diff else: print "Problem with input, not enough 'good' eigenvalues" return sp.zeros((m,m)),sp.ones((m,m))*100
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 make_fisher_mx(bl, vis_err, deriv_stepsize, beamfwhm, param_vec, brute_force=True, flux_norm=True): # param_vec = [norm,l0,m0,fwhm_1,fwhm_2,axis_angle,beamfwhm] nb = (bl['u']).size nparam = param_vec.size # for single Gaussian = 6 free params... #nparam=6 fish_mx = sp.zeros((nparam, nparam), dtype=sp.float128) for i in range(nparam): v1plus = sp.copy(param_vec) v1minus = sp.copy(param_vec) v1plus[i] += deriv_stepsize[i] v1minus[i] -= deriv_stepsize[i] delta_1 = 2.0 * deriv_stepsize[i] #print v1plus-v1minus #print delta_1 for j in range(i, nparam): v2plus = sp.copy(param_vec) v2minus = sp.copy(param_vec) v2plus[j] += deriv_stepsize[j] v2minus[j] -= deriv_stepsize[j] delta_2 = 2.0 * deriv_stepsize[j] #print v2plus-v2minus #print delta_2 this_sum = 0.0 #print i,j for k in range(nb): u = (bl['u'])[k] v = (bl['v'])[k] first_term = (visval( beamfwhm, u, v, v1plus[0], v1plus[1], v1plus[2], v1plus[3], v1plus[4], v1plus[5], brute_force, flux_norm) - visval( beamfwhm, u, v, v1minus[0], v1minus[1], v1minus[2], v1minus[3], v1minus[4], v1minus[5], brute_force, flux_norm)) / delta_1 second_term = (visval( beamfwhm, u, v, v2plus[0], v2plus[1], v2plus[2], v2plus[3], v2plus[4], v2plus[5], brute_force, flux_norm) - visval( beamfwhm, u, v, v2minus[0], v2minus[1], v2minus[2], v2minus[3], v2minus[4], v2minus[5], brute_force, flux_norm)) / delta_2 this_sum += sp.real(first_term) * sp.real(second_term) this_sum += sp.imag(first_term) * sp.imag(second_term) #print " ",k,u,v,first_term,second_term,delta_1,delta_2 fish_mx[i, j] = this_sum / vis_err**2 fish_mx[j, i] = fish_mx[i, j] # looks like the second_term is giving some NaNs in the off-diagonals... # i think the trouble is my stepsize is fractional and some of the parameter values are zero. return fish_mx
def WriteMatrix(X_D,bands_T,Xtype,logfname): ''' writes a dict or matrix with two indices to output in a matrix form input: Xtype = "D" = dict, "M" = matrix ''' out_text = '' NBand = len(bands_T) for i in range(NBand): for j in range(NBand): X = X_D[bands_T[i],bands_T[j]] if Xtype == 'D' else X_D[i][j] if sp.imag(X) == 0: out_text += '{0: .6f}\t'.format(float(sp.real(X))) else: out_text += '{0: .6f}{1:+0.6f}i\t'.format(float(sp.real(X)),float(sp.imag(X))) out_text += '\n' if logfname != '': PrintAndWrite(out_text,logfname) else: print out_text
def SelfEnergy(GF_A,ChiGamma_A): ''' calculating the dynamical self-energy from the Schwinger-Dyson equation ''' N = int((len(En_A)-1)/2) ## zero-padding the arrays exFD_A = sp.concatenate([FD_A[N:],sp.zeros(2*N+3),FD_A[:N]]) exBE_A = sp.concatenate([BE_A[N:],sp.zeros(2*N+3),BE_A[:N]]) exGF_A = sp.concatenate([GF_A[N:],sp.zeros(2*N+3),GF_A[:N]]) exCG_A = sp.concatenate([ChiGamma_A[N:],sp.zeros(2*N+3),ChiGamma_A[:N]]) ## performing the convolution ftSE1_A = -sp.conj(fft(exBE_A*sp.imag(exCG_A)))*fft(exGF_A)*dE ftSE2_A = fft(exFD_A*sp.imag(exGF_A))*sp.conj(fft(exCG_A))*dE SE_A = ifft(ftSE1_A+ftSE2_A)/sp.pi Sigma_A = sp.concatenate([SE_A[3*N+4:],SE_A[:N+1]]) return Sigma_A
def LambdaVertexD(Gup_A, Gdn_A, Lambda): ''' calculates the Lambda vertex for given i ''' global GG1_A, GG2_A, Det_A Det_A = DeterminantGD(Lambda, Gup_A, Gdn_A) K = KvertexD(Lambda, Gup_A, Gdn_A) # GFn_A = 0.5*(Gup_A-sp.flipud(sp.conj(Gup_A))) # XD = ReBDDFDD(GFn_A,GFn_A,0) XD = ReBDDFDD(Gup_A, Gdn_A, 0) Lambda = U / (1.0 + K * XD) print('# Lambda: {0: .8f} {1:+8f}i'.format(float(sp.real(Lambda)), float(sp.imag(Lambda)))) print('# X: {0: .8f}'.format(XD)) print('# K: {0: .8f} {1:+8f}i'.format(float(sp.real(K)), float(sp.imag(K)))) return Lambda
def SelfEnergy(GF_A,ChiGamma_A): ''' calculating the dynamical self-energy from the Schwinger-Dyson equation ''' N = int((len(En_A)-1)/2) ## zero-padding the arrays exFD_A = sp.concatenate([FD_A[N:],sp.zeros(2*N+3),FD_A[:N]]) exBE_A = sp.concatenate([BE_A[N:],sp.zeros(2*N+3),BE_A[:N]]) ImGF_A = sp.concatenate([sp.imag(GF_A[N:]),sp.zeros(2*N+3),sp.imag(GF_A[:N])]) ImCG_A = sp.concatenate([sp.imag(ChiGamma_A[N:]),sp.zeros(2*N+3),sp.imag(ChiGamma_A[:N])]) ## performing the convolution ftImSE1_A = -sp.conj(fft(exBE_A*ImCG_A))*fft(ImGF_A)*dE ftImSE2_A = -fft(exFD_A*ImGF_A)*sp.conj(fft(ImCG_A))*dE ImSE_A = sp.real(ifft(ftImSE1_A+ftImSE2_A))/sp.pi ImSE_A = sp.concatenate([ImSE_A[3*N+4:],ImSE_A[:N+1]]) Sigma_A = KramersKronigFFT(ImSE_A) + 1.0j*ImSE_A return Sigma_A
def Ht_real_integrand(u, z, t): """ Add docstring :param u: :param z: :param t: :return: """ if abs(scipy.imag(z)) > 0 or abs(scipy.imag(t)) > 0 \ or abs(scipy.imag(u)) > 0: print("complex values not allowed for this function") return "error" u, z, t = scipy.real(u), scipy.real(z), scipy.real(t) return scipy.real(exp(t * u * u) * phi_decay(u) * cos(z * u))
def process(self, X, V, C): """Tolerance for eigenvalues a possible problem when checking for neutral saddles.""" BifPoint.process(self, X, V, C) J_coords = C.CorrFunc.jac(X, C.coords) eigs, LV, RV = linalg.eig(J_coords,left=1,right=1) # Check for neutral saddles found = False for i in range(len(eigs)): if abs(imag(eigs[i])) < 1e-5: for j in range(i+1,len(eigs)): if C.verbosity >= 2: if abs(eigs[i]) < 1e-5 and abs(eigs[j]) < 1e-5: print 'Fold-Fold point found in Hopf!\n' elif abs(imag(eigs[j])) < 1e-5 and abs(real(eigs[i]) + real(eigs[j])) < 1e-5: print 'Neutral saddle found!\n' elif abs(real(eigs[i])) < 1e-5: for j in range(i+1, len(eigs)): if abs(real(eigs[j])) < 1e-5 and abs(real(eigs[i]) - real(eigs[j])) < 1e-5: found = True w = abs(imag(eigs[i])) if imag(eigs[i]) > 0: p = conjugate(LV[:,j])/linalg.norm(LV[:,j]) q = RV[:,i]/linalg.norm(RV[:,i]) else: p = conjugate(LV[:,i])/linalg.norm(LV[:,i]) q = RV[:,j]/linalg.norm(RV[:,j]) if not found: del self.found[-1] return False direc = conjugate(1/matrixmultiply(conjugate(p),q)) p = direc*p # Alternate way to compute 1st lyapunov coefficient (from Kuznetsov [4]) #print (1./(w*w))*real(1j*matrixmultiply(conjugate(p),b1)*matrixmultiply(conjugate(p),b3) + \ # w*matrixmultiply(conjugate(p),trilinearform(D,q,q,conjugate(q)))) self.found[-1].w = w self.found[-1].l1 = firstlyapunov(X, C.CorrFunc, w, J_coords=J_coords, p=p, q=q, check=(C.verbosity==2)) self.found[-1].eigs = eigs self.info(C, -1) return True
def polarization(wf, d_phi=1.0e-10): """ Polarization from Resta formula. """ L = states.shape[0] X = diag(exp(-1.0j*linspace(0,2*pi,L))) return -imag(log(det(conj(states.T) @ X @ states)))
def ambiguity_function(waveform, N): """ Function to calculate the ambiguity function of a waveform with a specified doppler width N, as well as units scaled down by const_1 and const_2. :param waveform: the waveform in question :type waveform: Waveform object :param N: the doppler width of our ambiguity function :type N: int :return: the ambiguity function of waveform. """ lst = [] const_1 = 3 const_2 = 3 bound_1 = const_1 * waveform.length # range of delays for delay in range(-bound_1, bound_1 + 1): row = [] bound_2 = N * const_2 # range of frequencies for freq in range(-bound_2, bound_2 + 1): fn = delay_fn(waveform.function, delay / const_1, freq / const_2) # note that we have to integrate the real and imaginary parts separately, due to scipy's constraints real_val = integrate.quad(lambda x: scipy.real(fn(x)), -float('inf'), float('inf')) imag_val = integrate.quad(lambda x: scipy.imag(fn(x)), -float('inf'), float('inf')) row.append(abs(real_val[0] + 1j * imag_val[0])) lst.append(row) return lst
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 = scipy.zeros(newshape, dtype=float) 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 = scipy.fft(xtilde,axis=axis) return (-scipy.imag(Xt)/2)[slices[0]]
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 imag_eq2X1(x, theta, z, y, phi): L = x * math.sin(theta) * math.cos(phi) + y * math.sin(theta) * math.sin( phi) + z * math.cos(theta) #return sp.real(-1.0*math.sin(theta)*math.sin(k*(z + length/2.0))*cmath.exp(j*z*k*math.cos(theta))) return sp.imag( math.cos(theta) * math.cos(phi) * math.cos(k * (x - length / 4.0)) * cmath.exp(j * k * L))
def SelfEnergyKK(GF_A,ChiGamma_A): ''' calculating the dynamical self-energy from the Schwinger-Dyson equation uses KramersKronigFFT to calculate the real part ''' N = int((len(En_A)-1)/2) ## zero-padding the arrays exFD_A = sp.concatenate([FD_A[N:],sp.zeros(2*N+3),FD_A[:N]]) exBE_A = sp.concatenate([BE_A[N:],sp.zeros(2*N+3),BE_A[:N]]) ImGF_A = sp.concatenate([sp.imag(GF_A[N:]),sp.zeros(2*N+3),sp.imag(GF_A[:N])]) ImCG_A = sp.concatenate([sp.imag(ChiGamma_A[N:]),sp.zeros(2*N+3),sp.imag(ChiGamma_A[:N])]) ## performing the convolution ftImSE1_A = -sp.conj(fft(exBE_A*ImCG_A))*fft(ImGF_A)*dE ftImSE2_A = -fft(exFD_A*ImGF_A)*sp.conj(fft(ImCG_A))*dE ImSE_A = sp.real(ifft(ftImSE1_A+ftImSE2_A))/sp.pi ImSE_A = sp.concatenate([ImSE_A[3*N+4:],ImSE_A[:N+1]]) Sigma_A = KramersKronigFFT(ImSE_A) + 1.0j*ImSE_A return Sigma_A
def complex_quadrature(paths, a, **kwargs): real_ = scipy.real(paths) imag_ = scipy.imag(paths) real_integral = simps(real_, a) imag_integral = simps(imag_, a) return real_integral + 1j*imag_integral
def BodefromTwoTimeDomainVectors(timevector,output,input,truncfreq=100): """This function calculates the Bode response between two time domain signals. The timevector is used to calculate the frequency vector, which is then used to truncate the Bode response to reduce calculation time and return only useful information. Input and output are time domain vectors. The return values are freq, magnitude ratio, phase, complex The goal of this function is to be useful for small amounts of data and/or as part of a routine to calculate a Bode response from fixed sine data.""" N=len(timevector) f=makefreqvect(timevector) co=thresh_py(f,truncfreq) f=f[0:co] curin_fft=fft(input,None,0)*2/N curout_fft=fft(output,None,0)*2/N curin_fft=curin_fft[0:co] curout_fft=curout_fft[0:co] curGxx=norm2(curin_fft) curGyy=norm2(curout_fft) curGxy=scipy.multiply(scipy.conj(curin_fft),curout_fft) H=scipy.divide(curGxy,curGxx) Hmag=abs(H) Hphase=mat_atan2(scipy.imag(H),scipy.real(H))*180.0/pi return f,Hmag,Hphase,H
def write(self, vals, name, label='Mie'): with open(name, 'w') as fp: N = len(self.elems) fp.write("View \"{0}\" {{\n".format(label)) for ii, elem in enumerate(self.elems): fp.write('ST( ') for jj, n in enumerate(elem): x, y, z = self.points[n - 1] fp.write('{0}, {1}, {2}'.format(x, y, z)) if jj == len(elem) - 1: fp.write(')') else: fp.write(', ') fp.write('{') for jj, n in enumerate(elem): rv = sp.real(vals[n - 1]) fp.write('{0}, '.format(rv)) for jj, n in enumerate(elem): iv = sp.imag(vals[n - 1]) fp.write('{0}'.format(iv)) if jj == len(elem) - 1: fp.write('};\n') else: fp.write(', ') self._print_progress(ii, N, 'written') fp.write("TIME{0, 1};\n};\n\n") print(' --> {0} written.'.format(name))
def _get_Voronoi_edges(vor): r""" Given a Voronoi object as produced by the scipy.spatial.Voronoi class, this function calculates the start and end points of eeach edge in the Voronoi diagram, in terms of the vertex indices used by the received Voronoi object. Parameters ---------- vor : scipy.spatial.Voronoi object Returns ------- A 2-by-N array of vertex indices, indicating the start and end points of each vertex in the Voronoi diagram. These vertex indices can be used to index straight into the ``vor.vertices`` array to get spatial positions. """ edges = [[], []] for facet in vor.ridge_vertices: # Create a closed cycle of vertices that define the facet edges[0].extend(facet[:-1]+[facet[-1]]) edges[1].extend(facet[1:]+[facet[0]]) edges = sp.vstack(edges).T # Convert to scipy-friendly format mask = sp.any(edges == -1, axis=1) # Identify edges at infinity edges = edges[~mask] # Remove edges at infinity edges = sp.sort(edges, axis=1) # Move all points to upper triangle # Remove duplicate pairs edges = edges[:, 0] + 1j*edges[:, 1] # Convert to imaginary edges = sp.unique(edges) # Remove duplicates edges = sp.vstack((sp.real(edges), sp.imag(edges))).T # Back to real edges = sp.array(edges, dtype=int) return edges
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 = scipy.zeros(newshape, dtype=float) 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 = scipy.fft(xtilde, axis=axis) return (-scipy.imag(Xt) / 2)[slices[0]]
def hamiltonian_element(coefficients_i, coefficients_j, potential_energy, c): '''This function computes the i,jth element of the Hamiltonian matrix. It does so by numerically integrating the product of the complex conjugate of the ith basis function and the hamiltonian operating on the jth basis function. Input coefficients_i: list of complex floats (the basis set coefficients of vector i in the standard basis set [1,x,x^2,x^3,etc.]) coefficients_j: list of complex floats (the basis set coefficients of vector j in the standard basis set) potential_energy: float (the potential energy constant) c: float (the constant involved in the Hamiltonian operator) Output matrix_element: float (the value of the above numerical integral)''' import scipy.integrate as integrate hamiltonian_on_phi_j = hamiltonian( coefficients_j, potential_energy, c) #operating hamiltonian on function j, returns in legendre basis set def value(x): #creating a fx to pass to scipy.integrate.quad phi_i = np.conjugate( coeffs_to_fx(coefficients_i, x, coeff_type='standard')) phi_j = coeffs_to_fx(hamiltonian_on_phi_j, x, coeff_type='legendre') return phi_i * phi_j matrix_element_real, error_real = integrate.quad( lambda x: scipy.real(value(x)), -1, 1) matrix_element_imaginary, error_imaginary = integrate.quad( lambda x: scipy.imag(value(x)), -1, 1) matrix_element = matrix_element_real + matrix_element_imaginary * 1j return matrix_element
def __mul__(self, other): if type(other ) == State and self.qtype == 'bra' and other.qtype == 'ket': if self.symbolic: limits = [(v, -oo, oo) for v in self.vars] current = conjugate(self.expr.copy()) * other.expr.copy() for limit in limits: current = integrate(current, limit) return current else: expr = conjugate(self.expr.copy()) * other.expr.copy() lamb = lambdify(self.vars, expr) return sc.integrate.nquad(lambda *args: sc.real(lamb(*args)),\ [[-sc.inf, sc.inf] for v in self.vars],\ opts={"epsabs": 1.49 * 10**(-4),\ "epsrel": 1.49 * 10**(-4),\ "maxp1": 4})[0]\ + 1j*sc.integrate.nquad(lambda *args: sc.imag(lamb(*args)),\ [[-sc.inf, sc.inf] for v in self.vars],\ opts={"epsabs": 1.49 * 10**(-4),\ "epsrel": 1.49 * 10**(-4),\ "maxp1": 4})[0] elif type(other) == Operator and self.qtype == 'bra': return (other * self.dag()).dag() else: return State(self.vars,\ expr=other*self.expr.copy(),\ qtype=self.qtype)
def write(self, vals, name, label='Mie'): with open(name, 'w') as fp: N = len(self.elems) fp.write("View \"{0}\" {{\n".format(label)) for ii, elem in enumerate(self.elems): fp.write('ST( ') for jj, n in enumerate(elem): x, y, z = self.points[n-1] fp.write('{0}, {1}, {2}'.format(x, y, z)) if jj == len(elem)-1: fp.write(')') else: fp.write(', ') fp.write('{') for jj, n in enumerate(elem): rv = sp.real(vals[n-1]) fp.write('{0}, '.format(rv)) for jj, n in enumerate(elem): iv = sp.imag(vals[n-1]) fp.write('{0}'.format(iv)) if jj == len(elem)-1: fp.write('};\n') else: fp.write(', ') self._print_progress(ii, N, 'written') fp.write("TIME{0, 1};\n};\n\n") print(' --> {0} written.'.format(name))
def PHIimag_eq2Y2(y, theta, x, z, phi): L = x * math.sin(theta) * math.cos(phi) + y * math.sin(theta) * math.sin( phi) + z * math.cos(theta) #return sp.real(-1.0*math.sin(theta)*math.sin(k*(z + length/2.0))*cmath.exp(j*z*k*math.cos(theta))) return sp.imag( math.cos(phi) * math.cos(k * (length / 2.0 - y)) * cmath.exp(j * k * L))
def JosephsonCurrent(G,params_F,W,NMats,direction,gtype): ''' Josephson current calculated from the Nambu Green function ''' [beta,U,Delta,GammaL,GammaR,GammaN,eps,P,B] = params_F Phi = P*sp.pi ## select direction, in theory JC_R = -JC_L Gamma = GammaR if direction == 'R' else -GammaL Phi_s = Phi/2.0 if direction == 'R' else -Phi/2.0 Hyb = lambda x: Gamma*IntFiniteBW(Delta,W,x) ## define empty GFs J = GfImFreq(indices = ['up','dn'],beta = beta,n_points = NMats) H = GfImFreq(indices = ['up','dn'],beta = beta,n_points = NMats) G_iw = GfImFreq(indices = ['up','dn'],beta = beta,n_points = NMats) ## calculate the Matsubara function from input if gtype == 'leg': G_iw.set_from_legendre(G) elif gtype == 'tau': G_iw.set_from_fourier(G) else: G_iw = G.copy() ## define lambdas and fill the hybridizations H11 = lambda x: x*Hyb(x) H12 = lambda x: Delta*sp.exp( 1.0j*Phi_s)*Hyb(x) H21 = lambda x: -Delta*sp.exp(-1.0j*Phi_s)*Hyb(x) H22 = lambda x: -x*Hyb(x) H['up','up'] << Function(H11) H['up','dn'] << Function(H12) H['dn','up'] << Function(H21) H['dn','dn'] << Function(H22) ## fill the GF i<c{dag}d-d{dag}c> for band1,band2 in product(['up','dn'], repeat=2): J[band1,band2] << H[band1,band2]*G_iw[band1,band2] J.tail.zero() ## tail is small and hard to fit JC = 2.0*sp.imag(J['up','dn'].density()[0][0]+J['dn','up'].density()[0][0]) return JC
def plot(nmin=-2, nmax=1, tmin=0, tmax=2, num=301, B=5.4, npar=1.8): Taxis = scipy.logspace(tmin, tmax, num) * 1e-3 naxis = scipy.logspace(nmin, nmax, num) * 1e20 n, T = scipy.meshgrid(naxis, Taxis) om = scipy.pi * 2 * 4.6e9 #wpe = n*pow(ec,2)/(e0*mes) print(nu(n, T)) Ains = As(n, T, B, om, npar) Bins = Bs(n, T, B, om, npar) Cins = Cs(n, T, B, om, npar) Q = (-Bins + scipy.sqrt(pow(Bins, 2) - 4 * Ains * Cins)) / 2 / Ains output = scipy.sqrt( scipy.sqrt(pow(scipy.real(Q), 2) + pow(scipy.imag(Q), 2)) - scipy.real(Q)) / pow(2, .5) CS = plt.contour(naxis, Taxis * 1e3, om * output / 299792458., locator=ticker.LogLocator(), linewidths=2., colors=colors['b']) #om*output/299792458. plt.clabel(CS, inline=1, fontsize=16, fmt=ticker.LogFormatterMathtext()) # #CS2 = plt.contour(naxis,Taxis*1e3,pow(2,-1)*abs(scipy.imag(Q)/abs(scipy.sqrt(scipy.real(Q))))*om/299792458.,locator=ticker.LogLocator(),linewidths=2.,colors=colors['g'])#om*output/299792458. #plt.clabel(CS2, inline=1, fontsize=16,fmt=ticker.LogFormatterMathtext())# wpe = n * pow(ec, 2) / (e0 * mes) wce = ec * B / mes wci = ec * B / mi output2 = nu(n, T) * pow(wpe, .5) / (2 * pow(om, 2)) * scipy.sqrt( abs((npar**2 - 1) / (1 - wpe / (pow(wce, 2) * (npar**2 - 1))))) #CS3 = plt.contour(naxis,Taxis*1e3,output2*om/299792458.,locator=ticker.LogLocator(),linewidths=2.,colors=colors['r'])#om*output/299792458. output3 = nu(n, T) * pow(wpe, .5) / (2 * pow(om, 2)) * npar # CS2 = plt.contour(naxis,Taxis*1e3,output3*om/299792458.,locator=ticker.LogLocator(),linewidths=2.,colors=colors['g'])#om*output/299792458. #plt.clabel(CS2, inline=1, fontsize=16,fmt=ticker.LogFormatterMathtext())# #plt.clabel(CS3, inline=1, fontsize=16,fmt=ticker.LogFormatterMathtext())# A2 = pow(ec, 2) / (e0 * mi) / pow(om, 2) B2 = -2 * pow(e0 * mes, -.5) * ec / wce * npar C2 = npar**2 - 1 temp = pow((-B2 - pow(B2**2 - 4 * A2 * C2, .5)) / (2 * A2), 2) plt.fill_between(naxis, Taxis[0] * 1e3, Taxis[-1] * 1e3, naxis > temp, color='k', alpha=.3, linewidth=2.) plt.gca().set_yscale("log") plt.gca().set_xscale("log") plt.ylabel(r'Electron Temperature [eV]') plt.xlabel(r'$n_e$ [m$^{-3}$]') plt.show()
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 orthonormalize_pair(self, vec): d1 = self.complex_precision(0.0 + 0.0j) d2 = self.complex_precision(0.0 + 0.0j) z = self.complex_precision(0.0 + 0.0j) nh = int(self.ndim / 2) sp.savetxt( "t_vec_op_i" + str(self.iev) + "_c" + str(self.cycle) + ".txt", vec) for ii in range(nh): z = z + vec[ii] * vec[ii + nh] # z = sp.dot(vec[:int(self.ndim/2)], vec[int(self.ndim/2):]) d = self.real_precision(z * np.conj(z)) r = self.real_precision(1.0) - self.real_precision(4.0) * d print("determining t_vec coefficients") print("z = ", z) print("d = ", d) print("r = ", r) if r >= 1e-12: if np.abs(d) > 1e-12: t = self.real_precision(1.0) + sp.sqrt(r) print("t = ", t) print("sp.sqrt(d) = ", sp.sqrt(d)) print("sp.real(z) = ", sp.real(z)) print("sp.imag(z) = ", sp.imag(z)) r1 = sp.real(z) / sp.sqrt(d) r2 = sp.imag(z) / sp.sqrt(d) print("r1 = ", r1) print("r2 = ", r2) d1 = self.complex_precision( -r1 * sp.sqrt(self.real_precision(0.5) * t / r) + r2 * sp.sqrt(self.real_precision(0.5) * t / r) * 1.0j) d2 = self.complex_precision( sp.sqrt(self.real_precision(2.0) * d / (t * r)) + 0.0j) else: print("WARNING!, small d in orthonormalize pair routine") d1 = self.complex_precision(1.0 + 0.0j) d2 = self.complex_precision(0.0 + 0.0j) else: print("WARNING!, small r in orthonormalize pair routine") print("d1, d2 = ", d1, d2) return d1, d2
def plot_pole(state): """ Plots the momentum pole of a state in the complex plane. """ mass = state.problem.mass energy = state.energy k = sp.sqrt(2 * mass * energy) return plt.plot(sp.real(k), sp.imag(k), "o", color="red")
def complex_quadrature(func, a, b, **kwargs): realFunc = lambda x: scipy.real(func(x)) imagFunc = lambda x: scipy.imag(func(x)) real_integral = integrate.quad(realFunc, a, b, **kwargs) imag_integral = integrate.quad(imagFunc, a, b, **kwargs) return (real_integral[0] + 1j * imag_integral[0], real_integral[1:], imag_integral[1:])
def CalculateHWHM(GF_A): ''' calculates the half-width at half-maximum of the Kondo resonance and the maximum of the spectral function ''' N = len(En_A) IntMin = int((N+1)/2-int(0.5/dE)) IntMax = int((N+1)/2+int(0.5/dE)) DOSmaxPos = sp.argmax(-sp.imag(GF_A[IntMin:IntMax])/sp.pi) DOSmax = -sp.imag(GF_A[IntMin+DOSmaxPos])/sp.pi # maximum of DoS wmax = En_A[IntMin+DOSmaxPos] # position of the maximum at energy axis DOS = InterpolatedUnivariateSpline(En_A-1e-12,-sp.imag(GF_A)/sp.pi-DOSmax/2.0) ## 1e-12 breaks symmetry for half-filling, otherway DOS.roots() loses one solution. DOSroots_A = sp.sort(sp.fabs(DOS.roots())) try: HWHM = (DOSroots_A[0] + DOSroots_A[1])/2.0 except IndexError: HWHM = 0.0 return [HWHM,DOSmax,wmax]
def TwoParticleBubble(F1_A,F2_A,channel): ''' calculates the two-particle bubble, channel = 'eh', 'ee' ''' N = int((len(En_A)-1)/2) ## zero-padding the arrays exFD_A = sp.concatenate([FD_A[N:],sp.zeros(2*N+3),FD_A[:N]]) ImF1_A = sp.concatenate([sp.imag(F1_A[N:]),sp.zeros(2*N+3),sp.imag(F1_A[:N])]) ImF2_A = sp.concatenate([sp.imag(F2_A[N:]),sp.zeros(2*N+3),sp.imag(F2_A[:N])]) ## performing the convolution if channel == 'eh': ftImChi1_A = sp.conj(fft(exFD_A*ImF2_A))*fft(ImF1_A)*dE # f(x)F2(x)F1(w+x) ftImChi2_A = -fft(exFD_A*ImF1_A)*sp.conj(fft(ImF2_A))*dE # f(x)F1(x)F2(x-w) elif channel == 'ee': ftImChi1_A = fft(exFD_A*ImF2_A)*fft(ImF1_A)*dE # f(x)F2(x)F1(w-x) ftImChi2_A = -sp.conj(fft(exFD_A*sp.flipud(ImF1_A)))*fft(ImF2_A)*dE # f(x)F1(-x)F2(w+x) ImChi_A = -sp.real(ifft(ftImChi1_A+ftImChi2_A))/sp.pi ImChi_A = sp.concatenate([ImChi_A[3*N+4:],ImChi_A[:N+1]]) Chi_A = KramersKronigFFT(ImChi_A) + 1.0j*ImChi_A return Chi_A
def RiemannSurface2(): """riemann surface for imaginary part of sqrt(z)""" fig = plt.figure() ax = Axes3D(fig) X = sp.arange(-5, 5, 0.25) Y = sp.arange(-5, 0, 0.25) X, Y = sp.meshgrid(X, Y) Z = sp.imag(sp.sqrt(X+1j*Y)) ax.plot_surface(X, Y, Z, rstride=1, cstride=1, linewidth=0, cmap=cmap_r) ax.plot_surface(X, Y, -Z, rstride=1, cstride=1, linewidth=0, cmap=cmap) X = sp.arange(-5, 5, 0.25) Y = sp.arange(0,5,.25) X, Y = sp.meshgrid(X, Y) Z = sp.imag(sp.sqrt(X+1j*Y)) ax.plot_surface(X, Y, -Z, rstride=1, cstride=1, linewidth=0, cmap=cmap_r) ax.plot_surface(X, Y, Z, rstride=1, cstride=1, linewidth=0, cmap=cmap) plt.savefig('RiemannSurface2.pdf', bbox_inches='tight', pad_inches=0)
def upconvert(x, fc): """ Upconverts in-phase and quadrature components of a time-domain signal appropriately. Returns the in-phase and quadrature signals """ t = sp.arange(x.size) x_i = sp.real(x) * 2 * sp.cos(2*pi*fc*t / sampling_rate) x_q = sp.imag(x) * 2 * sp.sin(2*pi*fc*t / sampling_rate) return x_i, x_q
def fourier_series(dat, t, n): """ Fourier series approximation to a function. returns Fourier coefficients of a function. The coefficients are numerical approximations of the true coefficients. Parameters ---------- dat: array Array of data representing the function. t: array Corresponding time array. n: int The desired number of terms to use in the Fourier series. Returns ---------- a, b: tuple Tuple containing arrays with the Fourier coefficients. The function also produces a plot of the approximation. Examples: >>> f = sp.hstack((sp.arange(-1, 1, .04), sp.arange(1, -1, -.04))) >>> f += 1 >>> t = sp.arange(0, len(f))/len(f) >>> a, b = fourier_series(f, t, 5) >>> a[0] 2.0 """ len_ = len(dat)/2 fs = (sp.fft(dat))/len_ a0 = fs[0] a = sp.real(sp.hstack((a0, fs[1:len(fs/2)]))) b = -sp.imag(fs[1:len(fs/2)]) len_ *= 2 dt = 2*sp.pi/len_ tp = sp.arange(0, 2*sp.pi, dt) dataapprox = a[0]/2 + sp.zeros_like(dat) fig = plt.figure() ax1 = fig.add_subplot(111) ax1.plot(t, dat) for i in range(1, n): newdat = a[i]*sp.cos(tp*i) + b[i]*sp.sin(tp*i) dataapprox += newdat if i == n-1: ax1.plot(t, newdat) ax1.plot(t, dataapprox) _ = plt.show() return a, b
def sliceEpsArr(EpsArr,NX,NY,NZ,figNum): """ Visualizing object with slices """ vxyR=sci.real(EpsArr[:,:,round(NZ/2.0)]) vxzR=sci.real(EpsArr[:,round(NY/2.0),:]) vyzR=sci.real(EpsArr[round(NX/2.0),:,:]) vxyI=sci.imag(EpsArr[:,:,round(NZ/2.0)]) vxzI=sci.imag(EpsArr[:,round(NY/2.0),:]) vyzI=sci.imag(EpsArr[round(NX/2.0),:,:]) plt.ion() fig=plt.figure(figNum) fig.clear() plt.subplot(231) plt.imshow(vxyR) plt.title('real($\\varepsilon$), xy-plane') plt.colorbar() plt.subplot(232) plt.imshow(sci.swapaxes(vxzR,0,1)) plt.title('real($\\varepsilon$), xz-plane') plt.colorbar() plt.subplot(233) plt.imshow(sci.swapaxes(vyzR,0,1)) plt.title('real($\\varepsilon$), yz-plane') plt.colorbar() plt.subplot(234) plt.imshow(vxyI) plt.title('imag($\\varepsilon$), xy-plane') plt.colorbar() plt.subplot(235) plt.imshow(sci.swapaxes(vxzI,0,1)) plt.title('imag($\\varepsilon$), xz-plane') plt.colorbar() plt.subplot(236) plt.imshow(sci.swapaxes(vyzI,0,1)) plt.title('imag($\\varepsilon$), yz-plane') plt.colorbar() fig.canvas.draw() plt.ioff() return
def plotEpsArr(EpsArr,NX,NY,NZ,figNum,hold,label,clear): """ Visualizing object with cuts """ cutxR=sci.real(EpsArr[:,round(NY/2.0),round(NZ/2.0)]) cutxI=sci.imag(EpsArr[:,round(NY/2.0),round(NZ/2.0)]) cutyR=sci.real(EpsArr[round(NX/2.0),:,round(NZ/2.0)]) cutyI=sci.imag(EpsArr[round(NX/2.0),:,round(NZ/2.0)]) cutzR=sci.real(EpsArr[round(NX/2.0),round(NY/2.0),:]) cutzI=sci.imag(EpsArr[round(NX/2.0),round(NY/2.0),:]) plt.ion() fig=plt.figure(figNum) fig.clear() if clear=='yes': fig.clear() plt.hold(hold) plt.subplot(231) plt.plot(cutxR,label) plt.title('real($\\varepsilon$), x-axis cut') plt.subplot(232) plt.plot(cutyR,label) plt.title('real($\\varepsilon$), y-axis cut') plt.subplot(233) plt.plot(cutzR,label) plt.title('real($\\varepsilon$), z-axis cut') plt.subplot(234) plt.plot(cutxI,label) plt.title('imag($\\varepsilon$), x-axis cut') plt.subplot(235) plt.plot(cutyI,label) plt.title('imag($\\varepsilon$), y-axis cut') plt.subplot(236) plt.plot(cutzI,label) plt.title('imag($\\varepsilon$), z-axis cut') plt.hold('False') fig.canvas.draw() plt.ioff() return
def log_riemann_surface(): """riemann surface for imaginary part of ln(z)""" fig = plt.figure() ax = Axes3D(fig) X = sp.arange(-5, 5, 0.25) Y = sp.arange(-5, 0, 0.25) X, Y = sp.meshgrid(X, Y) Z = sp.imag(sp.log(X+1j*Y)) ax.plot_surface(X, Y, Z, rstride=1, cstride=1, linewidth=0, cmap=cmap_r) ax.plot_surface(X,Y,Z+2*sp.pi, rstride=1, cstride=1,linewidth=0, cmap=cmap_r) ax.plot_surface(X,Y,Z-2*sp.pi, rstride=1, cstride=1,linewidth=0, cmap=cmap_r) X = sp.arange(-5, 5, 0.25) Y = sp.arange(0,5,.25) X, Y = sp.meshgrid(X, Y) Z = sp.imag(sp.log(X+1j*Y)) ax.plot_surface(X, Y, Z, rstride=1, cstride=1, linewidth=0, cmap=cmap) ax.plot_surface(X,Y,Z+2*sp.pi, rstride=1, cstride=1,linewidth=0, cmap=cmap) ax.plot_surface(X,Y,Z-2*sp.pi, rstride=1, cstride=1,linewidth=0, cmap=cmap) plt.savefig('log_riemann_surface.pdf', bbox_inches='tight', pad_inches=0)
def fft(xaxis, real, img, dwell, numPts): #check numPts is to a power of 2 if not float(sp.log2(numPts)).is_integer(): print 'Number of points is not a power of 2.' return fftReal = fp.fft(real) fftImg = fp.fft(img) #reorganize fourier transform properly #1-4 new real #2+3 new img fftR = sp.real(fftReal[:]) - sp.imag(fftImg[:]) fftR = fp.fftshift(fftR) fftI = sp.imag(fftReal[:]) + sp.real(fftImg[:]) fftI = fp.fftshift(fftI) #convert axis time to freq freq = timeToFreq(xaxis, dwell, numPts) return [freq, fftR, fftI]
def ComplexNumToStr(val, eps=1e-12, fmt='%0.4g', polar=False, \ debug=0, strip_sympy=True): #Note that this also becomes the default class for all elements of #arrays, so the possibility of those elements being sympy #expressions or something exists. if debug: print('In ComplexNumToStr, val='+str(val)) print('type(val)=%s' % type(val)) test = is_sage(val) print('is_sage test = '+str(test)) if hasattr(val,'ToLatex'): return val.ToLatex(eps=eps, fmt=fmt) elif is_sympy(val) or is_sage(val): sympy_out = sympy.latex(val, profile=sympy_profile) if strip_sympy: bad_list = ['\\begin{equation*}', \ '\\end{equation*}', \ '\\begin{equation}', \ '\\end{equation}', \ '$'] for item in bad_list: sympy_out = sympy_out.replace(item,'') if debug: print('sympy_out='+sympy_out) return sympy_out val = AbsEpsilonCheck(val)#this zeros out any vals that have very small absolute values test = bool(isinstance(val, complex)) #print('test = '+str(test)) if isinstance(val, complex): realstr = '' imagstr = '' rpart = real(val) ipart = imag(val) if abs(ipart) < eps: return fmt % rpart elif abs(rpart) < eps: return fmt%ipart+'j' else: realstr = fmt % rpart imagstr = fmt % ipart+'j' if ipart > 0: rectstr = realstr+'+'+imagstr else: rectstr = realstr+imagstr outstr = rectstr if polar: polarstr = fmt%abs(val) + ' \\angle '+fmt%angle(val,1)+'^\\circ' outstr += ' \\; \\textrm{or} \\; ' +polarstr return outstr else: return fmt % val
def damp(A): # Original Author: Kai P. Mueller <*****@*****.**> for Octave # Created: September 29, 1997. print("............... Eigenvalue ........... Damping Frequency") print("--------[re]---------[im]--------[abs]----------------------[Hz]") e, _ = la.eig(A) for i in range(len(e)): pole = e[i] d0 = -sp.cos(math.atan2(sp.imag(pole), sp.real(pole))) f0 = 0.5 / sp.pi * abs(pole) if (abs(sp.imag(pole)) < abs(sp.real(pole))): print(' {:.3f} {:.3f} {:.3f} {:.3f}'. format(float(sp.real(pole)), float(abs(pole)), float(d0), float(f0))) else: print(' {:.3f} {:+.3f} {:.3f} {:.3f} {:.3f}'. format(float(sp.real(pole)), float(sp.imag(pole)), float(abs(pole)), float(d0), float(f0)))
def _RLZoomDispatcher(event, sys, ax_rlocus, plotstr): """Rootlocus plot zoom dispatcher""" nump, denp = _systopoly1d(sys) xlim, ylim = ax_rlocus.get_xlim(), ax_rlocus.get_ylim() kvect, mymat, xlim, ylim = _default_gains( nump, denp, xlim=None, ylim=None, zoom_xlim=xlim, zoom_ylim=ylim) _removeLine('rootlocus', ax_rlocus) for i, col in enumerate(mymat.T): ax_rlocus.plot(real(col), imag(col), plotstr, label='rootlocus', scalex=False, scaley=False)
def process(self, X, V, C): BifPoint.process(self, X, V, C) J_coords = C.sysfunc.jac(X, C.coords) eigs, VL, VR = linalg.eig(J_coords, left=1, right=1) # Check for nonreal multipliers found = False for i in range(len(eigs)): for j in range(i+1,len(eigs)): if imag(eigs[i]) > 1e-5 and imag(eigs[j]) > 1e-5 and abs(eigs[i]*eigs[j] - 1) < 1e-5: found = True if not found: del self.found[-1] return False self.found[-1].eigs = eigs self.info(C, -1) return True
def bendmatz_comp(s, params, EIstr='EI2', symlabel='', \ subparams=False, debug=0): """Return a 4x4 transfer matrix for a beam in bending about the z-axis. This function is used for part of the GetMat function of an 8x8 or 12x12 beam. It will be the entire 4x4 transfer matrix if usez=True for the beam element.""" if debug>0: print('In bendmatz') EI = params[EIstr] mu = params['mu'] L = params['L'] if type(s) == rwkmisc.symstr: c = params['c'] else: s = complex(s) if not params.has_key('c'): c = 0.0#no damping elif params['c'] == 0.0: c = 0.0 else: w = imag(s) c = params['c']/w ## if abs(s) > 5*2*pi: ## c = 0.0 beta = pow((-1*s*s*L**4*mu/(EI*(c*s+1))),0.25) d1 = 0.5*(cos(beta)+cosh(beta)) d2 = 0.5*(sinh(beta)-sin(beta)) d3 = 0.5*(cosh(beta)-cos(beta)) d4 = 0.5*(sin(beta)+sinh(beta)) # there is an error in my thesis and this is it: (eqn 285) #a = beta/(L**2)#to check Brian Posts work a=L*L/EI outmat = array([[d1, L*d4/beta, a*d3/(beta**2*(1 + c*s)), \ -L*a*d2/(beta**3*(1 + c*s))], \ [beta*d2/L, d1, a*d4/(L*beta*(1 + c*s)), \ -a*d3/(beta**2*(1 + c*s))], \ [d3*beta**2*(1 + c*s)/a, L*beta*d2*(1 + c*s)/a, \ d1, -L*d4/beta], \ [-d4*beta**3*(1 + c*s)/(L*a), \ -d3*beta**2*(1 + c*s)/a, -beta*d2/L, d1]]) return outmat
def reference_symmetric_soc(A, theta): # This is just a direct complex extension of the classic # SA strength-of-connection measure. The extension continues # to compare magnitudes. This should reduce to the classic # measure if A is all real. # if theta == 0: # return A D = np.abs(A.diagonal()) S = coo_matrix(A) mask = S.row != S.col DD = np.array(D[S.row] * D[S.col]).reshape(-1,) # Note that abs takes the complex modulus element-wise # Note that using the square of the measure is the technique used # in the C++ routine, so we use it here. Doing otherwise causes errors. mask &= ((real(S.data)**2 + imag(S.data)**2) >= theta*theta*DD) S.row = S.row[mask] S.col = S.col[mask] S.data = S.data[mask] # Add back diagonal D = scipy.sparse.eye(S.shape[0], S.shape[0], format="csr", dtype=A.dtype) D.data[:] = csr_matrix(A).diagonal() S = S.tocsr() + D # Strength represents "distance", so take the magnitude S.data = np.abs(S.data) # Scale S by the largest magnitude entry in each row largest_row_entry = np.zeros((S.shape[0],), dtype=S.dtype) for i in range(S.shape[0]): for j in range(S.indptr[i], S.indptr[i+1]): val = abs(S.data[j]) if val > largest_row_entry[i]: largest_row_entry[i] = val largest_row_entry[largest_row_entry != 0] =\ 1.0 / largest_row_entry[largest_row_entry != 0] S = S.tocsr() S = scale_rows(S, largest_row_entry, copy=True) return S