Exemple #1
0
def cos_square_avg(J):
     global tol
     global nint
     norm,error1 = quadrature(func_norm,0,pi,args=(J,),tol=tol,maxiter=nint)
     avg,error2 = quadrature(func_avg,0,pi,args=(J,),tol=tol,maxiter=nint)
     avg *= 1.0/norm
     return avg
Exemple #2
0
def complex_integral(func,a,b,args,intype='stupid'):
    real_func = lambda z: np.real(func(z,*args))
    imag_func = lambda z: np.imag(func(z,*args))
    if intype == 'quad':
        real_int = integ.quad(real_func,a,b)
        imag_int = integ.quad(imag_func,a,b)
#        print(real_int)
#        print(imag_int)
        return real_int[0] + 1j * imag_int[0]
    elif intype == 'quadrature':
        real_int = integ.quadrature(real_func,a,b)
        imag_int = integ.quadrature(imag_func,a,b)
#        print(real_int)
#        print(imag_int)
        return real_int[0] + 1j * imag_int[0]
    elif intype == 'romberg':
        real_int = integ.romberg(real_func,a,b)
        imag_int = integ.romberg(imag_func,a,b)
#        print(real_int)
#        print(imag_int)
        return real_int + 1j * imag_int
    elif intype == 'stupid':
        Npoints = 500
        z,dz = np.linspace(a,b,Npoints,retstep=True)
        real_int = np.sum(real_func(z))*dz
        imag_int = np.sum(imag_func(z))*dz
#        print(real_int)
#        print(imag_int)
        return real_int + 1j*imag_int
Exemple #3
0
 def TR(self,**kwargs):
     """
     NAME:
        TR
     PURPOSE:
        Calculate the radial period for a flat rotation curve
     INPUT:
        scipy.integrate.quadrature keywords
     OUTPUT:
        T_R(R,vT,vT)*vc/ro + estimate of the error
     HISTORY:
        2010-05-13 - Written - Bovy (NYU)
     """
     if hasattr(self,'_TR'):
         return self._TR
     (rperi,rap)= self.calcRapRperi()
     if rap == rperi: #Rough limit
         #TR=kappa
         kappa= m.sqrt(2.)/self._R
         self._TR= nu.array([2.*m.pi/kappa,0.])
         return self._TR
     Rmean= m.exp((m.log(rperi)+m.log(rap))/2.)
     TR= 0.
     if Rmean > rperi:
         TR+= rperi*nu.array(integrate.quadrature(_TRFlatIntegrandSmall,
                                                  0.,m.sqrt(Rmean/rperi-1.),
                                                  args=((self._R*self._vT)**2/rperi**2.,),
                                                  **kwargs))
     if Rmean < rap:
         TR+= rap*nu.array(integrate.quadrature(_TRFlatIntegrandLarge,
                                                0.,m.sqrt(1.-Rmean/rap),
                                                args=((self._R*self._vT)**2/rap**2.,),
                                                **kwargs))
     self._TR= m.sqrt(2.)*TR
     return self._TR
 def TR(self,**kwargs): #pragma: no cover
     """
     NAME:
        TR
     PURPOSE:
        Calculate the radial period for a power-law rotation curve
     INPUT:
        scipy.integrate.quadrature keywords
     OUTPUT:
        T_R(R,vT,vT)*vc/ro + estimate of the error
     HISTORY:
        2010-12-01 - Written - Bovy (NYU)
     """
     if hasattr(self,'_TR'):
         return self._TR
     (rperi,rap)= self.calcRapRperi(**kwargs)
     if nu.fabs(rap-rperi)/rap < 10.**-4.: #Rough limit
         self._TR= 2.*m.pi/epifreq(self._pot,self._R,use_physical=False)
         return self._TR
     Rmean= m.exp((m.log(rperi)+m.log(rap))/2.)
     EL= self.calcEL(**kwargs)
     E, L= EL
     TR= 0.
     if Rmean > rperi:
         TR+= integrate.quadrature(_TRAxiIntegrandSmall,
                                   0.,m.sqrt(Rmean-rperi),
                                   args=(E,L,self._pot,rperi),
                                   **kwargs)[0]
     if Rmean < rap:
         TR+= integrate.quadrature(_TRAxiIntegrandLarge,
                                   0.,m.sqrt(rap-Rmean),
                                   args=(E,L,self._pot,rap),
                                   **kwargs)[0]
     self._TR= 2.*TR
     return self._TR
Exemple #5
0
 def _calc_or(self,Rmean,rperi,rap,E,L,fixed_quad,**kwargs):
     Tr= 0.
     if Rmean > rperi and not fixed_quad:
         Tr+= nu.array(integrate.quadrature(_TrSphericalIntegrandSmall,
                                            0.,m.sqrt(Rmean-rperi),
                                            args=(E,L,self._2dpot,
                                                  rperi),
                                            **kwargs))[0]
     elif Rmean > rperi and fixed_quad:
         Tr+= integrate.fixed_quad(_TrSphericalIntegrandSmall,
                                   0.,m.sqrt(Rmean-rperi),
                                   args=(E,L,self._2dpot,
                                         rperi),
                                   n=10,**kwargs)[0]
     if Rmean < rap and not fixed_quad:
         Tr+= nu.array(integrate.quadrature(_TrSphericalIntegrandLarge,
                                            0.,m.sqrt(rap-Rmean),
                                            args=(E,L,self._2dpot,
                                                  rap),
                                            **kwargs))[0]
     elif Rmean < rap and fixed_quad:
         Tr+= integrate.fixed_quad(_TrSphericalIntegrandLarge,
                                   0.,m.sqrt(rap-Rmean),
                                   args=(E,L,self._2dpot,
                                         rap),
                                   n=10,**kwargs)[0]
     Tr= 2.*Tr
     return 2.*nu.pi/Tr
Exemple #6
0
 def _calc_angler(self,Or,r,Rmean,rperi,rap,E,L,vr,fixed_quad,**kwargs):
     if r < Rmean:
         if r > rperi and not fixed_quad:
             wr= Or*integrate.quadrature(_TrSphericalIntegrandSmall,
                                         0.,m.sqrt(r-rperi),
                                         args=(E,L,self._2dpot,rperi),
                                         **kwargs)[0]
         elif r > rperi and fixed_quad:
             wr= Or*integrate.fixed_quad(_TrSphericalIntegrandSmall,
                                         0.,m.sqrt(r-rperi),
                                         args=(E,L,self._2dpot,rperi),
                                         n=10,**kwargs)[0]
         else:
             wr= 0.
         if vr < 0.: wr= 2*m.pi-wr
     else:
         if r < rap and not fixed_quad:
             wr= Or*integrate.quadrature(_TrSphericalIntegrandLarge,
                                         0.,m.sqrt(rap-r),
                                         args=(E,L,self._2dpot,rap),
                                         **kwargs)[0]
         elif r < rap and fixed_quad:
             wr= Or*integrate.fixed_quad(_TrSphericalIntegrandLarge,
                                         0.,m.sqrt(rap-r),
                                         args=(E,L,self._2dpot,rap),
                                         n=10,**kwargs)[0]
         else:
             wr= m.pi
         if vr < 0.:
             wr= m.pi+wr
         else:
             wr= m.pi-wr
     return wr
