def run_qag(self, method): def f1(x,y): return Numeric.sin(x) sys = integrate.gsl_function(f1, None) flag, result, error = integrate.qag(sys, 0, Numeric.pi, 1e-8, 1e-8, 1000, method, self.w) assert(Numeric.absolute(result - 2) < 1e-7) assert(error<1e-8)
def main(): parser = argparse.ArgumentParser(description='Simulation of selected and neutral site frequency spectra using the Poisson Random Field Model (PRF)') parser.add_argument('-n', '--nsam', type=int, required=True, dest='sample', help='The sample size') parser.add_argument('-t', '--theta', type=float, required=True, dest='theta', help='The scaled mutation parameter per site') parser.add_argument('-g', '--gamma', type=float, required=True, dest='gamma', help='The scaled selection coefficient (Ns). Can be positive or negative') parser.add_argument('-N', '--Nsites', required=True, type=int, dest='length_S', help = 'Size of region for neutral sites in base pairs to simulate using the PRF [default: 500] ') parser.add_argument('-S', '--Ssites', required=True, type=int, dest='length_N', help = 'Size of region for selected sites in base pairs to simulate using the PRF [default: 500] ') parser.add_argument('-o', '--out', required=True, dest='outfile', help = 'Output file for simulated Neutral and Selected sites site frequency spectra') parser.add_argument('-s', '--sfs', default='folded', required=False, dest='fold', help = 'Specify folded or unfolded [ default: folded]') args = parser.parse_args() n = args.sample Ls_N = args.length_N theta_ls_N = args.theta * Ls_N Ls_S = args.length_S theta_ls_S = args.theta * Ls_S # specified theta per site at input, so multiply by length gamma = args.gamma # gamma in Kai's program is twice that in the Bustamante paper so multiply by a half if args.fold == 'folded': fold = True elif args.fold == 'unfolded': fold = False else: print('Invalid option for -s, it should be folded or unfolded') sys.exit(1) with open(args.outfile, 'w') as outfile: nl = 1 # consider adding option to have multiple replicate of varying size output sfs = [] workspace = integrate.workspace(1000000) if fold: print('S', file=outfile) print(nl, file=outfile) for i in xrange(1, (n + 2) / 2): if gamma == 0: # still print "Selected" sites in output when gamma is zero if i < (n - i): nci = n_choose_i(n, i) neutral_integrand_eq2_func = integrate.gsl_function(neutral_integrand_eq2, [nci, n, i]) F_i_gamma = integrate.qag(neutral_integrand_eq2_func, 0, 1, 1e-8, 1e-8, 1000, integrate.GAUSS61, workspace)[1] nci = n_choose_i(n, n - i) neutral_integrand_eq2_func = integrate.gsl_function(neutral_integrand_eq2, [nci, n, n - i]) F_n_minus_i_gamma = integrate.qag(neutral_integrand_eq2_func, 0, 1, 1e-8, 1e-8, 1000, integrate.GAUSS61, workspace)[1] G_i_gamma = F_i_gamma + F_n_minus_i_gamma # equation 6 condition i < n - i xN = get_sfs(G_i_gamma, theta_ls_N) print(i, G_i_gamma*theta_ls_N) sfs.append(str(xN)) elif i == n / 2: nci = n_choose_i(n, n / 2) neutral_integrand_eq2_func = integrate.gsl_function(neutral_integrand_eq2, [nci, n, n / 2]) F_n_over_two_gamma = integrate.qag(neutral_integrand_eq2_func, 0, 1, 1e-8, 1e-8, 1000, integrate.GAUSS61, workspace)[1] xN = get_sfs(F_n_over_two_gamma, theta_ls_N) print(i, F_n_over_two_gamma * theta_ls_N) sfs.append(str(xN)) elif gamma < 0: if i < (n - i): nci = n_choose_i(n, i) integrand_eq2_func = integrate.gsl_function(integrand_eq2_neg, [gamma, nci, n, i]) F_i_gamma = integrate.qag(integrand_eq2_func, 0, 1, 1e-8, 1e-8, 1000, integrate.GAUSS61, workspace)[1] nci = n_choose_i(n, n - i) integrand_eq2_func = integrate.gsl_function(integrand_eq2_neg, [gamma, nci, n, n - i]) F_n_minus_i_gamma = integrate.qag(integrand_eq2_func, 0, 1, 1e-8, 1e-8, 1000, integrate.GAUSS61, workspace)[1] G_i_gamma = F_i_gamma + F_n_minus_i_gamma # equation 6 condition i < n - i #print(G_i_gamma, F_i_gamma, F_n_minus_i_gamma) xS = get_sfs(G_i_gamma, theta_ls_S) print(i, G_i_gamma * theta_ls_S) sfs.append(str(xS)) elif i == n / 2: # floor division in python 2 nci = n_choose_i(n, n / 2) integrand_eq2_func = integrate.gsl_function(integrand_eq2_neg, [gamma, nci, n, n / 2]) F_n_over_two_gamma = integrate.qag(integrand_eq2_func, 0, 1, 1e-10, 1e-10, 1000, integrate.GAUSS61, workspace)[1] xS = get_sfs(F_n_over_two_gamma , theta_ls_S) #print(F_n_over_two_gamma) print(i, F_n_over_two_gamma * theta_ls_S) sfs.append(str(xS)) else: if i < (n - i): nci = n_choose_i(n, i) integrand_eq2_func = integrate.gsl_function(integrand_eq2, [gamma, nci, n, i]) F_i_gamma = integrate.qag(integrand_eq2_func, 0, 1, 1e-8, 1e-8, 1000, integrate.GAUSS61, workspace)[1] nci = n_choose_i(n, n - i) integrand_eq2_func = integrate.gsl_function(integrand_eq2, [gamma, nci, n, n - i]) F_n_minus_i_gamma = integrate.qag(integrand_eq2_func, 0, 1, 1e-8, 1e-8, 1000, integrate.GAUSS61, workspace)[1] G_i_gamma = F_i_gamma + F_n_minus_i_gamma # equation 6 condition i < n - i xS = get_sfs(G_i_gamma, theta_ls_S) print(i, G_i_gamma * theta_ls_S) sfs.append(str(xS)) elif i == n / 2: # floor division in python 2 nci = n_choose_i(n, n / 2) integrand_eq2_func = integrate.gsl_function(integrand_eq2, [gamma, nci, n, n / 2]) F_n_over_two_gamma = integrate.qag(integrand_eq2_func, 0, 1, 1e-8, 1e-8, 1000, integrate.GAUSS61, workspace)[1] xS = get_sfs(F_n_over_two_gamma , theta_ls_S) print(i, F_n_over_two_gamma * theta_ls_S) sfs.append(str(xS)) sfs_string = ', '.join(sfs) print(n, Ls_S, sfs_string, sep=', ', file=outfile) del sfs[:] # Neutral sites print('N', file=outfile) print(nl, file=outfile) for i in xrange(1, (n + 2) / 2): if i < (n - i): nci = n_choose_i(n, i) neutral_integrand_eq2_func = integrate.gsl_function(neutral_integrand_eq2, [nci, n, i]) F_i_gamma = integrate.qag(neutral_integrand_eq2_func, 0, 1, 1e-8, 1e-8, 1000, integrate.GAUSS61, workspace)[1] nci = n_choose_i(n, n - i) neutral_integrand_eq2_func = integrate.gsl_function(neutral_integrand_eq2, [nci, n, n - i]) F_n_minus_i_gamma = integrate.qag(neutral_integrand_eq2_func, 0, 1, 1e-8, 1e-8, 1000, integrate.GAUSS61, workspace)[1] G_i_gamma = F_i_gamma + F_n_minus_i_gamma # equation 6 condition i < n - i xN = get_sfs(G_i_gamma, theta_ls_N) #print(i, G_i_gamma * theta_ls_N) sfs.append(str(xN)) elif i == n / 2: nci = n_choose_i(n, n / 2) neutral_integrand_eq2_func = integrate.gsl_function(neutral_integrand_eq2, [nci, n, n / 2]) F_n_over_two_gamma = integrate.qag(neutral_integrand_eq2_func, 0, 1, 1e-8, 1e-8, 1000, integrate.GAUSS61, workspace)[1] xN = get_sfs(F_n_over_two_gamma, theta_ls_N) #print(i, F_n_over_two_gamma * theta_ls_N) sfs.append(str(xN)) sfs_string = ', '.join(sfs) print(n, Ls_N, sfs_string, sep=', ', file=outfile) del sfs[:] else: # produce unfolded sfs print('S', file=outfile) print(nl, file=outfile) for i in xrange(1, n): if gamma == 0: nci = n_choose_i(n , i) neutral_integrand_eq2_func = integrate.gsl_function(neutral_integrand_eq2, [nci, n, i]) eq2_eval_neut = integrate.qag(neutral_integrand_eq2_func, 0, 1, 1e-8, 1e-8, 1000, integrate.GAUSS61, workspace)[1] xN = get_sfs(eq2_eval_neut, theta_ls_N) # print(i, xN) sfs.append(str(xN)) elif gamma < 0: nci = n_choose_i(n, i) integrand_eq2_func = integrate.gsl_function(integrand_eq2_neg, [gamma, nci, n, i]) eq2_eval_sel = integrate.qag(integrand_eq2_func, 0, 1, 1e-8, 1e-8, 1000, integrate.GAUSS61, workspace)[1] xS = get_sfs(eq2_eval_sel, theta_ls_S) # print(i, eq2_eval_sel) sfs.append(str(xS)) else: nci = n_choose_i(n, i) integrand_eq2_func = integrate.gsl_function(integrand_eq2, [gamma, nci, n, i]) eq2_eval_sel = integrate.qag(integrand_eq2_func, 0, 1, 1e-8, 1e-8, 1000, integrate.GAUSS61, workspace)[1] xS = get_sfs(eq2_eval_sel, theta_ls_S) # print(i, eq2_eval_sel) sfs.append(str(xS)) sfs_string = ', '.join(sfs) print(n, Ls_S, sfs_string, sep=', ', file=outfile) del sfs[:] print('N', file=outfile) print(nl, file=outfile) for i in xrange(1, n): nci = n_choose_i(n , i) neutral_integrand_eq2_func = integrate.gsl_function(neutral_integrand_eq2, [nci, n, i]) eq2_eval_neut = integrate.qag(neutral_integrand_eq2_func, 0, 1, 1e-8, 1e-8, 1000, integrate.GAUSS61, workspace)[1] xN = get_sfs(eq2_eval_neut, theta_ls_N) # print(i, xN) sfs.append(str(xN)) sfs_string = ', '.join(sfs) print(n, Ls_N, sfs_string, sep=', ', file=outfile) del sfs[:]
def GetSelfEnergyRPADummyMomFrequency(n, omega, kappa, L, asymptoteParams, nbrRTraining=40, orderInterpolate=3, nbrRTest=200, workspaceSize=100, maxBisections=100, epsilonQuad=1.0e-07, epsilonRelQuad=1.0e-04, useInterpolator=True, verbose=False, findEnergy=False): """n: vector of integers characterizing external momentum""" """omega: external frequency OR energy""" """kappa: hopping (eV)""" """L: vector of integers characterizing size of lattice""" """asymptoteParams: tensor of fit parameter characterizing asymptote of \delta \Pi at large frequency""" """nbrRTaining: number of points for training interpolator for integrand""" """nbrRTest: number of points to test integrand""" """workspaceSize: GSL integration workspace size""" """maxBisections: GSL integration number of subdivisions""" """epsilonQuad: absolute error for integration""" """epsilonRelQuad: relative error for integration""" """useInterpolator: use the interpolation routine or explicit evalaution of \delta \Pi""" """verbose: output integrand?""" """findEnergy: searching for energy? i.e. omega \to i\omega (Wick rotation)""" assert(len(n)==2) assert(len(L)==2) assert(len(asymptoteParams.shape)==2) assert(asymptoteParams.shape[0]==L[0]) assert(asymptoteParams.shape[1]==L[1]) prefactor = -1/(4*np.pi*L[0]*L[1]) resultIntegration = np.zeros((int(L[0]),int(L[1]),4)) work = integrate.workspace(workspaceSize) #create workspace for integration bareSigma = GetSelfEnergyBareDummyMom(n,kappa,L) result = 0.0 for n1 in range(int(L[0])): # sum over spatial loop momentum \vec{q} for n2 in range(int(L[1])): # integrate over q_0 for each loop momentum \vec{q} nLoop = np.copy([n1,n2]) print 'GetSelfEnergyRPADummyMomFrequency nLoop:',nLoop pPlusLoop = n+nLoop[:] pMinusLoop = n-nLoop[:] factorPlusLoop = ComputeStructureFactorHexagonalNN(pPlusLoop,L) factorMinusLoop = ComputeStructureFactorHexagonalNN(pMinusLoop,L) w = asymptoteParams[n1,n2] # get parameter which defines change of variables assert(w>0) rMax = 0.5*np.pi/w if useInterpolator: rIntegrandTrain = np.linspace(-rMax,rMax,num=nbrRTraining,endpoint=True) integrandTrain = np.zeros((nbrRTraining,2)) if verbose: rIntegrandTest = np.linspace(-rMax,rMax,num=nbrRTest,endpoint=True) integrandData = np.zeros((nbrRTest,2)) if np.abs(factorPlusLoop) > 1.0e-10: if findEnergy: numReal = lambda r: GetSigmaRPAIntegrandWeight(r,w)*((np.abs(factorPlusLoop)**2-omega**2+w*np.tan(r*w))*GetDifferenceDummyBosonPropagator(nLoop,w*np.tan(r*w),kappa,alpha,L).real + 2*omega*w*np.tan(r*w)*GetDifferenceDummyBosonPropagator(nLoop,w*np.tan(r*w),kappa,alpha,L).imag) denom = lambda r: ((1j*omega+w*np.tan(r*w))**2+np.abs(factorPlusLoop)**2)*((-1j*omega+w*np.tan(r*w))**2+np.abs(factorPlusLoop)**2) realIntegrand1 = lambda r: numReal(r)/denom(r) numImag = lambda r: GetSigmaRPAIntegrandWeight(r,w)*((np.abs(factorPlusLoop)**2-omega**2+w*np.tan(r*w))*GetDifferenceDummyBosonPropagator(nLoop,w*np.tan(r*w),kappa,alpha,L).imag - 2*omega*w*np.tan(r*w)*GetDifferenceDummyBosonPropagator(nLoop,w*np.tan(r*w),kappa,alpha,L).real) imagIntegrand1 = lambda r: numImag(r)/denom(r) else: # \delta \Pi_{1,2}(q_0, \vec{q}) G_{(0);2,1}(p_0+q_0,\vec{p}+\vec{q}) realIntegrand1 = lambda r: GetSigmaRPAIntegrandWeight(r,w)*GetDifferenceDummyBosonPropagator(nLoop,w*np.tan(r*w),kappa,alpha,L).real/((omega+w*np.tan(r*w))**2 + (kappa*np.abs(factorPlusLoop))**2) imagIntegrand1 = lambda r: GetSigmaRPAIntegrandWeight(r,w)*GetDifferenceDummyBosonPropagator(nLoop,w*np.tan(r*w),kappa,alpha,L).imag/((omega+w*np.tan(r*w))**2 + (kappa*np.abs(factorPlusLoop))**2) if useInterpolator: for i in range(nbrRTraining): integrandTrain[i,0] = realIntegrand1(rIntegrandTrain[i]) integrandTrain[i,1] = imagIntegrand1(rIntegrandTrain[i]) realIntegrand1Interp = InterpolationWrappers.MyUnivariateSpline(x=rIntegrandTrain,y=integrandTrain[:,0],name="realIntegrand1",order=orderInterpolate,boundsError=True,verbose=True) imagIntegrand1Interp = InterpolationWrappers.MyUnivariateSpline(x=rIntegrandTrain,y=integrandTrain[:,1],name="imagIntegrand1",order=orderInterpolate,boundsError=True,verbose=True) realIntFuc = integrate.gsl_function(MakeIntFunction(realIntegrand1Interp.EvaluateUnivariateInterpolationPoint), None) #set function to be integrated (real) imagIntFuc = integrate.gsl_function(MakeIntFunction(imagIntegrand1Interp.EvaluateUnivariateInterpolationPoint), None) #set function to be integrated (imag) else: realIntFuc = integrate.gsl_function(MakeIntFunction(realIntegrand1), None) #set function to be integrated (real) imagIntFuc = integrate.gsl_function(MakeIntFunction(imagIntegrand1), None) #set function to be integrated (imag) flag, resultIntegration[n1,n2,0], error = integrate.qag(realIntFuc, -rMax, rMax, epsilonQuad, epsilonRelQuad, maxBisections, integrate.GAUSS61, work) flag, resultIntegration[n1,n2,1], error = integrate.qag(imagIntFuc, -rMax, rMax, epsilonQuad, epsilonRelQuad, maxBisections, integrate.GAUSS61, work) if verbose: for i in range(nbrRTest): if useInterpolator: integrandData[i,0] = realIntegrand1Interp.EvaluateUnivariateInterpolationPoint(rIntegrandTest[i]) integrandData[i,1] = imagIntegrand1Interp.EvaluateUnivariateInterpolationPoint(rIntegrandTest[i]) else: integrandData[i,0] = realIntegrand1(rIntegrandTest[i]) integrandData[i,1] = imagIntegrand1(rIntegrandTest[i]) Output1DGrid("Integrand1_kappa_%g_alpha_%g_P_%d_%d_Q_%d_%d_omega_%g_L_%d_nbrR_%d"%(kappa,alpha,n[0],n[1],nLoop[0],nLoop[1],omega,L[0],nbrRTest), rIntegrandTest,integrandData) result += -kappa*np.conj(factorPlusLoop)*(resultIntegration[n1,n2,0]+1j*resultIntegration[n1,n2,1]) filename = "RPA_INTEGRAL1_P_%d_%d_Q_%d_%d_omega_%e"%(n[0],n[1],nLoop[0],nLoop[1],omega) checkExistingFile(filename) if verbose: with open(filename, "w") as text_file: if useInterpolator: text_file.write("interpolator_result: %.16e %.16e\n"%(resultIntegration[n1,n2,0],resultIntegration[n1,n2,1])) else: text_file.write("exact_result: %.16e %.16e\n"%(resultIntegration[n1,n2,0],resultIntegration[n1,n2,1])) text_file.close() if np.abs(factorMinusLoop) > 1.0e-10: if findEnergy: numReal = lambda r: GetSigmaRPAIntegrandWeight(r,w)*((np.abs(factorMinusLoop)**2-omega**2+w*np.tan(r*w))*GetDifferenceDummyBosonPropagator(nLoop,w*np.tan(r*w),kappa,alpha,L).real - 2*omega*w*np.tan(r*w)*GetDifferenceDummyBosonPropagator(nLoop,w*np.tan(r*w),kappa,alpha,L).imag) denom = lambda r: ((1j*omega-w*np.tan(r*w))**2+np.abs(factorMinusLoop)**2)*((-1j*omega+w*np.tan(r*w))**2-np.abs(factorMinusLoop)**2) realIntegrand2 = lambda r: numReal(r)/denom(r) numImag = lambda r: GetSigmaRPAIntegrandWeight(r,w)*((np.abs(factorMinusLoop)**2-omega**2+w*np.tan(r*w))*GetDifferenceDummyBosonPropagator(nLoop,w*np.tan(r*w),kappa,alpha,L).imag + 2*omega*w*np.tan(r*w)*GetDifferenceDummyBosonPropagator(nLoop,w*np.tan(r*w),kappa,alpha,L).real) imagIntegrand2 = lambda r: numImag(r)/denom(r) else: # \delta \Pi_{2,1}(q_0, \vec{q}) G_{(0);2,1}(p_0-q_0,\vec{p}+\vec{q}) realIntegrand2 = lambda r: GetSigmaRPAIntegrandWeight(r,w)*GetDifferenceDummyBosonPropagator(nLoop,w*np.tan(r*w),kappa,alpha,L).real/((omega-w*np.tan(r*w))**2 + (kappa*np.abs(factorMinusLoop))**2) imagIntegrand2 = lambda r: -GetSigmaRPAIntegrandWeight(r,w)*GetDifferenceDummyBosonPropagator(nLoop,w*np.tan(r*w),kappa,alpha,L).imag/((omega-w*np.tan(r*w))**2 + (kappa*np.abs(factorMinusLoop))**2) if useInterpolator: for i in range(nbrRTraining): integrandTrain[i,0] = realIntegrand2(rIntegrandTrain[i]) integrandTrain[i,1] = imagIntegrand2(rIntegrandTrain[i]) realIntegrand2Interp = InterpolationWrappers.MyUnivariateSpline(x=rIntegrandTrain,y=integrandTrain[:,0],name="realIntegrand2",order=orderInterpolate,boundsError=True,verbose=True) imagIntegrand2Interp = InterpolationWrappers.MyUnivariateSpline(x=rIntegrandTrain,y=integrandTrain[:,1],name="imagIntegrand2",order=orderInterpolate,boundsError=True,verbose=True) realIntFuc = integrate.gsl_function(MakeIntFunction(realIntegrand2Interp.EvaluateUnivariateInterpolationPoint), None) #set function to be integrated (real) imagIntFuc = integrate.gsl_function(MakeIntFunction(imagIntegrand2Interp.EvaluateUnivariateInterpolationPoint), None) #set function to be integrated (imag) else: realIntFuc = integrate.gsl_function(MakeIntFunction(realIntegrand2), None) #set function to be integrated (real) imagIntFuc = integrate.gsl_function(MakeIntFunction(imagIntegrand2), None) #set function to be integrated (imag) flag, resultIntegration[n1,n2,2], error = integrate.qag(realIntFuc, -rMax, rMax, epsilonQuad, epsilonRelQuad, maxBisections, integrate.GAUSS61, work) flag, resultIntegration[n1,n2,3], error = integrate.qag(imagIntFuc, -rMax, rMax, epsilonQuad, epsilonRelQuad, maxBisections, integrate.GAUSS61, work) if verbose: for i in range(nbrRTest): if useInterpolator: integrandData[i,0] = realIntegrand2Interp.EvaluateUnivariateInterpolationPoint(rIntegrandTest[i]) integrandData[i,1] = imagIntegrand2Interp.EvaluateUnivariateInterpolationPoint(rIntegrandTest[i]) else: integrandData[i,0] = realIntegrand2(rIntegrandTest[i]) integrandData[i,1] = imagIntegrand2(rIntegrandTest[i]) Output1DGrid("Integrand2_kappa_%g_alpha_%g_P_%d_%d_Q_%d_%d_omega_%g_L_%d_nbrR_%d"%(kappa,alpha,n[0],n[1],nLoop[0],nLoop[1],omega,L[0],nbrRTest), rIntegrandTest,integrandData) result += -kappa*np.conj(factorMinusLoop)*(resultIntegration[n1,n2,2]+1j*resultIntegration[n1,n2,3]) filename = "RPA_INTEGRAL2_P_%d_%d_Q_%d_%d_omega_%e"%(n[0],n[1],nLoop[0],nLoop[1],omega) checkExistingFile(filename) if verbose: with open(filename, "w") as text_file: if useInterpolator: text_file.write("interpolator_result: %.16e %.16e\n"%(resultIntegration[n1,n2,2],resultIntegration[n1,n2,3])) else: text_file.write("exact_result: %.16e %.16e\n"%(resultIntegration[n1,n2,2],resultIntegration[n1,n2,3])) text_file.close() return prefactor*result+bareSigma