Exemplo n.º 1
0
def run():
    def f2(x,y):
        return numx.sin(x) / x
    sys2 = integrate.gsl_function(f2, None)
    
    def f1(x,y):
        return 1 / x        
    sys1 = integrate.gsl_function(f1, None)
    
    def f3(x,y):
        return 1 / -x
    
    sys3 = integrate.gsl_function(f3, None)

    w = integrate.workspace(1000000)
    cyclew = integrate.workspace(1000000)
    
    table1 = integrate.qawo_table(1, 100, integrate.SINE, 100)
    table2 = integrate.qawo_table(-1, 100, integrate.SINE, 100)

    # Borders and singualrity for gagp
    pts = numx.array((-numx.pi, 0, numx.pi))
    
    flag, result1, error = integrate.qagp(sys2, pts, 1e-8, 1e-8, 100000, w)
    flag, result2, error = integrate.qawf(sys1, numx.pi, 1e-8,  100, w,
                                          cyclew, table1)
    flag, result3, error = integrate.qawf(sys3, numx.pi, 1e-8,  100, w,
                                          cyclew, table2)
    
    print "Result of integration is :", result1 + result2 + result3
Exemplo n.º 2
0
def run():
    def f2(x, y):
        return numx.sin(x) / x

    sys2 = integrate.gsl_function(f2, None)

    def f1(x, y):
        return 1 / x

    sys1 = integrate.gsl_function(f1, None)

    def f3(x, y):
        return 1 / -x

    sys3 = integrate.gsl_function(f3, None)

    w = integrate.workspace(1000000)
    cyclew = integrate.workspace(1000000)

    table1 = integrate.qawo_table(1, 100, integrate.SINE, 100)
    table2 = integrate.qawo_table(-1, 100, integrate.SINE, 100)

    # Borders and singualrity for gagp
    pts = numx.array((-numx.pi, 0, numx.pi))

    flag, result1, error = integrate.qagp(sys2, pts, 1e-8, 1e-8, 100000, w)
    flag, result2, error = integrate.qawf(sys1, numx.pi, 1e-8, 100, w, cyclew,
                                          table1)
    flag, result3, error = integrate.qawf(sys3, numx.pi, 1e-8, 100, w, cyclew,
                                          table2)

    print "Result of integration is :", result1 + result2 + result3
Exemplo n.º 3
0
    def test_qawf(self):
        def f2(x, y):
            return Numeric.sin(x) / x

        sys2 = integrate.gsl_function(f2, None)

        def f1(x, y):
            return 1 / x

        sys1 = integrate.gsl_function(f1, None)

        def f3(x, y):
            return 1 / -x

        sys3 = integrate.gsl_function(f3, None)

        pts = Numeric.array((-Numeric.pi, 0, Numeric.pi))
        flag, result1, error = integrate.qagp(sys2, pts, 1e-8, 1e-8, 100000,
                                              self.w)
        table1 = integrate.qawo_table(1, 100, integrate.SINE, 100)
        cyclew = integrate.workspace(1000000)
        flag, result2, error = integrate.qawf(sys1, Numeric.pi, 1e-8, 100,
                                              self.w, cyclew, table1)
        table2 = integrate.qawo_table(-1, 100, integrate.SINE, 100)
        flag, result3, error = integrate.qawf(sys3, Numeric.pi, 1e-8, 100,
                                              self.w, cyclew, table2)
        assert (Numeric.absolute(result1 + result2 + result3 - Numeric.pi) <
                1e-8)
Exemplo n.º 4
0
 def test_qng(self):
     def f1(x,y):
         return Numeric.sin(x)
     sys = integrate.gsl_function(f1, None)
     flag, result, error, method = integrate.qng(sys, 0, Numeric.pi, 1e-8, 1e-8)
     assert(Numeric.absolute(result - 2) < 1e-7)
     assert(error<1e-8)