Exemple #7
0
 def _calc_op(self,Or,Rmean,rperi,rap,E,L,fixed_quad,**kwargs):
     #Azimuthal period
     I= 0.
     if Rmean > rperi and not fixed_quad:
         I+= nu.array(integrate.quadrature(_ISphericalIntegrandSmall,
                                           0.,m.sqrt(Rmean-rperi),
                                           args=(E,L,self._2dpot,
                                                 rperi),
                                           **kwargs))[0]
     elif Rmean > rperi and fixed_quad:
         I+= integrate.fixed_quad(_ISphericalIntegrandSmall,
                                  0.,m.sqrt(Rmean-rperi),
                                  args=(E,L,self._2dpot,rperi),
                                  n=10,**kwargs)[0]
     if Rmean < rap and not fixed_quad:
         I+= nu.array(integrate.quadrature(_ISphericalIntegrandLarge,
                                           0.,m.sqrt(rap-Rmean),
                                           args=(E,L,self._2dpot,
                                                 rap),
                                           **kwargs))[0]
     elif Rmean < rap and fixed_quad:
         I+= integrate.fixed_quad(_ISphericalIntegrandLarge,
                                  0.,m.sqrt(rap-Rmean),
                                  args=(E,L,self._2dpot,rap),
                                  n=10,**kwargs)[0]
     I*= 2*L
     return I*Or/2./nu.pi
def p_avg(x):
     global tol
     global nint
     norm,error1 = quadrature(func_norm,-1,1,args=(x,),tol=tol,maxiter=nint)
     avg,error2 = quadrature(func_avg,-1,1,args=(x,),tol=tol,maxiter=nint)
     avg *= 1.0/norm
     return avg
Exemple #9
0
def p_avg(p0,a1,a3,Ex,T,tol=1.0e-3,maxiter=50):
     args=(p0,a1,a3,Ex,T)
     norm,error_norm = quadrature(kernel,0,pi,args=args,tol=tol,maxiter=maxiter)
     cos_avg,error_cos = quadrature(func_cos_avg,0,pi,args=args,tol=tol,maxiter=maxiter)
     cos_square_avg,error_cos_sqr = quadrature(func_cos_sqr_avg,0,pi,args=args,tol=tol,maxiter=maxiter)
     cos_avg *= 1.0/norm
     cos_square_avg *= 1.0/norm
     return p0*cos_avg + (a1 + (a3 - a1)*cos_square_avg)*Ex 
Exemple #10
0
 def _calc_anglez(self,Or,Op,ar,z,r,Rmean,rperi,rap,E,L,Lz,vr,axivz,
                  fixed_quad,**kwargs):
     #First calculate psi
     i= nu.arccos(Lz/L)
     sinpsi= z/r/nu.sin(i)
     if sinpsi > 1. and sinpsi < (1.+10.**-7.):
         sinpsi= 1.
     if sinpsi < -1. and sinpsi > (-1.-10.**-7.):
         sinpsi= -1.
     psi= nu.arcsin(sinpsi)
     if axivz > 0.: psi= nu.pi-psi
     psi= psi % (2.*nu.pi)
     #Calculate dSr/dL
     dpsi= Op/Or*2.*nu.pi #this is the full I integral
     if r < Rmean:
         if not fixed_quad:
             wz= L*integrate.quadrature(_ISphericalIntegrandSmall,
                                        0.,m.sqrt(r-rperi),
                                        args=(E,L,self._2dpot,
                                              rperi),
                                        **kwargs)[0]
         elif fixed_quad:
             wz= L*integrate.fixed_quad(_ISphericalIntegrandSmall,
                                        0.,m.sqrt(r-rperi),
                                        args=(E,L,self._2dpot,
                                              rperi),
                                        n=10,**kwargs)[0]
         if vr < 0.: wz= dpsi-wz
     else:
         if not fixed_quad:
             wz= L*integrate.quadrature(_ISphericalIntegrandLarge,
                                        0.,m.sqrt(rap-r),
                                        args=(E,L,self._2dpot,
                                              rap),
                                        **kwargs)[0]
         elif fixed_quad:
             wz= L*integrate.fixed_quad(_ISphericalIntegrandLarge,
                                        0.,m.sqrt(rap-r),
                                        args=(E,L,self._2dpot,
                                              rap),
                                        n=10,**kwargs)[0]
         if vr < 0.:
             wz= dpsi/2.+wz
         else:
             wz= dpsi/2.-wz
     #Add everything
     wz= -wz+psi+Op/Or*ar
     return wz
def find_gb_omega(omega, energy_low, energy_high, system, efermi, temp, delta):
	"""
	Integrate gb_integrand function over range of energies to find Gilbert damping
	"""
	scaling = 1 / omega
	out = (delta**2)*(scaling) * integrate.quadrature(lambda energy: gb_integrand(energy,omega,system,efermi,temp), energy_low, energy_high, vec_func = False,tol=10e-5)[0]
	return out
Exemple #12
0
def c(ni, nf): # eigenfunctions are real
    return integrate.quadrature(
        lambda x: eigen_f(nf, x) * eigen_i(ni, x), # < bra | ket >
        0., pi,
        rtol=1e-5, maxiter=1000,
        vec_func=False
    )
Exemple #13
0
def luminosity_distance(z, k=0):
    ''' Calculate the luminosity distance for a given redshift.
    
    Parameters:
        * z (float or array): the redshift(s)
        * k = 0 (float): the curvature constant.
        
    Returns:
        The luminosity distance in Mpc
     '''

    if not (type(z) is np.ndarray): #Allow for passing a single z
        z = np.array([z])
    n = len(z)

    if const.lam == 0:
        denom = np.sqrt(1+2*const.q0*z) + 1 + const.q0*z 
        dlum = (const.c*z/const.H0)*(1 + z*(1-const.q0)/denom)
        return dlum
    else:
        dlum = np.zeros(n)
        for i in xrange(n):
            if z[i] <= 0:
                dlum[i] = 0.0
            else:
                dlum[i] = quadrature(_ldist, 0, z[i])[0]

    if k > 0:
        dlum = np.sinh(np.sqrt(k)*dlum)/np.sqrt(k)
    elif k < 0:
        dlum = np.sin(np.sqrt(-k)*dlum)/np.sqrt(-k)
    return outputify(const.c*(1+z)*dlum/const.H0)
