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 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 bistatic_RCS(params_simu, inputDirName, simuDirName): phis_far_field = 180./pi * readASCIIBlitzFloatArray1DFromDisk(os.path.join(simuDirName, 'result/phis_far_field_ASCII.txt')) thetas_far_field = 180./pi * readASCIIBlitzFloatArray1DFromDisk(os.path.join(simuDirName, 'result/thetas_far_field_ASCII.txt')) e_phi = readBlitzArrayFromDisk(os.path.join(simuDirName, 'result/scatt_e_phi_far_Binary.txt'), thetas_far_field.shape[0], phis_far_field.shape[0], 'F') e_theta = readBlitzArrayFromDisk(os.path.join(simuDirName, 'result/scatt_e_theta_far_Binary.txt'), thetas_far_field.shape[0], phis_far_field.shape[0], 'F') p_scatt_theta = real(e_theta * conj(e_theta)) p_scatt_phi = real(e_phi*conj(e_phi)) R_cube_center = readASCIIBlitzFloatArray1DFromDisk(os.path.join(simuDirName, 'tmp' + str(0) + '/octtree_data/big_cube_center_coord.txt')) w = 2. * pi * params_simu.f eps, mu = params_simu.eps_r * eps_0, params_simu.mu_r * mu_0 k = w * sqrt(mu * eps) # the wavenumber P_inc = 0.0 if (params_simu.BISTATIC_EXCITATION_DIPOLES == 1): J_src, r_src = read_dipole_excitation(os.path.join(inputDirName, params_simu.BISTATIC_EXCITATION_J_DIPOLES_FILENAME)) r_dip_src = r_src[0,:] J_dip_src = J_src[0,:] G_EJ_inc, G_HJ_inc = G_EJ_G_HJ(r_dip_src, R_cube_center, eps, mu, k) E_inc = dot(G_EJ_inc, J_dip_src) P_inc += real(dot(E_inc, conj(E_inc))) if (params_simu.BISTATIC_EXCITATION_PLANE_WAVE == 1): E_inc = array([params_simu.E_inc_theta, params_simu.E_inc_phi], 'D') P_inc += real(dot(E_inc, conj(E_inc))) if (params_simu.BISTATIC_EXCITATION_DIPOLES == 1) and (params_simu.BISTATIC_EXCITATION_PLANE_WAVE == 1): print("WARNING: you have dipole and plane wave excitation simultaneously. Is it what you intended??") sigma_phi = 4.0*pi * p_scatt_phi/P_inc sigma_theta = 4.0*pi * p_scatt_theta/P_inc return sigma_theta, sigma_phi, thetas_far_field, phis_far_field
def algoChannelSelection(left, right): ''' Algorithm which automatically selects the channel with dominant vocals from a stereo flamenco recording based on spectral band energies as described in section 2-A-I of Kroher, N. & Gomez, E. (2016). Automatic Transcription of Flamenco Singing from Polyphonic Music Recordings. ACM / IEEE Transactions on Audio, Speech and Language Processing, 24(5), pp. 901-913. :param left: samples of the left audio channel in 44.1kHz :param right: samples of the right audio channel in 44.1kHz :return: index of the dominant vocal channel (0 = left, 1 = right) ''' # PARAMETERS fs = 44100 # sample rate wSize = 2048 # window size in samples hSize = 2048 # hop size in samples fftSize = 2048 # FFT size freqGuitLow = 80.0 # lower bound for guitar band freqGuitHigh = 400.0 # upper bound for guitar band freqVocLow = 500.0 # lower bound for vocal band freqVocHigh = 6000.0 # higher bound for vocal band # INIT window = hanning(wSize) numFrames = int(math.floor(float(len(left))/float(wSize))) # bin indices corresponding to freqeuncy band limits indGuitLow = int(round((freqGuitLow/fs)*fftSize)) indGuitHigh = int(round((freqGuitHigh/fs)*fftSize)) indVocLow = int(round((freqVocLow/fs)*fftSize)) indVocHigh = int(round((freqVocHigh/fs)*fftSize)) # frame-wise computation of the spectral band ratio sbrL = [] sbrR = [] for i in range(0,numFrames-100): frameL = left[i*hSize:i*hSize+wSize] specL = fft(frameL*window) / fftSize specL = abs(specL * conj(specL)) guitMag = sum(specL[indGuitLow:indGuitHigh],0) vocMag = sum(specL[indVocLow:indVocHigh],0) sbrL.append(20*math.log10(vocMag/guitMag)) frameR = right[i*hSize:i*wSize+wSize] specR = fft(frameR*window) / fftSize specR = abs(specR * conj(specR)) guitMag = sum(specR[indGuitLow:indGuitHigh],0) vocMag = sum(specR[indVocLow:indVocHigh],0) sbrR.append(20*math.log10(vocMag/guitMag)) # select channel based on mean SBR if mean(sbrL)>=mean(sbrR): ind = 0 else: ind = 1 return ind
def antenna_pattern(params_simu, simuDirName): phis_far_field = 180./pi * readASCIIBlitzFloatArray1DFromDisk(os.path.join(simuDirName, 'result/phis_far_field_ASCII.txt')) thetas_far_field = 180./pi * readASCIIBlitzFloatArray1DFromDisk(os.path.join(simuDirName, 'result/thetas_far_field_ASCII.txt')) scatt_e_phi = readBlitzArrayFromDisk(os.path.join(simuDirName, 'result/scatt_e_phi_far_Binary.txt'), thetas_far_field.shape[0], phis_far_field.shape[0], 'F') scatt_e_theta = readBlitzArrayFromDisk(os.path.join(simuDirName, 'result/scatt_e_theta_far_Binary.txt'), thetas_far_field.shape[0], phis_far_field.shape[0], 'F') source_e_phi = readBlitzArrayFromDisk(os.path.join(simuDirName, 'result/source_e_phi_far_Binary.txt'), thetas_far_field.shape[0], phis_far_field.shape[0], 'F') source_e_theta = readBlitzArrayFromDisk(os.path.join(simuDirName, 'result/source_e_theta_far_Binary.txt'), thetas_far_field.shape[0], phis_far_field.shape[0], 'F') e_theta, e_phi = scatt_e_theta + source_e_theta, scatt_e_phi + source_e_phi sigma_theta, sigma_phi = real(e_theta * conj(e_theta)), real(e_phi*conj(e_phi)) return sigma_theta, sigma_phi, thetas_far_field, phis_far_field
def algoChannelSelection(left, right): ''' Algorithm which automatically selects the channel with dominant vocals from a stereo flamenco recording based on spectral band energies as described in section 2-A-I of Kroher, N. & Gomez, E. (2016). Automatic Transcription of Flamenco Singing from Polyphonic Music Recordings. ACM / IEEE Transactions on Audio, Speech and Language Processing, 24(5), pp. 901-913. :param left: samples of the left audio channel in 44.1kHz :param right: samples of the right audio channel in 44.1kHz :return: index of the dominant vocal channel (0 = left, 1 = right) ''' # PARAMETERS fs = 44100 # sample rate wSize = 2048 # window size in samples hSize = 2048 # hop size in samples fftSize = 2048 # FFT size freqGuitLow = 80.0 # lower bound for guitar band freqGuitHigh = 400.0 # upper bound for guitar band freqVocLow = 500.0 # lower bound for vocal band freqVocHigh = 6000.0 # higher bound for vocal band # INIT window = hanning(wSize) numFrames = int(math.floor(float(len(left)) / float(wSize))) # bin indices corresponding to freqeuncy band limits indGuitLow = int(round((freqGuitLow / fs) * fftSize)) indGuitHigh = int(round((freqGuitHigh / fs) * fftSize)) indVocLow = int(round((freqVocLow / fs) * fftSize)) indVocHigh = int(round((freqVocHigh / fs) * fftSize)) # frame-wise computation of the spectral band ratio sbrL = [] sbrR = [] for i in range(0, numFrames - 100): frameL = left[i * hSize:i * hSize + wSize] specL = fft(frameL * window) / fftSize specL = abs(specL * conj(specL)) guitMag = sum(specL[indGuitLow:indGuitHigh], 0) vocMag = sum(specL[indVocLow:indVocHigh], 0) sbrL.append(20 * math.log10(vocMag / guitMag)) frameR = right[i * hSize:i * wSize + wSize] specR = fft(frameR * window) / fftSize specR = abs(specR * conj(specR)) guitMag = sum(specR[indGuitLow:indGuitHigh], 0) vocMag = sum(specR[indVocLow:indVocHigh], 0) sbrR.append(20 * math.log10(vocMag / guitMag)) # select channel based on mean SBR if mean(sbrL) >= mean(sbrR): ind = 0 else: ind = 1 return ind
def CorrelatorImGGzero(G1_A, G2_A, i1, i2): ''' <G1(x+i10)G2(x+i20)>, w=0 element of the CorrelatorGG ''' if i1 < 0: G1_A = sp.conj(G1_A) if i2 < 0: G2_A = sp.conj(G2_A) Int_A = FD_A * sp.imag(G1_A * G2_A) Int = simps(Int_A, En_A) #print(Int_A[ 0],Int_A[-1]) #TailL = -sp.real(Int_A[ 0])*En_A[ 0] #TailR = sp.real(Int_A[-1])*En_A[-1] #return -(Int+TailL+TailR)/sp.pi return -Int / sp.pi
def GetEigSys(filename,gsfile=None,Nsamp=1,channel=None,wavefile=None,q=None): if type(filename)==str: filename=[filename] hfile=h5py.File(filename[0],'r') attr=GetAttr(filename[0]) if channel==None: channel=attr['channel'] dpath,args=GetStat(filename,Nsamp) dat=sc.array(hfile["/rank-1/data-0"]) hfile.close() N=int(sc.shape(dat)[0]/2) L=attr['L'] shift=None if 'phasex' in attr.keys(): shift=[attr['phasex']/2.0,attr['phasey']/2.0] else: shift=[attr['phase_shift_x']/2.0,attr['phase_shift_y']/2.0] H=sc.zeros([Nsamp,N,N],complex) O=sc.zeros([Nsamp,N,N],complex) E=sc.zeros([Nsamp,N]) V=sc.zeros([Nsamp,N,N],complex) for sample,b in enumerate(args): for d in b: hfile=h5py.File(dpath[d][0],'r') dat=hfile[dpath[d][1]] H[sample,:,:]+=dat[0:N,0:2*N:2]+1j*dat[0:N,1:2*N:2] O[sample,:,:]+=dat[N:2*N,0:2*N:2]+1j*dat[N:2*N,1:2*N:2] hfile.close() H[sample,:,:]=0.5*(H[sample,:,:]+sc.conj(H[sample,:,:].T))/len(b) O[sample,:,:]=0.5*(O[sample,:,:]+sc.conj(O[sample,:,:].T))/len(b) if channel=='groundstate': return H fs=None refstate=sc.zeros(2*L*L) refstate[0::2]=1 if wavefile==None: fs=GetFermiSigns(filename[0],refstate,channel=channel) else: fs=GetFermiSigns(wavefile,refstate,channel=channel) for s in range(sc.shape(H)[0]): H[s,:,:]=sc.dot(sc.diag(fs),sc.dot(H[s,:,:],sc.diag(fs))) O[s,:,:]=sc.dot(sc.diag(fs),sc.dot(O[s,:,:],sc.diag(fs))) ren=sc.ones(Nsamp) if gsfile!=None: ren=RenormalizeFactor(filename,gsfile,Nsamp=1,channel=channel,O=O,q=q) print('{0} pair of (H,O) matrices loaded, now diagonalize'.format(sc.shape(H)[0])) H=sc.einsum('ijk,i->ijk',H,ren) O=sc.einsum('ijk,i->ijk',O,ren) for s in range(sc.shape(H)[0]): E[s,:],V[s,:,:]=vln.geneigh(sc.squeeze(H[s,:,:]),sc.squeeze(O[s,:,:])) print('diagonalization finished') return H,O,E,V
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 get_pair(self, pair_type, vec_in): vec_out = sp.empty(self.ndim, dtype=self.complex_precision) n2 = int(self.ndim / 2) if pair_type == 'x': vec_out[n2:] = sp.conj(vec_in[:n2]) vec_out[:n2] = sp.conj(vec_in[n2:]) elif pair_type == 'Ax': vec_out[n2:] = -vec_in[:n2].conj() vec_out[:n2] = -vec_in[n2:].conj() else: sys.exit( "ABORTING!! Unknown pair_type specified in eigenvector construction" ) return vec_out
def sqwtransamp(V,O,Lx,Ly,q,shift,phi,neel,r=sc.zeros((1,2)),rp=sc.zeros((1,2))): """ Returns Sq[sample,r,rp,n]=<q,r|q,n><q,n|q,rp> """ sqn=sc.zeros(sc.shape(V)[0:2],complex) kx,ky=fermisea(Lx,Ly,shift) pkrp=sc.zeros((sc.shape(V)[1],sc.shape(rp)[0]),complex) pkr=sc.zeros((sc.shape(V)[1],sc.shape(r)[0]),complex) pkrp[0:len(kx),:]=phiktrans(kx,ky,q[0],q[1],[phi,neel],rp) pkr[0:len(ky),:]=phiktrans(kx,ky,q[0],q[1],[phi,neel],r) OV=sc.einsum('ijk,ikl->ijl',O,V) rhs=sc.einsum('ijk,jl->ikl',sc.conj(OV),pkrp) lhs=sc.einsum('ij,kil->kjl',sc.conj(pkr),OV) sqn=sc.einsum('ijk,ikl->ijlk',lhs,rhs) return sqn
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 normJMCentroidsTriangles(J_M_centroids): T = J_M_centroids.shape[0] norm_J_M_centroids = zeros((T, 1), 'f') for i in range(T): norm_J_M_centroids[i] = sqrt( real(sum(J_M_centroids[i, :] * conj(J_M_centroids[i, :])))) return norm_J_M_centroids
def ffacorr(a): """Returns the autocorrelation of a. Expects raw data""" z=np.zeros(2*len(a)) z[:len(a)]=a fft=sc.fft(z) out=sc.ifft(fft*sc.conj(fft)) return (out[:len(out)/2])
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 evaluate_basis_at(self, nodes, component=None, prefactor=False): r""" Evaluate the Hagedorn functions :math:`\phi_k` recursively at the given nodes :math:`\gamma`. :param nodes: The nodes :math:`\gamma` at which the Hagedorn functions are evaluated. :param component: Takes the basis size :math:`K_i` of this component :math:`i` as upper bound for :math:`K`. :param prefactor: Whether to include a factor of :math:`\left(\det\left(Q\right)\right)^{-\frac{1}{2}}`. :return: Returns a twodimensional :math:`K` times #nodes array :math:`H` where the entry :math:`H[k,i]` is the value of the :math:`k`-th Hagedorn function evaluated at the node :math:`i`. """ if component is not None: basis_size = self.basis_size[component] else: # Evaluate up to maximal :math:`K_i` and slice later if necessary basis_size = max(self.basis_size) H = zeros((basis_size, nodes.size), dtype=complexfloating) Qinv = self.Q**(-1.0) Qbar = conj(self.Q) nodes = nodes.reshape((1,nodes.size)) H[0] = pi**(-0.25)*self.eps**(-0.5) * exp(1.0j/self.eps**2 * (0.5*self.P*Qinv*(nodes-self.q)**2 + self.p*(nodes-self.q))) H[1] = Qinv*sqrt(2.0/self.eps**2) * (nodes-self.q) * H[0] for k in xrange(2, basis_size): H[k] = Qinv*sqrt(2.0/self.eps**2)*1.0/sqrt(k) * (nodes-self.q) * H[k-1] - Qinv*Qbar*sqrt((k-1.0)/k) * H[k-2] if prefactor is True: sqrtQ, self._cont_sqrt_cache = cont_sqrt(self.Q, reference=self._cont_sqrt_cache) H = 1.0/sqrtQ*H return H
def sc_collapse(modes,N): """ Helper function: combines roles of c_collapse, s_collapse """ from numpy import sqrt, append from scipy import conj NEven = (N%2)==0 Nq = N + (N+1)%2 modescopy = modes.copy() if NEven: modescopy[0] /= 2. modescopy = append(modescopy,conj(modescopy[0])) tempN = Nq/2 tempN2 = tempN - ((Nq+1)%2) #cmodes = modes[:tempN+1][::-1].copy() cmodes = modescopy[:tempN+1][::-1] smodes = -cmodes[1:].copy() cmodes[1:tempN2+1] += modescopy[tempN+1:] smodes[:tempN2] += modescopy[tempN+1:] cmodes[0] *= sqrt(2) return [cmodes*1/2.,smodes*1/2.]
def sc_expand(cmodes,smodes,N): """ Helper function: combines roles of c_expand, s_expand """ from numpy import sqrt,zeros from scipy import conj Neven = (N+1)%2 n = N/2 factor = N - Neven # 'positive' modes pmodes = cmodes.copy() pmodes[0] *= sqrt(2) pmodes[1:] += smodes # Turn smodes into 'negative' modes smodes = (cmodes[1:] - smodes)[::-1] # Put it all together modes = zeros(2*n+1,dtype='complex128') modes[:n],modes[n:] = smodes,pmodes if bool(Neven): modes[0] += conj(modes[-1]) return modes[:-1] else: return modes
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 down_sample(filename, new_rate, outputfile=None): """ Create a down-sampled copy of the provided .wav file. Unless overridden, the output file will be of the form "down_<orginalname>.wav" Parameters ---------- filename : string input .wav file new_rate : int sample rate of output file outputfile : string name of output file """ if outputfile is None: outputfile = "down_" + filename old_rate, in_sig = wavfile.read(filename) in_sig = sp.float32(in_sig) fin = sp.fft(in_sig) nsiz = sp.floor(in_sig.size * new_rate / old_rate) nsizh = sp.floor(nsiz / 2) fout = sp.zeros(nsiz) fout = fout + 0j fout[0:nsizh] = fin[0:nsizh] fout[nsiz - nsizh + 1 :] = sp.conj(sp.flipud(fout[1:nsizh])) out = sp.ifft(fout) out = sp.real(out) # Take the real component of the signal out = sp.int16(out / sp.absolute(out).max() * 32767) wavfile.write(outputfile, new_rate, out)
def bondOrientation2sh(atoms,basis,l,neighbs=None,rcut=None,debug=False): atoms = array(atoms) basis = array(basis) atoms = rectify(atoms,basis) if neighbs==None: bounds=[[0,basis[0][0]],[0,basis[1][1]],[0,basis[2][2]]] if rcut==None: rcut = generateRCut(atoms,basis,debug=debug) #print "Automatically generating r-cutoff=",rcut neighbs = secondShell( neighbors(atoms,bounds,rcut) ) #sum the spherical harmonic over ever neighbor pair a = 4*np.pi / (2*l+1.) Ql=list() for i,ineighbs in enumerate(neighbs): n=len(ineighbs) shij = np.vectorize(complex)(zeros(2*l+1)) #spherical harmonic for bond i-j for j in ineighbs: shij += pairSphereHarms(atoms[i],minImageAtom(atoms[i],atoms[j],basis),l)/n shi = a * sum( scipy.real( scipy.multiply(shij,scipy.conj(shij)) ) ) Ql.append(shi**0.5) return Ql,rcut
def transitionMatrix4(g, minstrength=0.1, distribution='normal', maxtries=1000): A = gk.CG2adj(g) edges = np.where(A == 1) s = 2.0 c = 0 pbar = ProgressBar(widgets=['Searching for weights: ', Percentage(), ' '], maxval=maxtries).start() while s > 1.0: minstrength -= 0.001 A = initRandomMatrix(A, edges, distribution=distribution) x = A[edges] delta = minstrength / np.min(np.abs(x)) A[edges] = delta * x l = linalg.eig(A)[0] s = np.max(np.real(l * scipy.conj(l))) c += 1 if c > maxtries: return None pbar.update(c) pbar.finish() return A
def prob4(filename='saw.wav', new_rate = 11025, outfile='prob4.wav'): """Down-samples a given .wav file to a new rate and saves the resulting signal as another .wav file. Parameters ---------- filename : string, optional The name of the .wav sound file to be down-sampled. Defaults to 'saw.wav'. new_rate : integer, optional The down-sampled rate. Defaults to 11025. outfile : string, optional The name of the new file. Defaults to prob4.wav. Returns ------- None """ old_rate, in_sig = wavfile.read(filename) fin = fftw.fft(sp.float32(in_sig)) # Use if scipy_fftpack is unavailable # fin = sp.fft(sp.float32(in_sig)) nsiz = sp.floor(in_sig.size * new_rate / old_rate) nsizh = sp.floor(nsiz / 2) fout = sp.zeros(nsiz) + 0j fout[0:nsizh] = fin[0:nsizh] fout[nsiz-nsizh+1:] = sp.conj(sp.flipud(fout[1:nsizh])) out = sp.real(sp.ifft(fout)) out = sp.int16(out/sp.absolute(out).max() * 32767) plot_signal(filename) wavfile.write('prob4.wav',new_rate,out) print ""; plot_signal('prob4.wav')
def prob4(filename='saw.wav', new_rate=11025, outfile='prob4.wav'): """Down-samples a given .wav file to a new rate and saves the resulting signal as another .wav file. Parameters ---------- filename : string, optional The name of the .wav sound file to be down-sampled. Defaults to 'saw.wav'. new_rate : integer, optional The down-sampled rate. Defaults to 11025. outfile : string, optional The name of the new file. Defaults to prob4.wav. Returns ------- None """ old_rate, in_sig = wavfile.read(filename) fin = fftw.fft(sp.float32(in_sig)) # Use if scipy_fftpack is unavailable # fin = sp.fft(sp.float32(in_sig)) nsiz = sp.floor(in_sig.size * new_rate / old_rate) nsizh = sp.floor(nsiz / 2) fout = sp.zeros(nsiz) + 0j fout[0:nsizh] = fin[0:nsizh] fout[nsiz - nsizh + 1:] = sp.conj(sp.flipud(fout[1:nsizh])) out = sp.real(sp.ifft(fout)) out = sp.int16(out / sp.absolute(out).max() * 32767) plot_signal(filename) wavfile.write('prob4.wav', new_rate, out) print "" plot_signal('prob4.wav')
def project_to_canonical(self, potential): r""" Project the Hagedorn wavepacket into the canonical basis. :param potential: The potential :math:`V` whose eigenvectors :math:`nu_l` are used for the transformation. .. note:: This function is expensive and destructive! It modifies the coefficients of the ``self`` instance. """ # No projection for potentials with a single energy level. # The canonical and eigenbasis are identical here. if potential.get_number_components() == 1: return potential.calculate_eigenvectors() # Basically an ugly hack to overcome some shortcomings of the matrix function # and of the data layout. def f(q, x, component): x = x.reshape((self.quadrature.get_qr().get_number_nodes(),)) z = potential.evaluate_eigenvectors_at(x) (row, col) = component return z[col][row,:] F = transpose(conj(self.quadrature.build_matrix(self,self,f))) c = self.get_coefficient_vector() d = dot(F, c) self.set_coefficient_vector(d)
def evaluate_basis_at(self, nodes, component, prefactor=False): r""" Evaluate the Hagedorn functions :math:`\phi_k` recursively at the given nodes :math:`\gamma`. :param nodes: The nodes :math:`\gamma` at which the Hagedorn functions are evaluated. :param component: The index :math:`i` of the component whose basis functions :math:`\phi^i_k` we want to evaluate. :param prefactor: Whether to include a factor of :math:`\left(\det\left(Q_i\right)\right)^{-\frac{1}{2}}`. :return: Returns a twodimensional array :math:`H` where the entry :math:`H[k,i]` is the value of the :math:`k`-th Hagedorn function evaluated at the node :math:`i`. """ H = zeros((self.basis_size[component], nodes.size), dtype=complexfloating) (P, Q, S, p, q) = self.parameters[component] Qinv = Q**(-1.0) Qbar = conj(Q) nodes = nodes.reshape((1,nodes.size)) H[0] = pi**(-0.25)*self.eps**(-0.5) * exp(1.0j/self.eps**2 * (0.5*P*Qinv*(nodes-q)**2 + p*(nodes-q))) H[1] = Qinv*sqrt(2.0/self.eps**2) * (nodes-q) * H[0] for k in xrange(2, self.basis_size[component]): H[k] = Qinv*sqrt(2.0/self.eps**2)*1.0/sqrt(k) * (nodes-q) * H[k-1] - Qinv*Qbar*sqrt((k-1.0)/k) * H[k-2] if prefactor is True: sqrtQ, self._cont_sqrt_cache[component] = cont_sqrt(Q, reference=self._cont_sqrt_cache[component]) H = 1.0/sqrtQ*H return H
def phiktrans(kx,ky,qx,qy,p,r=sc.zeros((1,2))): """ Returns phi[k,r] such that |q,r>=sum_k phi[k,r]|q,k> """ kqx=kx-qx kqy=ky-qy pk=sc.zeros((sc.shape(kx)[0],sc.shape(r)[0]),complex) pke=sc.conj(uk(kx,ky,1,1,p))*uk(kqx,kqy,-1,-1,p)+\ sc.conj(vk(kx,ky,1,1,p))*vk(kqx,kqy,-1,-1,p) pko=sc.conj(vk(kx,ky,1,1,p))*uk(kqx,kqy,-1,-1,p)+\ sc.conj(uk(kx,ky,1,1,p))*vk(kqx,kqy,-1,-1,p) even=1-sc.mod(r[:,0]+r[:,1],2) odd=sc.mod(r[:,0]+r[:,1],2) ph=sc.exp(-2j*sc.pi*(sc.einsum('i,j->ij',kx,r[:,0])+sc.einsum('i,j->ij',ky,r[:,1]))) pk=sc.einsum('ij,j,i->ij',ph,even,pke)+sc.einsum('ij,j,i->ij',ph,odd,pko) return pk
def corr_high_freq(frame1, frame2, cut_off, one_is_ffted=False): """ Parameters ---------- """ frame_size_x, frame_size_y = frame2.shape x, y = scipy.meshgrid(scipy.arange(-frame_size_x / 2, frame_size_x / 2), scipy.arange(-frame_size_y / 2, frame_size_y / 2)) freqs = scipy.sqrt(x**2 + y**2) frame2 = frame2 - frame2.mean() if not one_is_ffted: fft_1 = fft2(frame1) / (frame_size_x * frame_size_y) else: fft_1 = frame1 fft_2 = fft2(frame2) / (frame_size_x * frame_size_y) correlation = fftshift(ifft2(fft_1 * scipy.conj(fft_2) * (freqs > cut_off)))**2 return correlation
def coherent(N, alpha, method='operator'): """Generates a coherent state with eigenvalue alpha. Constructed using displacement operator on vacuum state. Parameters ---------- N : int Number of Fock states in Hilbert space. alpha : float/complex Eigenvalue of coherent state. method : string {'operator', 'analytic'} Method for generating coherent state. Returns ------- state : qobj Qobj quantum object for coherent state Examples -------- >>> coherent(5,0.25j) Quantum object: dims = [[5], [1]], shape = [5, 1], type = ket Qobj data = [[ 9.69233235e-01+0.j ] [ 0.00000000e+00+0.24230831j] [ -4.28344935e-02+0.j ] [ 0.00000000e+00-0.00618204j] [ 7.80904967e-04+0.j ]] Notes ----- Select method 'operator' (default) or 'analytic'. With the 'operator' method, the coherent state is generated by displacing the vacuum state using the displacement operator defined in the truncated Hilbert space of size 'N'. This method guarantees that the resulting state is normalized. With 'analytic' method the coherent state is generated using the analytical formula for the coherent state coefficients in the Fock basis. THIS METHOD DOES NOT GUARANTEE THAT THE STATE IS NORMALIZED if truncated to a small number of Fock states, but would in that case give more accurate coefficients. """ if method == "operator": x=basis(N,0) a=destroy(N) D=(alpha*a.dag()-conj(alpha)*a).expm() return D*x elif method == "analytic": data = np.zeros([N,1],dtype=complex) n = arange(N) data[:,0] = np.exp(-(abs(alpha)**2)/2.0)*(alpha**(n))/_sqrt_factorial(n) return Qobj(data) else: raise TypeError("The method option can only take values 'operator' or 'analytic'")
def Renorm(sqsq,O,Lx,Ly,q,shift,p): kx,ky=fermisea(Lx,Ly,shift) pp=phiktrans(kx,ky,float(q[0])/Lx,float(q[1])/Ly,[p['phi'],p['neel']]) b=sc.dot(sc.conj(pp),sc.dot(O,pp)) r=sqsq/b if sc.isnan(r): r=1 return r,b
def xcorr(t, x, y, zeropad = True): tau = t sx = len(x) sy = len(y) if zeropad == True: Xn = sp.fft(x, n = len(x)*2) Yn = sp.conj(sp.fft(y, n = len(x)*2)) else: Xn = sp.fft(x) Yn = sp.conj(sp.fft(y)) xcor = sp.real(fftpack.fftshift(sp.ifft(Xn*Yn))) dt = t[1]-t[0] tau = sp.linspace(-len(xcor)/2*dt-dt/2,len(xcor)/2*dt-dt/2,len(xcor)) return tau, xcor
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 xcorr(t, x, y, zeropad=True): tau = t sx = len(x) sy = len(y) if zeropad == True: Xn = sp.fft(x, n=len(x) * 2) Yn = sp.conj(sp.fft(y, n=len(x) * 2)) else: Xn = sp.fft(x) Yn = sp.conj(sp.fft(y)) xcor = sp.real(fftpack.fftshift(sp.ifft(Xn * Yn))) dt = t[1] - t[0] tau = sp.linspace(-len(xcor) / 2 * dt - dt / 2, len(xcor) / 2 * dt - dt / 2, len(xcor)) return tau, xcor
def seizure(data, thresh = 0.3, bias = 0.1): # probably want to initialize by computing the ER for x number of windows, estimate a normal distribution # then compute threshold from whatever is statistically significant #Take some number of initial windows and set threshold to the minimum statistically significant value above the mean modeling the output as a normal distribution #print(numpy.shape(data)) fs = 256 # sampling frequency duration = 5 # time duration of the window advance = duration * fs # the number of samples to shift the window forward by startIndex = 0 endIndex = advance - 1 thetaLow = 4 thetaHigh = 7 alphaLow = 8 alphaHigh = 12 betaLow = 13 betaHigh = 24 gammaLow = 25 gammaHigh = 97 ER = numpy.array([]) while (endIndex < len(data)): energySpectrum = numpy.multiply(scipy.fft(data[startIndex:endIndex]), scipy.conj(scipy.fft(data[startIndex:endIndex]))) energyRatio = sum(energySpectrum[betaLow:gammaHigh]) / sum(energySpectrum[thetaLow:alphaHigh]) numpy.append(ER, energyRatio) endIndex = endIndex + advance startIndex = startIndex + advance U_n = numpy.array([]) seizureIndex = numpy.array([]) seizureStart = numpy.array([]) for i in range(0, len(ER)-1): numpy.append(U_n, ER[i] - numpy.average(ER[0:i]) - bias) if(U_n[i] - min(U_n) > thresh): seizureIndex = numpy.append(seizureIndex, i) seizureStart = numpy.append(seizureStart, numpy.argmin(U_n)) if(len(seizureIndex) == 0 and len(seizureStart) == 0): seizureIndex = numpy.array([-1]) seizureStart = numpy.array([-1]) return (seizureIndex, seizureStart)
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 conj(x): """ Wrapper for conjugate on a CXData object. """ if isinstance(x, CXData): l = [] for i in xrange(len(x)): l.append(sp.conj(x.data[i])) return CXData(data=l) elif isinstance(x, CXModal): l = [] for mode in range(len(x.modes)): l.append(conj(x.modes[mode])) return CXModal(modes=l) elif isinstance(x, np.ndarray): return sp.conj(x) else: raise Exception('Unknown data type passed to conj')
def cross_periodogram(x1, x2, Fs, window, scale_by_freq = True, two_sided = False, detrend = True): # Remove mean if detrend: t1 = s.fftpack.fft((x1-s.mean(x1))*window) t2 = s.fftpack.fft((x2-s.mean(x2))*window) else: t1 = s.fftpack.fft(x1*window) t2 = s.fftpack.fft(x2*window) # Return cross spectral density or just spectrum if scale_by_freq: csd = t1*s.conj(t2)/s.sum(window**2)/Fs else: csd = t1*s.conj(t2)/s.sum(window**2) if two_sided: return csd else: return csd[:len(x1)/2+1]
def phiktrans(kx, ky, qx, qy, p, r=sc.zeros((1, 2))): """ Returns phi[k,r] such that |q,r>=sum_k phi[k,r]|q,k> """ kqx = kx - qx kqy = ky - qy pk = sc.zeros((sc.shape(kx)[0], sc.shape(r)[0]), complex) pke=sc.conj(uk(kx,ky,1,1,p))*uk(kqx,kqy,-1,-1,p)+\ sc.conj(vk(kx,ky,1,1,p))*vk(kqx,kqy,-1,-1,p) pko=sc.conj(vk(kx,ky,1,1,p))*uk(kqx,kqy,-1,-1,p)+\ sc.conj(uk(kx,ky,1,1,p))*vk(kqx,kqy,-1,-1,p) even = 1 - sc.mod(r[:, 0] + r[:, 1], 2) odd = sc.mod(r[:, 0] + r[:, 1], 2) ph = sc.exp(-2j * sc.pi * (sc.einsum('i,j->ij', kx, r[:, 0]) + sc.einsum('i,j->ij', ky, r[:, 1]))) pk = sc.einsum('ij,j,i->ij', ph, even, pke) + sc.einsum( 'ij,j,i->ij', ph, odd, pko) return pk
def conj(x): """ Wrapper for conjugate on a CXData object. """ if isinstance(x, CXData): l=[] for i in xrange(len(x)): l.append(sp.conj(x.data[i])) return CXData(data=l) elif isinstance(x, CXModal): l=[] for mode in range(len(x.modes)): l.append(conj(x.modes[mode])) return CXModal(modes=l) elif isinstance(x, np.ndarray): return sp.conj(x) else: raise Exception('Unknown data type passed to conj')
def generateIDV(fnum, numpoints, footprint, rms): # Randomly sampled variables viss = random.uniform(3, 5) * 1e4 # velocity of ISS [m/s] sm = 10**random.uniform( -5, -2) * 3.09e19 # integrated scattering index [m^-17/3] z = random.uniform( 100, 1000) * 3.09e16 # distance of scattering screen from Earth [m] # Fixed variables s0 = 6.4e7 # [m] lmbda = 0.21 # wavelength [m] r_e = 2.82e-15 # radius of an electron [m] theta0 = 0.001 / 3600 * pi / 180 k = 2 * pi / lmbda # wavenumber [1/m] scale = 2.0 * (pi**2) * (r_e**2) * (lmbda**2) * sm * scipy.special.gamma( 7. / 6) * (z**2) / ((2 * pi / lmbda)**2) / ( (z**2 * theta0**2)**(7. / 6)) n_times = 1000 x = scipy.linspace(0, 10, n_times) timeInDays = (x * 2 * z * theta0 / viss) / (24 * 3600) y = scipy.linspace(0, 0, n_times) for i in range(n_times): y[i] = myutils.laguerre_7on6(float(pow(x[i], 2))) y2 = scipy.linspace(0, 0, n_times * 2 - 1) y2[0:n_times - 1] = y[0:n_times - 1] temp = y[::-1] for i in range(n_times - 1): y2[i + n_times] = temp[i] cphases = scipy.zeros(n_times, complex) for i in range(n_times): phases = random.uniform(0, 1) * 2 * pi cphases[i] = complex(cos(phases), sin(phases)) fy = scipy.fft(y2) abs_fy = numpy.sqrt(numpy.abs(fy)) new_y = scipy.zeros(n_times * 2 - 1, complex) for i in range(n_times): new_y[i] = abs_fy[i] * cphases[i] temp = scipy.conj(cphases)[::-1] for i in range(n_times - 1): new_y[i + n_times] = abs_fy[i + n_times] * temp[i] new_y[0] = 0 flux = 1.0 + scale * (scipy.real(scipy.ifft(new_y))) quiescent_flux = random.uniform(10, 100) fname = 'IDV_' + str(fnum) + '.data' f = open(fname, 'w') for i in range(n_times): writetime = str(timeInDays[i]) writeflux = str(flux[i] * quiescent_flux) f.write(writetime + '\t' + writeflux + '\n')
def _spectral_filtering(x, window): # Filtering in frequency space is multiplication, (convolution in time space). Nx = len(x) Cx = scipy.fft(x.ravel()) Cx = Cx[:(Nx // 2) + 1] CxH = Cx * window.ravel() # Mirror CxH and append it to itself, dropping the values depending on the length of the input. CxH = np.concatenate((CxH, scipy.conj(CxH[1:Nx - len(CxH) + 1][::-1]))) y = np.real(scipy.ifft(CxH)) return y, Cx
def CalcSpectra(x,y, input=None, output=None): """Calculate Gxx, Gyy, and Gxy. Note that input and output are just labels. x and y are time domain signals.""" N = max(shape(x)) x_fft = squeeze(fft(x, None, 0)*2/N) y_fft = squeeze(fft(y, None, 0)*2/N) Gxx = norm2(x_fft) Gyy = norm2(y_fft) Gxy = (scipy.conj(x_fft))*y_fft return Spectra(input, output, Gxx, Gyy, Gxy)
def Renorm(sqsq, O, Lx, Ly, q, shift, p): kx, ky = fermisea(Lx, Ly, shift) pp = phiktrans(kx, ky, float(q[0]) / Lx, float(q[1]) / Ly, [p['phi'], p['neel']]) b = sc.dot(sc.conj(pp), sc.dot(O, pp)) r = sqsq / b if sc.isnan(r): r = 1 return r, b
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 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 ReBDDFDD(Gup_A, Gdn_A, printint): ''' function to calculate the sum of real parts of FD and BD integrals ''' Int1_A = sp.imag(1.0 / sp.flipud(sp.conj(Det_A))) * sp.real( Gup_A * sp.flipud(Gdn_A)) Int2_A = sp.imag(Gup_A * sp.flipud(sp.conj(Gdn_A)) / sp.flipud(sp.conj(Det_A))) ## here we multiply big and small numbers for energies close to zero #RBF1_A = sp.exp(sp.log(FB_A)+sp.log(Int1_A)) RBF1_A = -FB_A * Int1_A RBF1_A[Nhalf] = (RBF1_A[Nhalf - 1] + RBF1_A[Nhalf + 1]) / 2.0 RBF2_A = -FD_A * Int2_A TailL2 = -0.5 * RBF2_A[0] * En_A[ 0] ## leading-order, 1/x**3 tail correction to Int2_A RBF = (simps(RBF1_A + RBF2_A, En_A) + TailL2) / sp.pi if printint: WriteFileX([Int1_A, Int2_A, RBF1_A, RBF2_A], 50.0, 3, '', 'RBF.dat') print('{0: .5f}\t{1: .8f}\t{2: .8f}'\ .format(T,simps(RBF1_A,En_A)/sp.pi,(simps(RBF2_A,En_A)+TailL2)/sp.pi),flush=True) #exit() return RBF
def CorrelatorsSE(Gup_A, Gdn_A, i1, i2): ''' correlators to Theta function, updated ''' ## zero-padding the arrays, G1 and G2 are complex functions FDex_A = sp.concatenate( [FD_A[Nhalf:], sp.zeros(2 * Nhalf + 3), FD_A[:Nhalf]]) Fup_A = sp.concatenate( [Gup_A[Nhalf:], sp.zeros(2 * Nhalf + 3), Gup_A[:Nhalf]]) Fdn_A = sp.concatenate( [Gdn_A[Nhalf:], sp.zeros(2 * Nhalf + 3), Gdn_A[:Nhalf]]) ftIGG1_A = fft(FDex_A * sp.imag(Fdn_A)) * sp.conj(fft(Fup_A)) * dE ftGG2_A = sp.conj(fft(FDex_A * sp.conj(Fup_A))) * fft(Fdn_A) * dE ftGG3_A = sp.conj(fft(FDex_A * Fup_A)) * fft(Fdn_A) * dE IGGs1_A = -ifft(ftIGG1_A) / sp.pi GGs2_A = -ifft(ftGG2_A) / (2.0j * sp.pi) GGs3_A = -ifft(ftGG3_A) / (2.0j * sp.pi) ## undo the zero padding IGGs1_A = sp.concatenate([IGGs1_A[3 * Nhalf + 4:], IGGs1_A[:Nhalf + 1]]) GGs2_A = sp.concatenate([GGs2_A[3 * Nhalf + 4:], GGs2_A[:Nhalf + 1]]) GGs3_A = sp.concatenate([GGs3_A[3 * Nhalf + 4:], GGs3_A[:Nhalf + 1]]) return [IGGs1_A, GGs2_A, GGs3_A]
def CorrelatorGG(G1_A, G2_A, En_A, i1, i2): ''' <G1(x+i10)G2(x+w+i20)>, i1 and i2 are imaginary parts of arguments ''' ## zero-padding the arrays, G1 and G2 are complex functions FDex_A = sp.concatenate( [FD_A[Nhalf:], sp.zeros(2 * Nhalf + 3), FD_A[:Nhalf]]) G1ex_A = sp.concatenate( [G1_A[Nhalf:], sp.zeros(2 * Nhalf + 3), G1_A[:Nhalf]]) G2ex_A = sp.concatenate( [G2_A[Nhalf:], sp.zeros(2 * Nhalf + 3), G2_A[:Nhalf]]) if i1 * i2 > 0: G1ex_A = sp.conj(G1ex_A) ftF1_A = fft(FDex_A * G1ex_A) ftF2_A = fft(G2ex_A) if i2 > 0: ftF1_A = sp.conj(ftF1_A) else: ftF2_A = sp.conj(ftF2_A) GG_A = ifft(ftF1_A * ftF2_A * dE) ## undo the zero padding GG_A = sp.concatenate([GG_A[3 * Nhalf + 4:], GG_A[:Nhalf + 1]]) TailL = -sp.real(G1_A)[0] * sp.real(G2_A)[0] * En_A[ 0] ## leading tail correction return -(GG_A + TailL) / sp.pi
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 phase_coded_wf(code, chip_width): """ Calculate the ambiguity function for phase coded waveforms. :param code: The value of each chip (1, -1). :param chip_width: The pulsewidth of each chip (s). :return: The ambiguity function for a phase coded waveform. """ # Upsample factor n_upsample = 100 # Number of Doppler bins n_frequency = 512 # Code length n_code = len(code) # Upsample the code n_samples = n_upsample * n_code # A fast length for the FFT n_fft_samples = next_fast_len(4 * n_samples) # Initialize the upsampled code code_up = zeros([n_fft_samples], dtype=complex) for i in range(n_code): for j in range(n_upsample): code_up[n_upsample * i + j] = code[i] # Create the FFT of the extended sequence v = conj(fft(code_up)) # The time delay s = 0.5 * (n_fft_samples / n_samples) time_delay = linspace(-n_code * chip_width * s, n_code * chip_width * s, n_fft_samples) # The Doppler mismatch frequency doppler_frequency = linspace(-1 / chip_width, 1 / chip_width, n_frequency) # Initialize the ambiguity function ambiguity = zeros([n_frequency, n_fft_samples]) # Create the array of FFTs of the shifted sequence for i in range(n_frequency): phi = 2.0 * pi * doppler_frequency[i] * time_delay u = fft(code_up * exp(1j * phi)) * v ambiguity[i, :] = fftshift(abs(ifft(u, n_fft_samples))) # Normalize the ambiguity function ambiguity /= amax(ambiguity) return ambiguity ** 2, time_delay, doppler_frequency
def sqwlongamp(V,O,Lx,Ly,q,shift,phi,neel): sqn=sc.zeros(sc.shape(V)[0:2],complex) kx,ky=fermisea(Lx,Ly,shift) pkup=phiklong(kx,ky,q[0],q[1],1,[phi,neel]) pkdo=phiklong(kx,ky,q[0],q[1],-1,[phi,neel]) pk=sc.zeros(sc.shape(V)[1],complex) pk[0:2*len(pkup):2]=pkup pk[1:2*len(pkup):2]=pkdo if (abs(q[0])+abs(q[1]))<1e-6 or\ (abs(q[0]-0.5)+abs(q[1]-0.5))<1e-6: if neel!=0: pk[-1]=sc.sum(neel/omega(kx,ky,[phi,neel])) sqn=abs(sc.einsum('ijk,ijl,l->ik',sc.conj(V),O,pk))**2 return sqn
def CenteredLagProduct(rawbeams, numtype=sp.complex128, pulse=sp.ones(14), lagtype='centered'): """ This function will create a centered lag product for each range using the raw IQ given to it. It will form each lag for each pulse and then integrate all of the pulses. Inputs: rawbeams - This is a NpxNs complex numpy array where Ns is number of samples per pulse and Npu is number of pulses N - The number of lags that will be created, default is 14. numtype - The type of numbers used to create the data. Default is sp.complex128 lagtype - Can be centered forward or backward. Output: acf_cent - This is a NrxNl complex numpy array where Nr is number of range gate and Nl is number of lags. """ N = len(pulse) # It will be assumed the data will be pulses vs rangne rawbeams = rawbeams.transpose() (Nr, Np) = rawbeams.shape # Make masks for each piece of data if lagtype == 'forward': arback = sp.zeros(N, dtype=int) arfor = sp.arange(N, dtype=int) elif lagtype == 'backward': arback = sp.arange(N, dtype=int) arfor = sp.zeros(N, dtype=int) else: # arex = sp.arange(0,N/2.0,0.5); arback = -sp.floor(sp.arange(0, N / 2.0, 0.5)).astype(int) arfor = sp.ceil(sp.arange(0, N / 2.0, 0.5)).astype(int) # figure out how much range space will be kept ap = sp.nanmax(abs(arback)) ep = Nr - sp.nanmax(arfor) rng_ar_all = sp.arange(ap, ep) # wearr = (1./(N-sp.tile((arfor-arback)[:,sp.newaxis],(1,Np)))).astype(numtype) #acf_cent = sp.zeros((ep-ap,N))*(1+1j) acf_cent = sp.zeros((ep - ap, N), dtype=numtype) for irng, curange in enumerate(rng_ar_all): rng_ar1 = int(curange) + arback rng_ar2 = int(curange) + arfor # get all of the acfs across pulses # sum along the pulses acf_tmp = sp.conj(rawbeams[rng_ar1, :]) * rawbeams[rng_ar2, :] #*wearr acf_ave = sp.sum(acf_tmp, 1) acf_cent[irng, :] = acf_ave # might need to transpose this return acf_cent
def transitionMatrix(cg, minstrength=0.1): A = gk.CG2adj(cg) edges = scipy.where(A == 1) A[edges] = randweights(edges[0].shape[0], c=minstrength) l = linalg.eig(A)[0] c = 0 pbar = ProgressBar(widgets=['Searching for weights: ', Percentage(), ' '], maxval=10000).start() while max(l*scipy.conj(l)) > 1: A[edges] = randweights(edges[0].shape[0], c=c) c += 1 l = linalg.eig(A)[0] pbar.update(c) pbar.finish() return A
def sqwlongamp(V, O, Lx, Ly, q, shift, phi, neel): sqn = sc.zeros(sc.shape(V)[0:2], complex) kx, ky = fermisea(Lx, Ly, shift) pkup = phiklong(kx, ky, q[0], q[1], 1, [phi, neel]) pkdo = phiklong(kx, ky, q[0], q[1], -1, [phi, neel]) pk = sc.zeros(sc.shape(V)[1], complex) pk[0:2 * len(pkup):2] = pkup pk[1:2 * len(pkup):2] = pkdo if (abs(q[0])+abs(q[1]))<1e-6 or\ (abs(q[0]-0.5)+abs(q[1]-0.5))<1e-6: if neel != 0: pk[-1] = sc.sum(neel / omega(kx, ky, [phi, neel])) sqn = abs(sc.einsum('ijk,ijl,l->ik', sc.conj(V), O, pk))**2 return sqn
def harmonic_deriv(omega, r): """Derivative of a harmonic function using frequency methods. Returns the derivatives of a harmonic function Parameters ---------- omega: float Fundamendal frequency, in rad/sec, of repeating signal r: array | Array of rows of time histories to take the derivative of. | The 1 axis (each row) corresponds to a time history. | The length of the time histories *must be an odd integer*. Returns ------- s: array array of function derivatives. The 1 axis (each row) corresponds to a time history. Notes ----- At this time, the length of the time histories *must be an odd integer*. Examples -------- >>> import matplotlib.pyplot as plt >>> from har_bal import * >>> import scipy as sp >>> from scipy import pi,sin,cos >>> f = 2 >>> omega = 2.*pi * f >>> numsteps = 11 >>> t = sp.arange(0,1/omega*2*pi,1/omega*2*pi/numsteps) >>> x = sp.array([sin(omega*t)]) >>> v = sp.array([omega*cos(omega*t)]) >>> states = sp.append(x,v,axis = 0) >>> state_derives = harmonic_deriv(omega,states) >>> plt.plot(t,states.T,t,state_derives.T,'x') [<matplotlib.line...] """ n = r.shape[1] omega_half = -sp.arange((n - 1) / 2 + 1) * omega * 2j / (n - 2) omega_whole = sp.append(sp.conj(omega_half[-1:0:-1]), omega_half) r_freq = fftp.fft(r) s_freq = r_freq * omega_whole s = fftp.ifft(s_freq) return sp.real(s)
def psd_func(timestream, samplerate=sample_rates.bolo): '''Takes the power spectral density of the input timestream. The format of timestream is a list. It CANNOT be a nested list. The output data is: data[0] is the frequency list data[1] is the psd in units of sqrt(power)/sqrt(Hz) ''' # take the largest power of 2 data points in array for psd # this makes the function quicker if len(array)= power of 2 data = [] # data is a list # make sure timestream has an even number of samples. fft is faster n = len(timestream) # make frequency column delta = 1 / samplerate deltaf = samplerate / n fc = samplerate / 2.0 # critical frequency f = np.array(range(0, n / 2)) frequency = fc * f / (n / 2) # frequency bins frequency = list(frequency) data.append(frequency) # do the fft; throw away negative frequencies PSD = sp.fft(timestream, n) PSD = np.resize(PSD, (n / 2,)) # Do normalization from Numerical Recipes in C pg 551 norm = n * n * deltaf PSD[0] = PSD[0] * sp.conj(PSD[0]) / norm PSD[1: n / 2-1] = 2 * PSD[1:n / 2 - 1] * sp.conj(PSD[1: n / 2 - 1]) / norm PSD[n / 2 - 1] = PSD[n / 2 - 1] * sp.conj(PSD[n / 2 - 1]) / norm # dividing by n**2 makes the sum of the coefficients equal to the # mean squared amplitude of the time stream. multiplying by n*delta = # delta f converts to PSD (ie per Hz) PSD = sp.real(PSD) PSD = list((PSD) ** 0.5) # convert to sqrt(power_rms)/sqrt(Hz) ie Vrms/rtHz data.append(PSD) return data
def kinetic_energy(self, kinetic, summed=False): r""" Calculate the kinetic energy :math:`E_{\text{kin}} := \langle\Psi|T|\Psi\rangle` of the different components. :param kinetic: The kinetic energy operator :math:`T`. :param summed: Whether to sum up the kinetic energies of the individual components. :return: A list with the kinetic energies of the individual components or the overall kinetic energy of the wavefunction. (Depending on the optional arguments.) """ ekin = tuple([ (2.0*pi*self.f) * dot(conj(item),(kinetic*item)) / self.ngn**2 for item in [ fft(component) for component in self.values ] ]) if summed is True: ekin = sum(ekin) return ekin