Exemplo n.º 5
0
def calc_vavg(tau,A,m,n,N0,Nz,c,phi,sigma=False):
    """Calculating average sediment velocities.
    
    tau: basal shear stress
    A: flow law factor
    m: exponent of effective pressure
    n: exponent of basal shear stress
    N0: effective pressure
    Nz: effective pressure gradient
    c: cohesion
    phi: angle of internal friction"""

    za = calc_za(tau,N0,Nz,c,phi)
    v = numpy.zeros(len(tau),numpy.float)
    
    if sigma:
        f = flow2
    else:
        f = flow1

    for i in range(0,len(v)):
        sys = integrate.gsl_function(f,[tau[i],A,m,n,N0,Nz,c,phi,0.])
        flag,result,error,num = integrate.qng(sys,za[i],0.,1e-6, 1e-6)
        if flag != 0:
            print flag
        if za[i]!=0:
            v[i] = -result/za[i]
    return v    
Exemplo n.º 6
0
 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)
Exemplo n.º 7
0
 def test_qawo(self):
     def f(x,y):
         return 1
     sys = integrate.gsl_function(f, None)
     table = integrate.qawo_table(1, 2*Numeric.pi, integrate.COSINE, 100)
     flag, result, error = integrate.qawo(sys, -Numeric.pi, 1e-8,  1e-8, 100, self.w, table)
     assert(Numeric.absolute(result) < 1e-7)
     assert(Numeric.absolute(error) < 1e-7)
Exemplo n.º 8
0
 def test_qagp(self):
     def f1(x,y):
         return x / x
     sys = integrate.gsl_function(f1, None)
     pts = Numeric.array((-1, 0, 1))
     flag, result, error = integrate.qagp(sys, pts, 1e-8, 1e-8, 100000, self.w)
     assert(Numeric.absolute(result - 2.) < 1e-3)
     assert(error<1e-8)
Exemplo n.º 9
0
    def test_no_object_returned(self):
        """Test that the user is flagged an error if no object is returned
        """
        def f1(x, *args):
            return None

        sys = integrate.gsl_function(f1, None)
        self.assertRaises(pygsl.errors.gsl_BadFuncError, integrate.qng, sys, 0,
                          Numeric.pi, 1e-8, 1e-8)
Exemplo n.º 10
0
def calc_vsld(tau,A,m,n,N0,Nz,c,phi,sigma=False):

    za = calc_za(tau,N0,Nz,c,phi)
    v = Numeric.zeros(len(tau),Numeric.Float)

    if sigma:
        f = flow2
    else:
        f = flow1

    for i in range(0,len(v)):
        sys = integrate.gsl_function(f,[tau[i],A,m,n,N0,Nz,c,phi,None])
        sys = integrate.gsl_function(flow1,[tau[i],A,m,n,N0,Nz,c,phi,None])
        flag,result,error,num = integrate.qng(sys,za[i],0.,1e-8, 1e-8)
        if flag != 0:
            print flag
        v[i] = result
    return v
Exemplo n.º 11
0
 def test_0_qagiu(self):
     expected = 1./2.
     def f1(x,y):
         return 1. / (1.* x**2)
     
     sys = integrate.gsl_function(f1, None)
     flag, result, error = integrate.qagiu(sys, 2, 1e-8, 1e-8, 1000000, self.w)
     assert(Numeric.absolute(result - expected) < 1e-7)
     assert(Numeric.absolute(error) < 1e-7)
     self.w.get_size()
Exemplo n.º 12
0
 def test_qawf(self):
     def f2(x,y):
         return Numeric.sin(x) / x
     sys2 = integrate.gsl_function(f2, None)
     def f1(x,y):
         return 1 / x        
     sys1 = integrate.gsl_function(f1, None)
     def f3(x,y):
         return 1 / -x        
     sys3 = integrate.gsl_function(f3, None)
     
     pts = Numeric.array((-Numeric.pi, 0, Numeric.pi))
     flag, result1, error = integrate.qagp(sys2, pts, 1e-8, 1e-8, 100000, self.w)
     table1 = integrate.qawo_table(1, 100, integrate.SINE, 100)        
     cyclew = integrate.workspace(1000000)
     flag, result2, error = integrate.qawf(sys1, Numeric.pi, 1e-8,  100, self.w, cyclew, table1)
     table2 = integrate.qawo_table(-1, 100, integrate.SINE, 100)        
     flag, result3, error = integrate.qawf(sys3, Numeric.pi, 1e-8,  100, self.w, cyclew, table2)
     assert(Numeric.absolute(result1+result2+result3 - Numeric.pi) < 1e-8)