Exemple #14
0
def ps_to_xi(k,ps,r,precision='mid'):
    xi = 0 * r
    if precision=='low':
        from scipy.integrate import trapz
        from scipy import sin
        
        for i in range(len(r)):
            xi[i] = trapz((ps/k) * sin(k*r[i]) / (k*r[i]),k)
    
    elif precision=='high':
        from scipy import sin
        from scipy.integrate import quad,quadrature
        from scipy.interpolate import interp1d
        for i in range(len(r)):
            psi = interp1d(k,ps)
            core = lambda k: (psi(k)/k) * sin(k*r[i]) / (k*r[i])
            A = quadrature(core,min(k),2.0/r[i],tol=1e-3)
            xi[i] = A[0]
        
    else:
        from scipy.integrate import trapz
        from scipy import sin
        from pylab import find
        import numpy as np
        for i in range(len(r)):
            cutoff = np.min(find(k>2.0/r[i]))
            kl = k[1:cutoff]
            psl = ps[1:cutoff]
            i1 = trapz((psl/kl) * sin(kl*r[i]) / (kl*r[i]),kl)
            psh = ps[cutoff+1:len(k)]
            kh = k[cutoff+1:len(k)]
            i2 = trapz((psh/kh) * sin(kh*r[i]) / (kh*r[i]),kh)
            xi[i] = i1+i2
                         
    return xi
    def get_mmax(self, catalogue, config):
        '''Calculate mmax
        
        :return: **mmax** Maximum magnitude and **mmax_sig** corresponding
                    uncertainty
        :rtype: Float
        '''

        obsmax, obsmaxsig = _get_observed_mmax(catalogue, config)
        
        mmin = config['input_mmin']
        beta = config['b-value'] * np.log(10.)
       
        neq, mmin = _get_magnitude_vector_properties(catalogue, config)
        
        mmax = deepcopy(obsmax) 
        d_t = np.inf
        iterator = 0
        while d_t > config['tolerance']:
            delta = quadrature(_ks_intfunc, mmin, mmax, 
                               args = [neq, mmax, mmin, beta])[0]
            #print mmin, neq, delta, mmax
            tmmax = obsmax + delta
            d_t = np.abs(tmmax - mmax)
            mmax = deepcopy(tmmax)
            iterator += 1
            if iterator > config['maximum_iterations']:
                print 'Kijko-Sellevol estimator reached maximum # of iterations'
                d_t = -np.inf
        return mmax, np.sqrt(obsmaxsig ** 2. + delta ** 2.)      
    def get_mmax(self, catalogue, config):
        '''Calculate maximum magnitude
        :return: **mmax** Maximum magnitude and **mmax_sig** corresponding
                    uncertainty
        :rtype: Float
        '''
        obsmax, obsmaxsig = _get_observed_mmax(catalogue, config)
        
        beta = config['b-value'] * np.log(10.)
        sigbeta = config['sigma-b'] * np.log(10.)

        neq, mmin = _get_magnitude_vector_properties(catalogue, config)

        pval = beta / (sigbeta ** 2.)
        qval = (beta / sigbeta) ** 2.
        
        mmax = deepcopy(obsmax) 
        d_t = np.inf
        iterator = 0
        while d_t > config['tolerance']:
            rval = pval / (pval + mmax - mmin)
            ldelt = (1. / (1. - (rval ** qval))) ** neq
            delta = ldelt * quadrature(_ksb_intfunc, mmin, mmax, 
                                       args = [neq, mmin, pval, qval])[0]

            tmmax = obsmax + delta
            d_t = np.abs(tmmax - mmax)
            mmax = deepcopy(tmmax)
            iterator += 1
            if iterator > config['max_iterations']:
                print 'Kijko-Sellevol-Bayes estimator reached'
                print 'maximum # of iterations'
                d_t = -np.inf
        
        return mmax, np.sqrt(obsmaxsig ** 2. + delta ** 2.)        
    def CalculateEnergyFlux(self,modelName,params):

        model = self.eFluxModels[modelName]
        #self.shit=params
        #print params
        try:
           args=params.tolist()
                
        except(AttributeError):
  
            args = tuple(params)
        #print args
        if (modelName == 'Band\'s GRB, Epeak') or (modelName =='Power Law w. 2 Breaks') or (modelName =='Broken Power Law'):

            
            
            
            val,_, = quadrature(model, self.eMin,self.eMax,args=args,tol=1.49e-10, rtol=1.49e-10, maxiter=200)
            val = val*keV2erg
            return val
            

        val,_, = quad(model, self.eMin,self.eMax,args=args[0], epsrel= 1.e-8 )

        
        val = val*keV2erg
        

        return val
def comoving_distance(z,cosmo=None):
    """
    Calculate the line of sight comoving distance
    
    parameters
    ----------
    z: float
        redshift
    
    cosmo: astropy.cosmology object, optional
        cosmology object specifying cosmology.  If None,  FlatLambdaCDM(H0=70,Om0=0.3)
    
    returns
    -------
    DC: float
        Comoving line of sight distance in Mpc
    """
    
    if cosmo==None:
        cosmo = astropy.cosmology.FlatLambdaCDM(H0=70, Om0=0.3)
    
    f = lambda zz: 1.0/_Ez(zz, cosmo.Om0, cosmo.Ok0, cosmo.Ode0)
    DC = integrate.quadrature(f,0.0,z)[0]
    
    return hubble_distance(cosmo.H0.value)*DC
    def test_quadrature_rtol(self):
        def myfunc(x, n, z):  # Bessel function integrand
            return 1e90 * cos(n * x - z * sin(x)) / pi

        val, err = quadrature(myfunc, 0, pi, (2, 1.8), rtol=1e-10)
        table_val = 1e90 * 0.30614353532540296487
        assert_allclose(val, table_val, rtol=1e-10)
def comoving_volume(z,dw,cosmo=None):
    """
    Calculate comoving volume
    
    parameters
    ----------
    z: float
        redshift
    
    dw: float
        solid angle
    
    cosmo: astropy.cosmology object, optional
        cosmology object specifying cosmology.  If None,  FlatLambdaCDM(H0=70,Om0=0.3)
    
    returns
    -------
    VC: float
        comoving volume in Mpc^3
    """

    if cosmo==None:
        cosmo = astropy.cosmology.FlatLambdaCDM(H0=70, Om0=0.3)

    DH = hubble_distance(cosmo.H0.value) 
    f = lambda zz: DH*((1.0+zz)**2.0*angular_diameter_distance(zz,cosmo)**2.0)/(_Ez(zz, cosmo.Om0, cosmo.Ok0, cosmo.Ode0))

    VC = integrate.quadrature(f,0.0,z,vec_func=False)[0]*dw
    
    return VC
Exemple #21
0
 def test_quadrature(self):
     # Typical function with two extra arguments:
     def myfunc(x, n, z):       # Bessel function integrand
         return cos(n*x-z*sin(x))/pi
     val, err = quadrature(myfunc, 0, pi, (2, 1.8))
     table_val = 0.30614353532540296487
     assert_almost_equal(val, table_val, decimal=7)
Exemple #22
0
    def test_quadrature_single_args(self):
        def myfunc(x, n):
            return 1e90 * cos(n * x - 1.8 * sin(x)) / pi

        val, err = quadrature(myfunc, 0, pi, args=2, rtol=1e-10)
        table_val = 1e90 * 0.30614353532540296487
        assert_allclose(val, table_val, rtol=1e-10)
Exemple #23
0
def lumdist(z, k=0):
	''' Calculate the luminosity distance for redshift z 

	Parameters:
		* z (float or numpy array): the redshift or redshifts

	Returns:
		The luminosity distance(s) in Mpc
	'''

	if not (type(z) is np.ndarray): #Allow for passing a single z
		z = np.array([z])
	n = len(z)

	if lam == 0:
		denom = np.sqrt(1+2*q0*z) + 1 + q0*z 
		dlum = (c*z/h0)*(1 + z*(1-q0)/denom)
		return dlum
	else:
		dlum = np.zeros(n)
		for i in xrange(n):
			if z[i] <= 0:
				dlum[i] = 0.0
			else:
				dlum[i] = quadrature(ldist, 0, z[i])[0]

	if k > 0:
		dlum = np.sinh(np.sqrt(k)*dlum)/np.sqrt(k)
	elif k < 0:
		dlum = np.sin(np.sqrt(-k)*dlum)/np.sqrt(-k)
	result = c*(1+z)*dlum/H0
	
	if len(result) == 1:
		return result[0]
	return result
 def _evaluate(self,R,z,phi=0.,t=0.,dR=0,dphi=0):
     """
     NAME:
        _evaluate
     PURPOSE:
        evaluate the potential at R,z
     INPUT:
        R - Galactocentric cylindrical radius
        z - vertical height
        phi - azimuth
        t - time
     OUTPUT:
        Phi(R,z)
     HISTORY:
        2010-07-09 - Started - Bovy (NYU)
     """
     if dR == 0 and dphi == 0:
         if not self.integerSelf == None:
             return self.integerSelf._evaluate(R,z,phi=phi,t=t)
         else:
             r= numpy.sqrt(R**2.+z**2.)
             return integrate.quadrature(_potIntegrandTransform,
                                         0.,self.a/r,
                                         args=(self.alpha,self.beta))[0]
     elif dR == 1 and dphi == 0:
         return -self._Rforce(R,z,phi=phi,t=t)
     elif dR == 0 and dphi == 1:
         return -self._phiforce(R,z,phi=phi,t=t)
Exemple #25
0
def computeLuminosityDistance(z):
    """

    Compute luminosity distance via gaussian quadrature.

    @param z: Redshift at which to calculate luminosity distance

    @return: Luminosity distance in Mpc

    """

    # constants
    H0 = 71 * 1000      # Hubble constant in (m/s)/Mpc
    Ol = 0.73           # Omega lambda
    Om = 0.27           # Omega matter
    G = 6.67e-11        # Gravitational constant in SI units
    c = 3.0e8           # Speed of light in SI units

    # proper distance function
    properDistance = lambda z: c/H0*np.sqrt(Ol+Om*(1+z)**3)
    
    #def properDistance(z):
    #    
    #    Ez = np.sqrt(Ol+Om*(1+z)**3)
    #    
    #    return c/H0/Ez

    # carry out numerical integration
    Dp = si.quadrature(properDistance, 0 ,z)[0]
    Dl = (1+z) * Dp

    return Dl
 def muBar_generic(self):
   """
   Average inverse diffuse optical depth per unit leaf area
   calculated for an arbitrary G/GZ function 
   """
   out=integrate.quadrature( self.__muBar_generic_integ,0,1,vec_func=False)
   return out[0] 
def kijko_sellevol_bayes(mag, mag_sig, bval, sigbval, tol = 1.0E-5, 
                         maxiter = 1E3, obsmax=False):
    '''Kijko-Sellevol-Bayes estimator of MMax and its associated uncertainty
    (Eq. 12 - Kijko, 2004). 
    :param mag: Earthquake magnitudes
    :type mag: numpy.ndarray
    :param mag_sig: Earthquake Magnitude Uncertainty
    :type mag_sig: numpy.ndarray
    :param bval: b-value
    :type bval: float
    :param sigbval: b-value uncertainty
    :type sigbval: float
    :keyword tol: Intergral tolerance
    :type tol: Float
    :keyword maxiter: Maximum number of Iterations
    :type maxiter: Int
    :keyword obsmax: Maximum Observed Magnitude (if not in magnitude array)
                     and its corresponding uncertainty (sigma)
    :type obsmax: Tuple (float) or Boolean
    :return: **mmax** Maximum magnitude and **mmax_sig** corresponding
             uncertainty
    :rtype: Float    
    '''
    
    if not(obsmax):
        # If maxmag is False then maxmag is maximum from magnitude list
        del(obsmax)
        obsmax = np.max(mag)
        obsmaxsig = mag_sig[np.argmax(mag)]
    else:
        obsmaxsig = obsmax[1]
        obsmax = obsmax[0]
    
    neq = np.float(np.shape(mag)[0])
    mmin = np.min(mag)
    mmax = np.copy(obsmax)
    beta = bval * np.log(10.)
    sigbeta = sigbval * np.log(10.)
    pval = beta / (sigbeta ** 2.)
    qval = (beta / sigbeta) ** 2.
    
    d_t = 1.E8
    j = 0
    while d_t > tol:
        rval = pval / (pval + mmax - mmin)
        ldelt = (1. / (1. - (rval ** qval))) ** neq
        delta = ldelt * quadrature(ksb_intfunc, mmin, mmax, 
                                   args = [neq, mmin, pval, qval])[0]

        tmmax = obsmax + delta
        d_t = np.abs(tmmax - mmax)
        mmax = np.copy(tmmax)
        j += 1
        if j > maxiter:
            print 'Kijko-Sellevol-Bayes estimator reached'
            print 'maximum # of iterations'
            d_t = 0.5 * tol
    mmax_sig = np.sqrt(obsmaxsig ** 2. + delta ** 2.)
    return mmax, mmax_sig
Exemple #28
0
def main():

    group_edges, sig_t, sig_el, scat_mat = proc_cx_file('hydrogen.cx')
    group_dE = [group_edges[i] - group_edges[i+1] for i in range(len(group_edges)-1)]

    #convert all cross sections to
    atom_dens = 0.00149

    sig_t = [i*atom_dens for i in sig_t]
    for key in scat_mat.keys():
        scat_mat[key] = [[i*atom_dens for i in x] for x in scat_mat[key]]
    sig_el = [i*atom_dens for i in sig_el]

    #Check 
    print "These two numbers should be equal", sum([scat_mat[0][i][4] for i in range(5)]), sig_el[4]

    #create the fission spectrum for U235
    chi = lambda E:  0.4865*np.sinh(np.sqrt(2.*E))*np.exp(-E)

    #Find group averaged chi's
    chi_groups = []
    for i in range(len(group_edges)-1):
        chi_g = quadrature(chi,group_edges[i+1],group_edges[i])[0]
        chi_groups.append(chi_g)
    chi_groups = np.array(chi_groups)

    #Build a matrix
    A = np.zeros((len(chi_groups),len(chi_groups)))

    #Same matrix for all methods
    S = scat_mat[0]
    for i in range(len(A)):
        A[i,i] = sig_t[i]
        for j in range(len(A[i])):
            A[i,j] -= S[i][j]

    #Solve system
    phi = np.linalg.solve(A,chi_groups)

    #normalize
    intphi = sum([group_dE[i]*phi[i] for i in range(len(phi))])
    phi = [i/intphi for i in phi]
    
    #let's make some plots
    fig = plt.figure()
    log_x = np.linspace(math.log10(group_edges[0]-0.000001),math.log10(group_edges[-1]),num=1000)
    x = [10.**i for i in log_x]
    y = []
    for i in x:
        for g in range(len(phi)):
            if i <= group_edges[g]:
                if i >= group_edges[g+1]:
                    y.append(phi[g])
    print len(x), len(y)
    plt.semilogx(x,y)
    plt.legend(loc=3) #bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
    plt.ylabel("$\phi(E)/|\phi(E)|_1$ MeV$^{-1}$")
    plt.xlabel("E (MeV)")
    plt.savefig("../method_compare.pdf",bbox_inches='tight')
 def angle3(self,**kwargs):
     """
     NAME:
        angle3 DONE
     PURPOSE:
        Calculate the radial angle
     INPUT:
        scipy.integrate.quadrature keywords
     OUTPUT:
        angle_3 in radians + 
        estimate of the error (does not include TR error)
     HISTORY:
        2011-03-03 - Written - Bovy (NYU)
     """
     if hasattr(self,'_angle3'):
         return self._angle3
     (rperi,rap)= self.calcRapRperi()
     if rap == rperi:
         return 0.
     T3= self.T3(**kwargs)[0]
     EL= self.calcEL()
     E, L= EL
     Rmean= m.exp((m.log(rperi)+m.log(rap))/2.)
     if self._r < Rmean:
         if self._r > rperi:
             wR= (2.*m.pi/T3*
                  nu.array(integrate.quadrature(_T3SphericalIntegrandSmall,
                                                0.,m.sqrt(self._axi._R-rperi),
                                                args=(E,L,self._pot,rperi),
                                                **kwargs)))\
                                                +nu.array([m.pi,0.])
         else:
             wR= nu.array([m.pi,0.])
     else:
         if self._r < rap:
             wR= -(2.*m.pi/T3*
                   nu.array(integrate.quadrature(_TRAxiIntegrandLarge,
                                                 0.,m.sqrt(rap-self._axi._R),
                                                 args=(E,L,self._pot,rap),
                                                 **kwargs)))
         else:
             wR= nu.array([0.,0.])
     if self._axi._vR < 0.:
         wR[0]+= m.pi
     self._angle3= nu.array([wR[0] % (2.*m.pi),wR[1]])
     return self._angle3
 def angleR(self,**kwargs): #pragma: no cover
     """
     NAME:
        AngleR
     PURPOSE:
        Calculate the radial angle
     INPUT:
        scipy.integrate.quadrature keywords
     OUTPUT:
        w_R(R,vT,vT) in radians + 
        estimate of the error (does not include TR error)
     HISTORY:
        2010-12-01 - Written - Bovy (NYU)
     """
     if hasattr(self,'_angleR'):
         return self._angleR
     (rperi,rap)= self.calcRapRperi(**kwargs)
     if rap == rperi:
         return 0.
     TR= self.TR(**kwargs)[0]
     EL= self.calcEL(**kwargs)
     E, L= EL
     Rmean= m.exp((m.log(rperi)+m.log(rap))/2.)
     if self._R < Rmean:
         if self._R > rperi:
             wR= (2.*m.pi/TR*
                  nu.array(integrate.quadrature(_TRAxiIntegrandSmall,
                                                0.,m.sqrt(self._R-rperi),
                                                args=(E,L,self._pot,rperi),
                                                **kwargs)))\
                                                +nu.array([m.pi,0.])
         else:
             wR= nu.array([m.pi,0.])
     else:
         if self._R < rap:
             wR= -(2.*m.pi/TR*
                   nu.array(integrate.quadrature(_TRAxiIntegrandLarge,
                                                 0.,m.sqrt(rap-self._R),
                                                 args=(E,L,self._pot,rap),
                                                 **kwargs)))
         else:
             wR= nu.array([0.,0.])
     if self._vR < 0.:
         wR[0]+= m.pi
     self._angleR= nu.array([wR[0] % (2.*m.pi),wR[1]])
     return self._angleR