Exemplo n.º 13
0
 def test_1_qags(self):
     expected = -4.0
     def f(x, params):
         alpha = params
         return Numeric.log(alpha *x) / Numeric.sqrt(x)
     self.sys = integrate.gsl_function(f, 1)
     flag, result, error = integrate.qags(self.sys, 0, 1, 0, 1e-7, 1000,
                                          self.w, )
     assert(Numeric.absolute(result - expected) < 1e-7)
     assert(Numeric.absolute(error) < 1e-7)
     self.w.get_size()
Exemplo n.º 14
0
def II(x, a, t, method=5):
    if method == 0:
        sys = integrate.gsl_function(cdf, (a, t))
        integral = integrate.qagp(sys, [0., x], 1e-8, 1e-7, 100, w2)
    elif method == 2:
        integral = quad(cdf_eta, 1e-8, x, args=(a, t))
    elif method == 3:
        integral = x * cdf_eta(x, a, t) - quad(xpdf, 1e-10, x, args=(a, t))[0] 
    elif method == 4:
        phi = a + 2 * sqrt(t) * erfinv(2. * x - 1.)
        integral = x * cdf_phi(phi, a, t) - quad(xr, -12., phi, args=(a, t))[0]
    elif method == 5:
        phi = a + 2 * sqrt(t) * erfinv(2. * x - 1.)
        integral = x / 2. * (1. + erf(phi / sqrt(2. * (1. - 2. * t)))) - quad(xr, -Inf, phi, args=(a, t))[0] 
    return integral
Exemplo n.º 15
0
def II(x, a, t, method=5):
    if method == 0:
        sys = integrate.gsl_function(cdf, (a, t))
        integral = integrate.qagp(sys, [0., x], 1e-8, 1e-7, 100, w2)
    elif method == 2:
        integral = quad(cdf_eta, 1e-8, x, args=(a, t))
    elif method == 3:
        integral = x * cdf_eta(x, a, t) - quad(xpdf, 1e-10, x, args=(a, t))[0]
    elif method == 4:
        phi = a + 2 * sqrt(t) * erfinv(2. * x - 1.)
        integral = x * cdf_phi(phi, a, t) - quad(xr, -12., phi, args=(a, t))[0]
    elif method == 5:
        phi = a + 2 * sqrt(t) * erfinv(2. * x - 1.)
        integral = x / 2. * (1. + erf(phi / sqrt(2. * (1. - 2. * t)))) - quad(
            xr, -Inf, phi, args=(a, t))[0]
    return integral
Exemplo n.º 16
0
def calc_vsld(tau,A,m,n,N0,Nz,c,phi,sigma=False):

    za = calc_za(tau,N0,Nz,c,phi)
    v = numpy.zeros(len(tau),numpy.float)

    if sigma:
        f = flow2
    else:
        f = flow1

    for i in range(0,len(v)):
        sys = integrate.gsl_function(f,[tau[i],A,m,n,N0,Nz,c,phi,None])
        flag,result,error,num = integrate.qng(sys,za[i],0.,1e-8, 1e-8)
        if flag != 0:
            print flag
        v[i] = result
    return v
Exemplo n.º 17
0
    def test_0_qagil(self):
        expected = 1. / 2.

        def f1(x, y):
            return 1. / (1. * x**2)

        sys = integrate.gsl_function(f1, None)
        test = 0
        try:
            flag, result, error = integrate.qagil(sys, -2, 1e-8, 1e-8, 1000000,
                                                  self.w)
            test = 1
        finally:
            if test == 0:
                print(integrate.qagil(sys, -2, 1e-8, 1e-8, 1000000, self.w))
        assert (Numeric.absolute(result - expected) < 1e-7)
        assert (Numeric.absolute(error) < 1e-7)
        self.w.get_size()