def E0_integrate(g):
    f = lambda k: -1. / (2. * np.pi) * np.sqrt(g**2 - 2 * g * np.cos(k) + 1)
    E0, error = integrate.quadrature(f,
                                     -np.pi,
                                     np.pi,
                                     tol=1e-16,
                                     rtol=1e-16,
                                     maxiter=2000)
    return E0, error
    def idc_fe(self, a, b, alpha, N, p, f):
        """Perform IDCp-FE
        Input: (a,b) endpoints; alpha ics; N #intervals; p order; f vector field.
        Require: N divisible by M=p-1, with JM=N. M is #corrections.
        Return: eta_sol
        """

        # Initialise, J intervals of size M
        if not type(N) is int:
            raise TypeError('N must be integer')
        M = p - 1
        if N % M != 0:
            raise Exception('p-1 does not divide N')
        dt = (b - a) / N
        J = int(N / M)
        S = np.zeros([M, M + 1])

        # M corrections, M intervals I, of size J
        eta_sol = np.zeros(N + 1)
        eta_sol[0] = alpha
        eta = np.zeros([M + 1, J, M + 1])
        t = np.zeros([J, M + 1])
        eta_overlaps = np.zeros([J])

        # Precompute integration matrix
        for m in range(M):
            for i in range(M + 1):
                c = lambda t, i: reduce(lambda x, y: x * y, [(t - k) / (i - k)
                                                             for k in range(M)
                                                             if k != i])
                S[m, i] = quadrature(c, m, m + 1, args=(i))[0]

        for j in range(J):
            # Prediction Loop
            eta[0, j, 0] = alpha if j == 0 else eta_overlaps[j]
            for m in range(M):
                t[j, m] = (j * M + m) * dt
                eta[0, j, m + 1] = eta[0, j, m] + dt * f(t[j, m], eta[0, j, m])

            # Correction Loops
            for l in range(1, M + 1):
                eta[l, j, 0] = eta[l - 1, j, 0]
                for m in range(M):
                    # Error equation, Forward Euler
                    term1 = dt * (f(t[j, m], eta[l, j, m]) -
                                  f(t[j, m], eta[l - 1, j, m]))
                    term2 = dt * np.sum([
                        S[m, i] * f(t[j, i], eta[l - 1, j, i])
                        for i in range(M)
                    ])
                    eta[l, j, m + 1] = eta[l, j, m] + term1 + term2

            eta_sol[j * M + 1:(j + 1) * M + 1] = eta[M, j, 1:]
            if j != J - 1:
                eta_overlaps[j + 1] = eta[M, j, M]

        return np.arange(a, b + dt, dt)[:-1], eta_sol[:-1]
Exemple #33
0
 def test_quadrature_miniter(self):
     # Typical function with two extra arguments:
     def myfunc(x,n,z):       # Bessel function integrand
         return cos(n*x-z*sin(x))/pi
     table_val = 0.30614353532540296487
     for miniter in [5, 52]:
         val, err = quadrature(myfunc,0,pi,(2,1.8),miniter=miniter)
         assert_almost_equal(val, table_val, decimal=7)
         assert_(err < 1.0)
Exemple #34
0
 def fmin(gamma, measpcfc, cfcinterp, tmax):
     # This is the function to be minimized: the difference between the observed partial
     # pressure and that done by convolving an IG with the atmospheric history
     conv, _ = quadrature(pdf_atm_expr,
                          0,
                          tmax,
                          args=(gamma, cfcinterp),
                          tol=0.1)
     return np.sqrt((measpcfc - conv)**2)
Exemple #35
0
def TRFlat(R, vR, vT, vc=1., ro=1., rap=None, rperi=None, **kwargs):
    """
    NAME:
       TRFlat
    PURPOSE:
       Calculate the radial period for a flat rotation curve
    INPUT:
       R - Galactocentric radius (/ro)
       vR - radial part of the velocity (/vc)
       vT - azimuthal part of the velocity (/vc)
       vc - circular velocity
       ro - reference radius
       +scipy.integrate.quadrature keywords
    OPTIONAL INPUT:
       rap - apocenter radius (/ro)
       rperi - pericenter radius (/ro)
    OUTPUT:
       T_R(R,vT,vT)*vc/ro + estimate of the error
    HISTORY:
       2010-05-13 - Written - Bovy (NYU)
    """
    if rap == None or rperi == None:
        (rperi, rap) = calcRapRperiFlat(R, vR, vT, vc=vc, ro=ro)
    if rap == rperi:  #Rough limit
        e = 10.**-6.
        rap = R * (1 + e)
        rperi = R * (1 - e)
    Rmean = m.exp((m.log(rperi) + m.log(rap)) / 2.)
    TR = 0.
    if Rmean > rperi:
        TR += rperi * nu.array(
            integrate.quadrature(_TRFlatIntegrandSmall,
                                 0.,
                                 m.sqrt(Rmean / rperi - 1.),
                                 args=((R * vT)**2 / rperi**2., ),
                                 **kwargs))
    if Rmean < rap:
        TR += rap * nu.array(
            integrate.quadrature(_TRFlatIntegrandLarge,
                                 0.,
                                 m.sqrt(1. - Rmean / rap),
                                 args=((R * vT)**2 / rap**2., ),
                                 **kwargs))
    return m.sqrt(2.) * TR
	def test_pdf_boundary_quadrature(self):
		for bw in [1e-2, 1e-1, 1]:
			hp_kernel = hp_kernels.Gaussian(data=self.x_train, bandwidth=bw, fix_boundary=True)
		
			def quad_me(x):
				x_test = np.array([x])
				pdfs = hp_kernel(x_test)
				return(pdfs.mean())

			self.assertAlmostEqual(quadrature(quad_me, 0, 1)[0], 1, delta=1e-4)
 def muBar_generic(self):
     """
 Average inverse diffuse optical depth per unit leaf area
 calculated for an arbitrary G/GZ function 
 """
     out = integrate.quadrature(self.__muBar_generic_integ,
                                0,
                                1,
                                vec_func=False)
     return out[0]
Exemple #38
0
 def _intensity(self):
     """
     Returns an array of the integrated values using ~scipy.integrate.quadrature as the 
     intensities for the blue shifted and red shifted rays above the critical impact paratmeter 
     from the distance to the emitter
     """
     intensity = []
     for i in np.arange(len(self.z)):
         b = self.z[i][0]
         val1, _ = quadrature(self._intensity_blue_sch,
                              self.fov.value,
                              self.z[i][1],
                              args=(b, ))
         val2, _ = quadrature(self._intensity_red_sch,
                              self.z[i][1],
                              self.fov.value,
                              args=(b, ))
         intensity.append(val1 + val2)
     return intensity
Exemple #39
0
 def I(self, **kwargs):
     """
     NAME:
        I
     PURPOSE:
        Calculate I, the 'ratio' between the radial and azimutha period, 
        for a flat rotation curve
     INPUT:
        +scipy.integrate.quadrature keywords
     OUTPUT:
        I(R,vT,vT) + estimate of the error
     HISTORY:
        2010-05-13 - Written - Bovy (NYU)
     """
     if hasattr(self, '_I'):
         return self._I
     (rperi, rap) = self.calcRapRperi()
     Rmean = m.exp((m.log(rperi) + m.log(rap)) / 2.)
     if rap == rperi:  #Rough limit
         TR = self.TR()[0]
         Tphi = self.Tphi()[0]
         self._I = nu.array([TR / Tphi, 0.])
         return self._I
     I = 0.
     if Rmean > rperi:
         I += nu.array(
             integrate.quadrature(
                 _IFlatIntegrandSmall,
                 0.,
                 m.sqrt(Rmean / rperi - 1.),
                 args=((self._R * self._vT)**2 / rperi**2., ),
                 **kwargs)) / rperi
     if Rmean < rap:
         I += nu.array(
             integrate.quadrature(_IFlatIntegrandLarge,
                                  0.,
                                  m.sqrt(1. - Rmean / rap),
                                  args=(
                                      (self._R * self._vT)**2 / rap**2., ),
                                  **kwargs)) / rap
     self._I = I / m.sqrt(2.) * self._R * self._vT
     return self._I
Exemple #40
0
def prob_damage_states(damfun, poecurve):
    pds = {}
    for ds in damfun.ds:
        pgas, poes = zip(*poecurve)
        paddedpgas = [0] + list(pgas) + [3]
        paddedpoes = [1] + list(poes) + [0]
        poef = interp1d(paddedpgas, paddedpoes)
        kernel = lambda x: damfun(ds, x) * (1 - poef(x))
        pds[ds] = 1 - quadrature(kernel, 0, 3)[0]

    return pds
Exemple #41
0
 def TR(self, **kwargs):
     """
     NAME:
        TR
     PURPOSE:
        Calculate the radial period for a flat rotation curve
     INPUT:
        scipy.integrate.quadrature keywords
     OUTPUT:
        T_R(R,vT,vT)*vc/ro + estimate of the error
     HISTORY:
        2010-05-13 - Written - Bovy (NYU)
     """
     if hasattr(self, '_TR'):
         return self._TR
     (rperi, rap) = self.calcRapRperi()
     if rap == rperi:  #Rough limit
         #TR=kappa
         kappa = m.sqrt(2.) / self._R
         self._TR = nu.array([2. * m.pi / kappa, 0.])
         return self._TR
     Rmean = m.exp((m.log(rperi) + m.log(rap)) / 2.)
     TR = 0.
     if Rmean > rperi:
         TR += rperi * nu.array(
             integrate.quadrature(
                 _TRFlatIntegrandSmall,
                 0.,
                 m.sqrt(Rmean / rperi - 1.),
                 args=((self._R * self._vT)**2 / rperi**2., ),
                 **kwargs))
     if Rmean < rap:
         TR += rap * nu.array(
             integrate.quadrature(_TRFlatIntegrandLarge,
                                  0.,
                                  m.sqrt(1. - Rmean / rap),
                                  args=(
                                      (self._R * self._vT)**2 / rap**2., ),
                                  **kwargs))
     self._TR = m.sqrt(2.) * TR
     return self._TR
Exemple #42
0
    def predictive_intensity_function(self, X_eval):
        """ Computes the predictive intensity function at X_eval by Gaussian
        quadrature.

        :param X_eval: numpy.ndarray [num_points_eval x D]
            Points where the intensity function should be evaluated.

        :returns:
            numpy.ndarray [num_points]: mean of predictive posterior intensity
            numpy.ndarray [num_points]: variance of predictive posterior
                                        intensity
        """
        num_preds = X_eval.shape[0]
        mu_pred, var_pred = self.predictive_posterior_GP(X_eval)

        mean_lmbda_pred, var_lmbda_pred = numpy.empty(num_preds), \
                                          numpy.empty(num_preds)

        mean_lmbda_q1 = self.lmbda_star_q1
        var_lmbda_q1 = self.alpha_q1 / (self.beta_q1**2)
        mean_lmbda_q1_squared = var_lmbda_q1 + mean_lmbda_q1**2

        for ipred in range(num_preds):
            mu, std = mu_pred[ipred], numpy.sqrt(var_pred[ipred])
            func1 = lambda g_pred: 1. / (1. + numpy.exp(-g_pred)) * \
                                  numpy.exp(-.5*(g_pred - mu)**2 / std**2) / \
                                  numpy.sqrt(2.*numpy.pi*std**2)
            a, b = mu - 10. * std, mu + 10. * std
            mean_lmbda_pred[ipred] = mean_lmbda_q1 * quadrature(
                func1, a, b, maxiter=500)[0]
            func2 = lambda g_pred: (1. / (1. + numpy.exp(-g_pred)))**2 * \
                                  numpy.exp(
                                      -.5 * (g_pred - mu) ** 2 / std ** 2) / \
                                  numpy.sqrt(2. * numpy.pi * std ** 2)
            a, b = mu - 10. * std, mu + 10. * std
            mean_lmbda_pred_squared = mean_lmbda_q1_squared *\
                                     quadrature(func2, a, b, maxiter=500)[0]
            var_lmbda_pred[
                ipred] = mean_lmbda_pred_squared - mean_lmbda_pred[ipred]**2

        return mean_lmbda_pred, var_lmbda_pred
Exemple #43
0
def ip_08_04():
    """
    MATLAB script for Illustrative Problem 4, Chapter 8.
    """
    a_db = np.arange(-13, 13.5, 0.5)
    a = 10**(a_db / 10)
    a_hard = a.copy()
    c_hard = 1 - entropy2(qfunc(a_hard))
    f = np.zeros(53)
    g = np.zeros(53)
    c_soft = np.zeros(53)

    il3_8fun = lambda x, p: 1 / np.sqrt(2 * np.pi) * np.exp(
        (-(x - p)**2) / 2) * np.log2(2 / (1 + np.exp(-2 * x * p)))

    for i in range(0, 53):
        f[i] = integrate.quadrature(il3_8fun,
                                    a[i] - 5,
                                    a[i] + 5,
                                    args=(a[i], ),
                                    tol=1e-3)[0]  # ,1e-3,[],a[i]
        g[i] = integrate.quadrature(il3_8fun,
                                    -a[i] - 5,
                                    -a[i] + 5,
                                    args=(-a[i], ),
                                    tol=1e-3)[0]  # ,1e-3
        c_soft[i] = 0.5 * f[i] + 0.5 * g[i]
    plt.title(
        'Capacity for BPSK transmisison on the AWGN channel for Hard and Soft Decision'
    )
    plt.xlabel(r'A/$\sigma$')
    plt.ylabel('Capacity in bits Per channel Use')
    # plt.grid(True,which="both",ls="-")
    line1, = plt.semilogx(a, c_soft, label="Soft Decision")
    line2, = plt.semilogx(a_hard, c_hard, label="Hard Decision")
    plt.legend(handles=[
        line1,
        line2,
    ], loc=4)
    plt.show()
    return