Exemplo n.º 18
0
def run_fail():
    """Demonstrates pygsl capabilites in finding problems with callbacks
    """
    def f1(x, *args):
        return None

    import pygsl

    sys = integrate.gsl_function(f1, None)

    # Enables printing debug messages. The higher the level the more information
    # will be displayed
    #pygsl.set_debug_level(3)

    # Quite a few functions add traceback frames when they propage the error
    # through the different levels. If you can not understand the error messages
    # directly, looking at the source where the error occured can help.
    #pygsl.add_c_traceback_frames(True)
    flag, result, error, method = integrate.qng(sys, 0, numx.pi, 1e-8, 1e-8)
    pygsl.set_debug_level(0)
Exemplo n.º 19
0
 def getage(self,z): 
  """Look-back time as a function of redhshift.  Returns time in tunit.  
     Hogg paper Equation 30.
  """
  def agefunc(z2,y):
   return 1./ (self.epeebles(z2)*(1.+z2))
  
  #gsl baggage
  gsl_agefunc=integ.gsl_function(agefunc,None) #extra pygsl baggage
  w=integ.workspace(1000000)

  try: #check if z is list or array
   output=[]
   for zz in z:
    flag,result,error=integ.qagiu(gsl_agefunc,zz,1e-8,1e-8,100000,w) 
    output.append(self.thubble()*result)
   output=numpy.array(output)
   return output
  except TypeError: #z is single value
   flag,result,error=integ.qagiu(gsl_agefunc,z,1e-8,1e-8,100000,w) 
   output=self.thubble()*result
  return output
Exemplo n.º 20
0
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
Exemplo n.º 21
0
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[:]
Exemplo n.º 22
0
    xx = 0.5 * (1 + erf((phi - a) / 2. / sqrt(t)))
    return xx * r(phi, a, t)
        
def X(phi, a, t):
    return 0.5 * (1 + erf((phi - a) / 2. / sqrt(t)))

def phi(x, a, t):
    return a + 2 * sqrt(t) * erfinv(2 * x - 1)
    
def integrand(phi, a, t):
    sr = sqrt(1. - 2. * t)
    x = 0.5 * (1 + erf((sr * phi - a) / sqrt(1. - sr * sr) / sqrt(2.)))
    return x * x * exp(- phi * phi / 2.)

def cdf(x, (a, t)):
    sys = integrate.gsl_function(pdf, (a, t))
    flag, result, error = integrate.qagp(sys, [0., x], 1e-8, 1e-7, 100, w1)
    return result
 
def cdf_eta(x, a, t):
    return quad(pdf, 1e-10, x, args=(a, t))[0]

def cdf_phi(x, a, t):
    return quad(r, -12., x, args=(a, t))[0]
    
def II(x, a, t, method=5):
    if method == 0:
        sys = integrate.gsl_function(cdf, (a, t))
        integral = integrate.qagp(sys, [0., x], 1e-8, 1e-7, 100, w2)
    elif method == 2:
        integral = quad(cdf_eta, 1e-8, x, args=(a, t))
Exemplo n.º 23
0
def X(phi, a, t):
    return 0.5 * (1 + erf((phi - a) / 2. / sqrt(t)))


def phi(x, a, t):
    return a + 2 * sqrt(t) * erfinv(2 * x - 1)


def integrand(phi, a, t):
    sr = sqrt(1. - 2. * t)
    x = 0.5 * (1 + erf((sr * phi - a) / sqrt(1. - sr * sr) / sqrt(2.)))
    return x * x * exp(-phi * phi / 2.)


def cdf(x, (a, t)):
    sys = integrate.gsl_function(pdf, (a, t))
    flag, result, error = integrate.qagp(sys, [0., x], 1e-8, 1e-7, 100, w1)
    return result


def cdf_eta(x, a, t):
    return quad(pdf, 1e-10, x, args=(a, t))[0]


def cdf_phi(x, a, t):
    return quad(r, -12., x, args=(a, t))[0]


def II(x, a, t, method=5):
    if method == 0:
        sys = integrate.gsl_function(cdf, (a, t))