Exemple #44
0
 def angle2(self,**kwargs):
     """
     NAME:
        angle2 DONE
     PURPOSE:
        Calculate the longitude of the ascending node
     INPUT:
     OUTPUT:
        angle2 in radians + 
        estimate of the error
     HISTORY:
        2011-03-03 - Written - Bovy (NYU)
     """
     if hasattr(self,'_angle2'): return self._angle2
     if not hasattr(self,'_i'): self._i= m.acos(self._J1/self._J2)
     if self._i == 0.: dstdj2= m.pi/2.
     else: dstdj2= m.asin(m.cos(self._theta)/m.sin(self._i))
     out= self._angle3(**kwargs)*self.T3(**kwargs)[0]/self.T2(**kwargs)[0]
     out[0]+= dstdj2
     #Now add the final piece dsrdj2
     EL= self.calcEL()
     E, L= EL
     Rmean= m.exp((m.log(rperi)+m.log(rap))/2.)
     if self._axi._R < Rmean:
         if self._axi._R > self.rperi:
             out+= L*nu.array(integrate.quadrature(_ISphericalIntegrandSmall,
                                                   0.,m.sqrt(self._axi._R-rperi),
                                                   args=(E,L,self._pot,rperi),
                                                   **kwargs))
     else:
         if self._axi._R < self._rap:
             out+= L*nu.array(integrate.quadrature(_ISphericalIntegrandLarge,
                                                   0.,m.sqrt(rap-self._axi._R),
                                                   args=(E,L,self._pot,rap),
                                                   **kwargs))
         else:
             out[0]+= m.pi*self.T3(**kwargs)[0]/self.T2(**kwargs)[0]
     if self._axi._vR < 0.:
         out[0]+= m.pi*self.T3(**kwargs)[0]/self.T2(**kwargs)[0]
     self._angle2= out
     return self._angle2
 def outer_integrand(y):
     return sint.quadrature(  # NOQA
         lambda x: func(x, y, *args),
         a,
         b,
         (),
         toli,
         rtoli,
         maxiteri,
         vec_func,
         miniteri,
     )[0]  # NOQA
Exemple #46
0
def z_to_cdist(z):
    ''' Calculate the comoving distance 

    Parameters:
        z (float): redshift

    Returns:
        Comoving distance in Mpc
    '''
    Ez_func = lambda x: 1./np.sqrt(const.Omega0*(1.+x)**3+const.lam)
    dist = const.c/const.H0 * quadrature(Ez_func, 0, z)[0]
    return outputify(dist)
 def volssa_generic(self):
     """
 The volume single scattering albedo for any
 G and Zeta function
 
 See eqn 5 & 7 of Sellers 1985
 """
     out = integrate.quadrature(self.__volssa_generic_integ,
                                0,
                                1,
                                vec_func=False)
     return out[0] * (self.leaf_r + self.leaf_t) * 0.5
 def compute_ext_inf_integral(target, s, radius):
     # target: target point
     # s: fractional order
     # radius: radius of the circle
     import scipy.integrate as sint
     val, _ = sint.quadrature(partial(ext_inf_integrand,
                                      s=s,
                                      target=target,
                                      radius=radius),
                              a=0,
                              b=2 * np.pi)
     return val * (1 / (2 * s)) * fl_scaling(k=self.dim, s=s)
Exemple #49
0
def traveltime(x, c):
    """
    Calculates the travel-time 

Args:
    x: scalar or array of locations 
    c: Velocity model; has to be a callable function returning the velocity at some location
    """
    from scipy.integrate import quadrature
    from numpy import isscalar, asarray, empty

    s = lambda x: 1.0 / c(x)

    if isscalar(x):
        T = quadrature(func=s, a=0.0, b=x)[0]
    else:
        x = asarray(x)
        T = empty(x.shape)
        T[:] = [quadrature(func=s, a=0.0, b=b)[0] for b in x]

    return T
Exemple #50
0
def MutalInductance(r1, r2, d):
    # return 0.5 * mu0 * quadrature(_f, 0, 2*nu.pi, args=(r1, r2, d), tol=1e-9, maxiter=100000)[0]
    # return 0.5 * mu0 * quadrature(_g, -1, 1, args=(r1, r2, d), tol=1e-12, maxiter=100000)[0]

    k = nu.sqrt(4 * r1 * r2 / ((r1 + r2)**2 + d**2))
    result = mu0 * nu.sqrt(r1 * r2) * (
        (2 / k - k) * ellipk(k**2) - 2 / k * ellipe(k**2))
    if result >= 0:
        return result
    else:
        return 0.5 * mu0 * quadrature(
            _f, 0, 2 * nu.pi, args=(r1, r2, d), tol=1e-6, maxiter=3000)[0]
Exemple #51
0
def xi_poles(rfid, alpha, epsilon, order):
    coeff = 2 * order + 1
    fn = xi_poles_integrand
    int, error = quadrature(fn,
                            0,
                            1,
                            tol=1.49e-8,
                            maxiter=100,
                            args=(rfid, alpha, epsilon, order),
                            vec_func=False)

    return coeff * int
Exemple #52
0
 def TR(self, **kwargs):
     """
     NAME:
        TR
     PURPOSE:
        Calculate the radial period for a power-law rotation curve
     INPUT:
        scipy.integrate.quadrature keywords
     OUTPUT:
        T_R(R,vT,vT)*vc/ro + estimate of the error
     HISTORY:
        2010-11-30 - Written - Bovy (NYU)
     """
     if hasattr(self, '_TR'):
         return self._TR
     (rperi, rap) = self.calcRapRperi()
     if rap == rperi:  #Rough limit
         #TR=kappa
         gamma = m.sqrt(2. / (1. + self._beta))
         kappa = 2. * self._R**(self._beta - 1.) / gamma
         self._TR = nu.array([2. * m.pi / kappa, 0.])
         return self._TR
     Rmean = m.exp((m.log(rperi) + m.log(rap)) / 2.)
     TR = 0.
     if Rmean > rperi:
         TR+= rperi**(1.-self._beta)\
             *nu.array(integrate.quadrature(_TRPowerIntegrandSmall,
                                            0.,m.sqrt(Rmean/rperi-1.),
                                            args=(self._X,self._beta,
                                                  self._signbeta),
                                            **kwargs))
     if Rmean < rap:
         TR+= rap**(1.-self._beta)\
             *nu.array(integrate.quadrature(_TRPowerIntegrandLarge,
                                            0.,m.sqrt(1.-Rmean/rap),
                                            args=(self._Y,self._beta,
                                                  self._signbeta),
                                            **kwargs))
     self._TR = 2. * m.sqrt(self._absbeta) * TR
     return self._TR
Exemple #53
0
 def I(self, **kwargs):
     """
     NAME:
        I
     PURPOSE:
        Calculate I, the 'ratio' between the radial and azimutha period, 
        for a power-law rotation curve
     INPUT:
        +scipy.integrate.quadrature keywords
     OUTPUT:
        I(R,vT,vT) + estimate of the error
     HISTORY:
        2010-11-30 - Written - Bovy (NYU)
     """
     if hasattr(self, '_I'):
         return self._I
     (rperi, rap) = self.calcRapRperi()
     Rmean = m.exp((m.log(rperi) + m.log(rap)) / 2.)
     if rap == rperi:  #Rough limit
         TR = self.TR()[0]
         Tphi = self.Tphi()[0]
         self._I = nu.array([TR / Tphi, 0.])
         return self._I
     I = 0.
     if Rmean > rperi:
         I+= rperi**(-1.-self._beta)\
             *nu.array(integrate.quadrature(_IPowerIntegrandSmall,
                                            0.,m.sqrt(Rmean/rperi-1.),
                                            args=(self._X,self._beta,
                                                  self._signbeta),
                                            **kwargs))
     if Rmean < rap:
         I+= rap**(-1.-self._beta)\
             *nu.array(integrate.quadrature(_IPowerIntegrandLarge,
                                            0.,m.sqrt(1.-Rmean/rap),
                                            args=(self._Y,self._beta,
                                                  self._signbeta),
                                            **kwargs))
     self._I = I * self._R * self._vT * m.sqrt(self._absbeta)
     return self._I
Exemple #54
0
 def _calc_angler(self, Or, r, Rmean, rperi, rap, E, L, vr, fixed_quad,
                  **kwargs):
     if r < Rmean:
         if r > rperi and not fixed_quad:
             wr = Or * integrate.quadrature(_TrSphericalIntegrandSmall,
                                            0.,
                                            m.sqrt(r - rperi),
                                            args=(E, L, self._2dpot, rperi),
                                            **kwargs)[0]
         elif r > rperi and fixed_quad:
             wr = Or * integrate.fixed_quad(_TrSphericalIntegrandSmall,
                                            0.,
                                            m.sqrt(r - rperi),
                                            args=(E, L, self._2dpot, rperi),
                                            n=10,
                                            **kwargs)[0]
         else:
             wr = 0.
         if vr < 0.: wr = 2 * m.pi - wr
     else:
         if r < rap and not fixed_quad:
             wr = Or * integrate.quadrature(_TrSphericalIntegrandLarge,
                                            0.,
                                            m.sqrt(rap - r),
                                            args=(E, L, self._2dpot, rap),
                                            **kwargs)[0]
         elif r < rap and fixed_quad:
             wr = Or * integrate.fixed_quad(_TrSphericalIntegrandLarge,
                                            0.,
                                            m.sqrt(rap - r),
                                            args=(E, L, self._2dpot, rap),
                                            n=10,
                                            **kwargs)[0]
         else:
             wr = m.pi
         if vr < 0.:
             wr = m.pi + wr
         else:
             wr = m.pi - wr
     return wr
Exemple #55
0
 def TR(self,**kwargs):
     """
     NAME:
        TR
     PURPOSE:
        Calculate the radial period for a power-law rotation curve
     INPUT:
        scipy.integrate.quadrature keywords
     OUTPUT:
        T_R(R,vT,vT)*vc/ro + estimate of the error
     HISTORY:
        2010-12-01 - Written - Bovy (NYU)
     """
     if hasattr(self,'_TR'):
         return self._TR
     (rperi,rap)= self.calcRapRperi(**kwargs)
     if rap == rperi: #Rough limit
         raise AttributeError("Not implemented yet")
         #TR=kappa
         gamma= m.sqrt(2./(1.+self._beta))
         kappa= 2.*self._R**(self._beta-1.)/gamma
         self._TR= nu.array([2.*m.pi/kappa,0.])
         return self._TR
     Rmean= m.exp((m.log(rperi)+m.log(rap))/2.)
     EL= self.calcEL(**kwargs)
     E, L= EL
     TR= 0.
     if Rmean > rperi:
         TR+= nu.array(integrate.quadrature(_TRAxiIntegrandSmall,
                                            0.,m.sqrt(Rmean-rperi),
                                            args=(E,L,self._pot,rperi),
                                            **kwargs))
     if Rmean < rap:
         TR+= nu.array(integrate.quadrature(_TRAxiIntegrandLarge,
                                            0.,m.sqrt(rap-Rmean),
                                            args=(E,L,self._pot,rap),
                                            **kwargs))
     self._TR= 2.*TR
     return self._TR
Exemple #56
0
def calcularDensidadeEnergia(nQuarks, sacola, massa):
    resultado = 0
    eAuxiliar = 0
    e = []
    for kf in range(1, 1001):
        for i in range(0, nQuarks):
            resultado = integrate.quadrature(
                lambda k: (k**2) * (((k**2) + (massa[i]**2))**(1 / 2)), 0, kf)
            eAuxiliar += resultado[0]
        e.append((6 / ((2 * pi)**2)) * eAuxiliar + sacola)
        resultado = 0
        eAuxiliar = 0
    return e
Exemple #57
0
def calcularPressao(nQuarks, sacola, massa):
    resultado = 0
    pAuxiliar = 0
    p = []
    for kf in range(1, 1001):
        for i in range(0, nQuarks):
            resultado = integrate.quadrature(
                lambda k: (k**4) / (((k**2) + (massa[i]**2))**(1 / 2)), 0, kf)
            pAuxiliar += resultado[0]
        p.append((1 / (pi**2)) * pAuxiliar - sacola)
        resultado = 0
        pAuxiliar = 0
    return p
Exemple #58
0
 def T3(self,**kwargs):
     """
     NAME:
        T3 DONE
     PURPOSE:
        Calculate the radial period
     INPUT:
        scipy.integrate.quadrature keywords
     OUTPUT:
        T_3(R,vT,vT)*vc/ro + estimate of the error
     HISTORY:
        2011-03-03 - Written - Bovy (NYU)
     """
     if hasattr(self,'_T3'):
         return self._T3
     (rperi,rap)= self.calcRapRperi()
     if rap == rperi: #Rough limit
         raise AttributeError("Not implemented yet")
         #TR=kappa
         gamma= m.sqrt(2./(1.+self._beta))
         kappa= 2.*self._R**(self._beta-1.)/gamma
         self._TR= nu.array([2.*m.pi/kappa,0.])
         return self._TR
     Rmean= m.exp((m.log(rperi)+m.log(rap))/2.)
     EL= self.calcEL()
     E, L= EL
     T3= 0.
     if Rmean > rperi:
         T3+= nu.array(integrate.quadrature(_T3SphericalIntegrandSmall,
                                            0.,m.sqrt(Rmean-rperi),
                                            args=(E,L,self._pot,rperi),
                                            **kwargs))
     if Rmean < rap:
         T3+= nu.array(integrate.quadrature(_T3SphericalAxiIntegrandLarge,
                                            0.,m.sqrt(rap-Rmean),
                                            args=(E,L,self._pot,rap),
                                            **kwargs))
     self._T3= 2.*T3
     return m.fabs(self._T3)
Exemple #59
0
def complex_quadrature(integrand: Callable, a: float, b: float,
                       **kwargs) -> Tuple[complex, tuple, tuple]:
    """
    As :func:`scipy.integrate.quadrature`, but works with complex integrands.

    Parameters
    ----------
    integrand
        The function to integrate.
    a
        The lower limit of integration.
    b
        The upper limit of integration.
    kwargs
        Additional keyword arguments are passed to
        :func:`scipy.integrate.quadrature`.

    Returns
    -------
    (result, real_extras, imag_extras)
        A tuple containing the result, as well as the other things returned
        by :func:`scipy.integrate.quadrature` for the real and imaginary parts
        separately.
    """
    def real_func(*args, **kwargs):
        return np.real(integrand(*args, **kwargs))

    def imag_func(*args, **kwargs):
        return np.imag(integrand(*args, **kwargs))

    real_integral = integ.quadrature(real_func, a, b, **kwargs)
    imag_integral = integ.quadrature(imag_func, a, b, **kwargs)

    return (
        real_integral[0] + (1j * imag_integral[0]),
        real_integral[1:],
        imag_integral[1:],
    )
Exemple #60
0
def p_avg(p0, a1, a3, Ex, T, tol=1.0e-3, maxiter=50):
    args = (p0, a1, a3, Ex, T)
    norm, error_norm = quadrature(kernel,
                                  0,
                                  pi,
                                  args=args,
                                  tol=tol,
                                  maxiter=maxiter)
    cos_avg, error_cos = quadrature(func_cos_avg,
                                    0,
                                    pi,
                                    args=args,
                                    tol=tol,
                                    maxiter=maxiter)
    cos_square_avg, error_cos_sqr = quadrature(func_cos_sqr_avg,
                                               0,
                                               pi,
                                               args=args,
                                               tol=tol,
                                               maxiter=maxiter)
    cos_avg *= 1.0 / norm
    cos_square_avg *= 1.0 / norm
    return p0 * cos_avg + (a1 + (a3 - a1) * cos_square_avg) * Ex