コード例 #1
0
def losvprojden(param = [2.0, -5.3, 2.5, 0.16, 1.5, -9.0, 6.9, 0.086, 21.0, 1.5, 1,3,1], dR = 0.05):
	a,d,e, Ec, rlim, b, q, Jb, Vmax, rmax, alpha, beta, gamma = param
	rs = rmax/2.16           # rmax=2.16*rs

	losvsiglist = []
        projdenlist = []
        Rlist = []
        Ri = 0.0000
        while Ri<rlim:  #for each Ri, integrate over r
		def losvI(theta, v,r):
			zz = r*r - Ri*Ri + 10**-10  #add 10**-10 to prevent divide by zero
                	dz = r / np.sqrt(zz)
			f  = ftheta( (r/rs), v, theta, param )
			Ja = f * zz*pow(v,4)*np.cos(theta)*np.cos(theta)*np.sin(theta)/(r*r)
			Jb = f * Ri*Ri*pow(v,4)*pow(np.sin(theta),3)/(r*r)
			print 'using Ri', Ri, theta, v, r
			#missing rhor again! WRONG
			rhor = ftheta( (r/rs), v, theta, param ) * v*v * np.sin(theta) 
			return (Ja+Jb)*dz

		def projI(theta,v,r):
			zz = r*r - Ri*Ri + 10**-10
                        dz = r / np.sqrt(zz)
			I  = ftheta( (r/rs), v, theta, param ) * v*v * np.sin(theta) * dz
			return I
	
		def bounds_theta(v,r):
			return [0, np.pi]
		def bounds_v(r):
			vmax = vesc( (r/rs), [rlim, Vmax, rmax, alpha, beta, gamma] )
	 		return [0, vmax]
		def bounds_r():
			return [Ri, rlim]
		
		def vmax(r):
                        return vesc( (r/rs), [rlim, Vmax, rmax, alpha, beta, gamma] )

		def vmin(r):
                        return 0.0
		def tmax(v,r):
			return np.pi
		def tmin(v,r):
			return 0.0

		#Ilos  = integrate.nquad( losvI, [bounds_theta, bounds_v, bounds_r], epsrel = 1e-6 )[0] 
		#Iproj = integrate.nquad( projI, [bounds_theta, bounds_v, bounds_r], epsrel = 1e-6 )[0]
		
		Ilos = integrate.tplquad(losvI, Ri, rlim, vmin,vmax, tmin,tmax, epsrel=1e-4, epsabs=0)[0]
		Iproj= integrate.tplquad(projI, Ri, rlim, vmin,vmax, tmin,tmax, epsrel=1e-4, epsabs=0)[0]

		losvsiglist.append( Ilos  )
		projdenlist.append( Iproj )
		Rlist.append(Ri)
		print "3quad ftheta: ", Ri, rlim
		Ri = Ri + dR

	Rarr	    = np.asarray(Rlist)
	projdenarr  = np.asarray(projdenlist)
        losvsigarr2 = np.asarray(losvsiglist) / (projdenarr+10**-8)
        return Rarr, losvsigarr2**0.5, projdenarr/(max(projdenarr) + 10**-8)
コード例 #2
0
def MEVG0(Rhwhm, RefE, RefV, Rrms) :
	print '... ... ... MEVG0: Rhwhm, RefE, RefV, Rrms', Rhwhm, RefE, RefV, Rrms

	if RefE !=0 and RefV !=0 :
		print "Ooops RE OR RV please"
		sys.exit(0)

	if RefE == 0 and RefV == 0:
		result = MG0(Rhwhm, Rrms)

	if RefV == 0 and RefE != 0 :
		result = tplquad(MEVG0_integrand_exp,\
						0.0, numpy.pi, \
						lambda th: 0.0,\
						lambda th: 3.0*Rrms,\
						lambda th,rt: 0.0,\
						lambda th,rt: 5.0*RefE,\
						args = (Rhwhm, RefE, RefV, Rrms),\
						)[0]

	if RefE == 0 and RefV != 0:
		result = tplquad(MEVG0_integrand_vau,\
						0, numpy.pi,
						lambda th: 0.0,\
						lambda th: 3.0*Rrms,\
						lambda th,rt: 0.0,\
						lambda th,rt: 5.0*RefV,\
						args = (Rhwhm, RefE, RefV, Rrms),\
						)[0]


	return result
コード例 #3
0
ファイル: analytical.py プロジェクト: mlev71/sascalc_geom
 def calc_ff(self,Q_VAL):
     for q in Q_VAL:
         r = self.r	
         a_int= integrate.tplquad(lambda x,y,z:np.cos(q*(x**2+y**2+z**2)**.5), 
                 -r, r, 
                 lambda x:-(r**2-x**2)**.5, lambda x: (r**2-x**2)**.5, 
                 lambda x,y: -(r**2-x**2-y**2)**.5, lambda x,y: (r**2-x**2-y**2)**.5)
         b_int = integrate.tplquad(lambda x,y,z:np.sin(q*(x**2+y**2+z**2)**.5), 
                 -r, r, 
                 lambda x:-(r**2-x**2)**.5 ,lambda x: (r**2-x**2)**.5, 
                 lambda x,y: -(r**2-x**2-y**2)**.5, lambda x,y: (r**2-x**2-y**2)**.5)	
         pq = (a_int[0]-1j*b_int[0])
         print(pq)	
         yield pq
コード例 #4
0
def integrate_that_shit():
  volume = tplquad(diff_volume, r1, r3, lambda r:   t1, lambda r:   t2,
                                        lambda r,t: p1, lambda r,t: p2)[0]
  print 'volume check (' + str(4./3.*np.pi*(r3)**3.) + '): ' + str(volume)

  print 'now the nasty integral...'
  Uabs_T = tplquad(new_diff_Uabs, r1, r3, lambda r:   t1, lambda r:   t2,
                                        lambda r,t: p1, lambda r,t: p2)[0]

  print '... no problem!'

  eps0 = 8.854187E-12
  mu0 = 4.*np.pi*1.E-7
  Ap = np.pi*radshell*radshell
  Qabs_corrected = Uabs_T/Ap/(1./2.*np.sqrt(eps0/mu0))
  print 'my calc divided by sqrt(eps0/mu0) = ' + str(Qabs_corrected*1.E-6)
コード例 #5
0
ファイル: integrate.py プロジェクト: wulmer/mystic
def _scipy_integrate(f,lb,ub):  
  """
Returns the integral of an n-dimensional function f from lb to ub
(where n = 1, 2, or 3), using scipy.integrate

Inputs:
    f -- a function that takes a list and returns a number.
    lb -- a list of lower bounds
    ub -- a list of upper bounds
"""
  from scipy.integrate import quad, dblquad, tplquad
  if len(lb) == 3:
    def func(z,y,x): return f([x,y,z])
    def qf(x,y): return lb[2]
    def rf(x,y): return ub[2]
    def gf(x): return lb[1]
    def hf(x): return ub[1]
    expectation,confidence = tplquad(func,lb[0],ub[0],gf,hf,qf,rf)
    return expectation
  if len(lb) == 2:
    def func(y,x): return f([x,y])
    def gf(x): return lb[1]
    def hf(x): return ub[1]
    expectation,confidence = dblquad(func,lb[0],ub[0],gf,hf)
    return expectation 
  if len(lb) == 1:
    expectation,confidence = quad(f,lb[0],ub[0])
    return expectation 
コード例 #6
0
ファイル: util.py プロジェクト: ayshih/heroes
def heroes_effective_area_gaussian(energy_range=(20,30), fwhm=3, radius=9.5,
                                   offaxis=0):
    """
    Calculates the average effective area for a Gaussian exposure.  Off-axis
    exposures take *much* longer to calculate, by >~2 orders of magnitude in
    time!
    
    energy_range is in keV
    fwhm of source is in arcmin
    radius of integration area is in arcmin
    offaxis is in arcmin
    """
    f2d = heroes_effective_area_fit()
    sigma = fwhm/2.355
    if offaxis == 0:
        area = integrate.dblquad(lambda e,r: f2d(e,r)*r*np.exp(-(r/sigma)**2/2)/sigma**2,
                                 0, radius,
                                 lambda r:energy_range[0], lambda r: energy_range[1])[0]
    else:
        r2 = lambda x,y: x**2+y**2
#        area = integrate.dblquad(lambda y,x: np.exp(-(r(x-offaxis,y)/sigma)**2/2)/(2*np.pi*sigma**2),
#                                 -radius, radius,
#                                 lambda x: -np.sqrt(radius**2-x**2), lambda x: np.sqrt(radius**2-x**2))[0]
        area = integrate.tplquad(lambda e,y,x: f2d(e,np.sqrt(r2(x,y)))*np.exp(-r2(x-offaxis,y)/sigma**2/2)/(2*np.pi*sigma**2),
                                 -radius, radius,
                                 lambda x: -np.sqrt(radius**2-x**2), lambda x: np.sqrt(radius**2-x**2),
                                 lambda x,y: energy_range[0], lambda x,y: energy_range[1])[0]
    norm_area = 1.
    area /= norm_area*(energy_range[1]-energy_range[0])
    return area
コード例 #7
0
ファイル: iso_cone.py プロジェクト: pombredanne/relax
def pcs_numeric_quad_int_iso_cone(theta_max=None, sigma_max=None, c=None, r_pivot_atom=None, r_ln_pivot=None, A=None, R_eigen=None, RT_eigen=None, Ri_prime=None):
    """Determine the averaged PCS value via numerical integration.

    @keyword theta_max:     The half cone angle.
    @type theta_max:        float
    @keyword sigma_max:     The maximum torsion angle.
    @type sigma_max:        float
    @keyword c:             The PCS constant (without the interatomic distance and in Angstrom units).
    @type c:                float
    @keyword r_pivot_atom:  The pivot point to atom vector.
    @type r_pivot_atom:     numpy rank-1, 3D array
    @keyword r_ln_pivot:    The lanthanide position to pivot point vector.
    @type r_ln_pivot:       numpy rank-1, 3D array
    @keyword A:             The full alignment tensor of the non-moving domain.
    @type A:                numpy rank-2, 3D array
    @keyword R_eigen:       The eigenframe rotation matrix.
    @type R_eigen:          numpy rank-2, 3D array
    @keyword RT_eigen:      The transpose of the eigenframe rotation matrix (for faster calculations).
    @type RT_eigen:         numpy rank-2, 3D array
    @keyword Ri_prime:      The empty rotation matrix for the in-frame isotropic cone motion, used to calculate the PCS for each state i in the numerical integration.
    @type Ri_prime:         numpy rank-2, 3D array
    @return:                The averaged PCS value.
    @rtype:                 float
    """

    # Perform numerical integration.
    result = tplquad(pcs_pivot_motion_full_quad_int, -sigma_max, sigma_max, lambda phi: -pi, lambda phi: pi, lambda theta, phi: 0.0, lambda theta, phi: theta_max, args=(r_pivot_atom, r_ln_pivot, A, R_eigen, RT_eigen, Ri_prime))

    # The surface area normalisation factor.
    SA = 4.0 * pi * sigma_max * (1.0 - cos(theta_max))

    # Return the value.
    return c * result[0] / SA
コード例 #8
0
    def test_matching_tplquad(self):
        def func3d(x0, x1, x2, c0, c1):
            return x0 ** 2 + c0 * x1 ** 3 - x0 * x1 + 1 + c1 * np.sin(x2)

        res = tplquad(func3d, -1, 2, lambda x: -2, lambda x: 2, lambda x, y: -np.pi, lambda x, y: np.pi, args=(2, 3))
        res2 = nquad(func3d, [[-np.pi, np.pi], [-2, 2], (-1, 2)], args=(2, 3))
        assert_almost_equal(res, res2)
コード例 #9
0
    def spherical_vol_avg(self,center,r_max):
        """
        Averages the density over the volume of a sphere centered at the point
        center, with a radis r_max.
        """
        # Physics notation for spherical coordinates are use:
        # rho - radial distance
        # theta - inclination
        # phi - azimuthal angle
        from scipy.integrate import tplquad
        def func(theta,phi,rho,center,dens):
            """
            Function to find the value of the density at a point equal to
            center+Vector(rho).
            """
            # Determine direct rectilinear coordinates relative to center from
            # spherical coordinates away from center.
            rho_x = rho*np.cos(phi)*np.sin(theta)
            rho_y = rho*np.sin(phi)*np.sin(theta)
            rho_z = rho*np.cos(theta)
            # Determine absolute direct coordinates from relative coordinates
            # and center.
            r_x = rho_x + center[0]
            r_y = rho_y + center[1]
            r_z = rho_z + center[2]
            # Find the value of the density at the point r.
            val = dens.interpolate([r_x,r_y,r_z])
            # Weight the value by the spherical coordinate Jacobian.
            val = val*rho*rho*np.sin(theta)
            return val

        integral,error = tplquad(func,0,r_max,lambda a:0,lambda b:2*np.pi,
                                 lambda c,d:0,lambda e,f: np.pi,args=(center,self))
        return integral
コード例 #10
0
ファイル: test_distribution.py プロジェクト: hzxusx/PlasmaPy
 def test_norm(self):
     """
     Tests whether distribution function is normalized, and integrates to 1.
     """
     # converting vTh to unitless
     vTh = self.vTh.si.value
     # setting up integration from 0 to 10*vTh, which is close to Inf
     infApprox = (10 * vTh)
     # integral should be close to 1
     integ = spint.tplquad(Maxwellian_speed_3D,
                           0,
                           infApprox,
                           lambda z: 0,
                           lambda z: infApprox,
                           lambda z, y: 0,
                           lambda z, y: infApprox,
                           args=(self.T,
                                 self.particle,
                                 0,
                                 0,
                                 0,
                                 vTh,
                                 "unitless"),
                           epsabs=1e0,
                           epsrel=1e0,
                           )
     # value returned from tplquad is (integral, error), we just need
     # the 1st
     integVal = integ[0]
     exceptStr = ("Integral of distribution function should be 1 "
                  f"and not {integVal}")
     assert np.isclose(integVal,
                       1,
                       rtol=1e-3,
                       atol=0.0), exceptStr
コード例 #11
0
def integrate_nd(f, domain, shape, dtype):

    if shape == () or shape == (1,):
        if dtype in continuous_types:
            return integrate.quad(f, domain.lower, domain.upper, epsabs=1e-8)[0]
        else:
            return np.sum(list(map(f, np.arange(domain.lower, domain.upper + 1))))
    elif shape == (2,):
        def f2(a, b):
            return f([a, b])

        return integrate.dblquad(f2,
                                 domain.lower[0],
                                 domain.upper[0],
                                 lambda a: domain.lower[1],
                                 lambda a: domain.upper[1])[0]

    elif shape == (3,):
        def f3(a, b, c):
            return f([a, b, c])

        return integrate.tplquad(f3,
                                 domain.lower[0], domain.upper[0],
                                 lambda a: domain.lower[1],
                                 lambda a: domain.upper[1],
                                 lambda a, b: domain.lower[2],
                                 lambda a, b: domain.upper[2])[0]
    else:
        raise ValueError("Dont know how to integrate shape: " + str(shape))
コード例 #12
0
 def __init__(self, r0, basis, mean, covar):
     self.r0 = r0
     self.basis = basis
     self.mean = mean
     self.covar = covar
     self.C = 1
     self.C = integrate.tplquad(lambda psi, phi, theta: sin(psi)**2*sin(phi)*self.pdfSphere(Quaternion(cos(psi), sin(psi)*cos(phi), sin(psi)*sin(phi)*cos(theta), sin(psi)*sin(phi)*sin(theta))), 0, 2*pi, lambda theta: 0, lambda theta: pi, lambda phi, theta: 0, lambda phi,theta: pi)[0]
コード例 #13
0
def boxIntegrate(cx, cy, r, zMin, zMax, f):
    yBot = lambda x : cy - r
    yTop = lambda x : cy + r
    zBot = lambda x, y : zMin
    zTop = lambda x, y : zMax
    
    res, err = integrate.tplquad(f, cx - r, cx + r, yBot, yTop, zBot, zTop)
    return (res,err)
コード例 #14
0
def cylinderIntegrate(cx, cy, r, zMin, zMax, f):
    yTop = lambda x : cy + (r*r - (x - cx)*(x - cx))**0.5
    yBot = lambda x : cy - (r*r - (x - cx)*(x - cx))**0.5
    zTop = lambda x, y : zMax
    zBot = lambda x, y : zMin
    
    res, err = integrate.tplquad(f, cx - r, cx + r, yBot, yTop, zBot, zTop)
    return res, err
コード例 #15
0
def tripleRectIntegrate(bounds, f):
    a1 = bounds[0][0]
    b1 = bounds[0][1]
    a2 = lambda x : bounds[1][0]
    b2 = lambda x : bounds[1][1]
    a3 = lambda x, y : bounds[2][0]
    b3 = lambda x, y : bounds[2][1]
    
    res, err = integrate.tplquad(f, a1,b1,a2,b2,a3,b3)
    return (res,err)
コード例 #16
0
ファイル: test_quadpack.py プロジェクト: 317070/scipy
    def test_triple_integral(self):
        # 9) Triple Integral test
        def simpfunc(z,y,x):      # Note order of arguments.
            return x+y+z

        a, b = 1.0, 2.0
        assert_quad(tplquad(simpfunc,a,b,
                            lambda x: x, lambda x: 2*x,
                            lambda x,y: x-y, lambda x,y: x+y),
                    8/3.0 * (b**4.0 - a**4.0))
コード例 #17
0
ファイル: potentials.py プロジェクト: alafuzof/pykCSD
def b_pot_3d_cont(x, R, h, sigma, basis_func):
    """
    Returns the value of the potential at point (x,y,0) generated
    by a basis source located at (0,0,0)
    """
    pot, err = integrate.tplquad(int_pot_3D, -R, R,
                                 lambda x: -R, lambda x: R,
                                 lambda x, y: -R, lambda x, y: R,
                                 args=(x, R, h, basis_func))
    pot *= 1./(2.0*pi*sigma)  # TODO check the constant
    return pot
コード例 #18
0
ファイル: utils.py プロジェクト: jainajinkya/deep_bingham
def eaad_bingham(bingham_z, integral_options=None):
    """ Expected Absolute Angular Deviation of Bingham Random Vector

    Arguments:
        bingham_z: Bingham dispersion parameter in the format expected by the
            manstats BinghamDistribution class.
        integral_options: Options to pass on to the scipy integrator for
            computing the eaad and the bingham normalization constant.
    """
    def aad(quat_a, quat_b):
        # acos_val = np.arccos(np.dot(quat_a, quat_b))
        # diff_ang = 2 * np.min([acos_val, np.pi - acos_val])
        acos_val = np.arccos(np.abs(np.dot(quat_a, quat_b)))
        diff_ang = 2 * acos_val
        return diff_ang

    if integral_options is None:
        integral_options = {"epsrel": 1e-4, "epsabs": 1e-4}

    bd = ms.BinghamDistribution(np.eye(4), bingham_z, {
        "norm_const_mode": "numerical",
        "norm_const_options": integral_options
    })

    def integrand_transformed(x):
        # To avoid unnecessary divisions, this term does not contain the
        # normalization constant. At the end, the result of the integration is
        # divided by it.
        return aad(x, bd.mode) \
               * np.exp(np.dot(x, np.dot(np.diag(bingham_z), x)))

    def integrand(phi1, phi2, phi3):
        sp1 = np.sin(phi1)
        sp2 = np.sin(phi2)
        return integrand_transformed(
            np.array([
                sp1 * sp2 * np.sin(phi3), sp1 * sp2 * np.cos(phi3),
                sp1 * np.cos(phi2),
                np.cos(phi1)
            ])) * (sp1**2.) * sp2

    eaad_int = integrate.tplquad(
        integrand,
        0.0,
        2.0 * np.pi,  # phi3
        lambda x: 0.0,
        lambda x: np.pi,  # phi2
        lambda x, y: 0.0,
        lambda x, y: np.pi,  # phi1
        **integral_options)

    return eaad_int[0] / bd.norm_const
コード例 #19
0
ファイル: bigQlmNum.py プロジェクト: JGLee6/PointGravity
def annulus(L, dens, h1, h2, IR, OR, phih):
    """
    Numerically integrates for the outer moments of an annulus using tplquad.
    The annular section has an axis of symmetry along zhat and extends
    vertically from h1 to h2, h2 > h1. Phih is defined to match qlm.annulus
    as the half-subtended angle so that the annular section subtends an angle
    of 2*phih, symmetric about the x-axis. The density is given by rho.
    Both the inner and outer radii (IR, OR) must be positive with IR < OR.

    Inputs
    ------
    LMax : int
        Maximum order of outer multipole moments.
    rho : float
        Density in kg/m^3
    h1 : float
        Starting z-location vertically along z-axis.
    h2 : float
        Ending z-location vertically along z-axis.
    IR : float
        Inner radius of annulus
    OR : float
        Outer radius of annulus
    phih : float
        Half angular width of annular section


    Returns
    -------
    Qlmb : ndarray
        (LMax+1)x(2LMax+1) complex array of outer moments
    """
    Qlmb = np.zeros([L+1, 2*L+1], dtype='complex')
    if (h1 > h2) or (OR < IR) or (phih <= 0) or (OR <= 0) or (phih > np.pi):
        raise ValueError('Unphysical parameter arguments')
    # Make sure this solid doesn't reach the origin
    if (h1 <= 0 <= h2) and (IR <= 0):
        raise ValueError('Unphysical parameter arguments')
    for l in range(L+1):
        for m in range(l+1):
            Qlmb[l, m+L], err = intg.tplquad(cyl_integrand_Qlmb, -phih, phih,
                                             IR, OR, h1, h2, args=(l, m))
            print(l, m, err)

    # Scale by density
    Qlmb *= dens
    # Moments always satisfy Q(l, -m) = (-1)^m Q(l, m)*
    ms = np.arange(-L, L+1)
    mfac = (-1)**(np.abs(ms))
    Qlmb += np.conj(np.fliplr(Qlmb))*mfac
    Qlmb[:, L] /= 2
    return Qlmb
コード例 #20
0
ファイル: util.py プロジェクト: ayshih/heroes
def heroes_atmospheric_attenuation(energy_range = (20, 30),
                                   altitude = (40, 40.1),
                                   elevation = (45, 45.1)):
    """First attempt, not fully tested and *very* slow"""
    f = lambda en, al, el: xray_transmission_in_atmosphere(en, al, view_angle=el)
    attenuation = integrate.tplquad(f, elevation[0], elevation[1],
                                    lambda el: altitude[0], lambda el: altitude[1],
                                    lambda el, al: energy_range[0], lambda el, al: energy_range[1])[0]
    attenuation /= energy_range[1]-energy_range[0]
    attenuation /= altitude[1]-altitude[0]
    attenuation /= elevation[1]-elevation[0]

    return attenuation
コード例 #21
0
 def getAnalyticSolutionIntegral(self, start, end):
     if self.dim == 3:
         f = lambda x, y, z: self.eval([x, y, z]) * self.eval_with_normal(
             [x, y, z])
         return integrate.tplquad(f, start[2], end[2], lambda x: start[1],
                                  lambda x: end[1], lambda x, y: start[0],
                                  lambda x, y: end[0])[0]
     elif self.dim == 2:
         f = lambda x, y: self.eval([x, y]) * self.eval_with_normal([x, y])
         return integrate.dblquad(f, start[1], end[1], lambda x: start[0],
                                  lambda x: end[0])[0]
     else:
         assert False
コード例 #22
0
def main():
    x1,x2=0,2
    y1,y2=lambda x:0,lambda x:1
    z1,z2=lambda x,y:0,lambda x,y:1
    
    #llamada a la funcion dblquad de scipy
    area,_=tplquad(f,    #funcion a integrar
                 x1,x2,  #limites de x
                 y1,y2,  #limites de y
                 z1,z2   #limites de z
                 ) 
                 
    print('quadrature = ',area)
コード例 #23
0
def Fg_tot(z, y, x):
    def Fg_curr(phi, theta, r):
        return Fg(phi, theta, r, x, y, z)

    f1 = integrate.tplquad(Fg_curr,
                           0.0,
                           D / 2.0,
                           lambda y: 0.0,
                           lambda y: math.pi,
                           lambda y, z: 0.0,
                           lambda y, z: 2.0 * math.pi,
                           epsabs=1e-2,
                           epsrel=1e-2)
    return f1[0]
コード例 #24
0
def integraltest(numsite, numorb, coors, coeff):
    n, l, Z = setorb()
    integrallist = setlist()
    for site1, site2, orb1, orb2 in integrallist:
        print('start')

        def func(x, y, z):
            return wf(site1, orb1, numsite, numorb, n, l, Z, coors, x, y, z,
                      coeff) * wf(site2, orb2, numsite, numorb, n, l, Z, coors,
                                  x, y, z, coeff)

        print(
            integrate.tplquad(func, -5, 5, lambda x: -5, lambda x: 5,
                              lambda x, y: -5, lambda x, y: 5))
コード例 #25
0
def do_slow_sph_integral(h, gx, gy):
    """Evaluate the very slow triple integral to find kernel contribution. Only do it when we must."""
    #z limits are -h - > h, for simplicity.
    #x and y limits are grid cells
    (weight, err) = integ.tplquad(sph_cart_wrap,
                                  -h,
                                  h,
                                  lambda x: gx,
                                  lambda x: gx + 1,
                                  lambda x, y: gy,
                                  lambda x, y: gy + 1,
                                  args=(h, ),
                                  epsabs=5e-3)
    return weight
コード例 #26
0
    def test_matching_tplquad(self):
        def func3d(x0, x1, x2, c0, c1):
            return x0**2 + c0 * x1**3 - x0 * x1 + 1 + c1 * np.sin(x2)

        res = tplquad(func3d,
                      -1,
                      2,
                      lambda x: -2,
                      lambda x: 2,
                      lambda x, y: -np.pi,
                      lambda x, y: np.pi,
                      args=(2, 3))
        res2 = nquad(func3d, [[-np.pi, np.pi], [-2, 2], (-1, 2)], args=(2, 3))
        assert_almost_equal(res, res2)
コード例 #27
0
 def normalize(psi, x1=-inf, x2=inf, y1=-inf, y2=inf, z1=-inf, z2=inf):
     if nParam(psi) == 1:
         a = integrate.quad(lambda x: abs(psi(x) * np.conj(psi(x))), x1, x2)
         return 1 / np.sqrt(float(a[0]))
     if nParam(psi) == 2:
         a = integrate.dblquad(
             lambda x, y: abs(psi(x, y) * np.conj(psi(x, y))), x1, x2, y1,
             y2)
         return 1 / np.sqrt(float(a[0]))
     if nParam(psi) == 3:
         a = integrate.tplquad(
             lambda x, y, z: abs(psi(x, y, z) * np.conj(psi(x, y, z))), x1,
             x2, y1, y2, z1, z2)
         return 1 / np.sqrt(float(a[0]))
コード例 #28
0
ファイル: KCSD.py プロジェクト: Neuroinflab/kCSD-python
 def forward_model(self, x, R, h, sigma, src_type):
     """FWD model functions
     Evaluates potential at point (x,0) by a basis source located at (0,0)
     Utlizies sk monaco monte carlo method if available, otherwise defaults
     to scipy integrate
     Parameters
     ----------
     x : float
     R : float
     h : float
     sigma : float
     src_type : basis_3D.key
     Returns
     -------
     pot : float
         value of potential at specified distance from the source
     """
     if src_type.__name__ == "gauss_3D":
         if x == 0: x=0.0001
         pot = special.erf(x/(np.sqrt(2)*R/3.0)) / x
     elif src_type.__name__ == "gauss_lim_3D":
         if x == 0: x=0.0001
         d = R/3.
         if x < R:
             e = np.exp(-(x / (np.sqrt(2)*d))**2)
             erf = special.erf(x / (np.sqrt(2)*d))
             pot = 4*np.pi * ((d**2)*(e - np.exp(-4.5)) +
                              (1/x)*((np.sqrt(np.pi/2)*(d**3)*erf) - x*(d**2)*e))
         else:
             pot = 15.28828*(d)**3 / x
         pot /= (np.sqrt(2*np.pi)*d)**3
     elif src_type.__name__ == "step_3D":
         Q = 4.*np.pi*(R**3)/3.
         if x < R:
             pot = (Q * (3 - (x/R)**2)) / (2.*R)
         else:
             pot = Q / x
         pot *= 3/(4*np.pi*R**3)
     else:
         pot, err = integrate.tplquad(self.int_pot_3D,
                                      -R,
                                      R,
                                      lambda x: -R,
                                      lambda x: R,
                                      lambda x, y: -R,
                                      lambda x, y: R,
                                      args=(x, R, h, src_type))
     pot *= 1./(4.0*np.pi*sigma)
     return pot
コード例 #29
0
def solve_2d_space_distributed_integral_system(
        g: tp.Callable[[float, float, float], float],
        us_list: tp.List[float],
        xyts_list: tp.List[tp.Tuple[float, float, float]],
        a: float,
        b: float,
        c: float,
        d: float,
        T: float,
) -> tp.Callable[[float, float, float], float]:
    """
    :param g: real-valued function of space and time.
        Maps x, y, t to G(x, y, t)
    :param us_list: list of length N,
        consisting of real values u(x_i, y_i, t_i)
    :param xyts_list: list of length N,
        consisting of space-time points (x_i, y_i, t_i).
        The equation is optimized at these points
    :param a: lower bound of the x-domains of g and u
    :param b: upper bound of the x-domains of g and u
    :param c: lower bound of the y-domains of g and u
    :param d: upper bound of the y-domains of g and u
    :param T: end time
    :return: real-valued function f of space and time,
        least squares solutions to
        int_c^d int_a^b int_0^T G(x - x_i, y - y_i, t - t_i) f(x, y, t) dt dx dy
            = u(x_i, y_i, t_i), i = 1..N.
    """

    class GfuncComputer:
        def __init__(self, x: float, y: float, t: float) -> None:
            self._x, self._y, self._t = x, y, t

        def __call__(self, x: float, y: float, t: float) -> float:
            return g(self._x - x, self._y - y, self._t - t)

    g_1 = [GfuncComputer(x_i, y_i, t_i) for x_i, y_i, t_i in xyts_list]

    vec_u = np.array([[u_i] for u_i in us_list])

    p_1 = np.matrix([[integrate.tplquad(
        lambda t, x, y: g_i(x, y, t) * g_j(x, y, t), c, d, a, b, 0, T
    )[0] for g_j in g_1] for g_i in g_1])

    def f(x: float, y: float, t: float) -> float:
        g_1_local = np.array([g_i(x, y, t) for g_i in g_1])
        return (g_1_local * np.linalg.pinv(p_1) * vec_u)[0, 0]

    return f
コード例 #30
0
def b_pot_3d_cont(x, R, h, sigma, basis_func):
    """
    Returns the value of the potential at point (x,y,0) generated
    by a basis source located at (0,0,0)
    """
    pot, err = integrate.tplquad(int_pot_3D,
                                 -R,
                                 R,
                                 lambda x: -R,
                                 lambda x: R,
                                 lambda x, y: -R,
                                 lambda x, y: R,
                                 args=(x, R, h, basis_func))
    pot *= 1. / (2.0 * pi * sigma)  # TODO check the constant
    return pot
コード例 #31
0
def bingham_normalization(lambdas, ):
    """Compute the Bingham normalization of concentration parameters.
    """
    assert len(lambdas) == 4
    f_integrand = functools.partial(bingham_integrand, lambdas=lambdas)

    return tplquad(f_integrand,
                   0.,
                   np.pi,
                   lambda a: 0.,
                   lambda a: np.pi,
                   lambda a, b: 0.,
                   lambda a, b: 2. * np.pi,
                   epsabs=1e-7,
                   epsrel=1e-3)
コード例 #32
0
 def force(self,surface):
     F = list()
     global p,rho,i,q_1  #making sure these values don't get lost in the class by definining them as global.
     rho = surface.rho # Wouldnt it be better to define this as a global variable within in the surface class 
     p = self.p
     q_1= self.q_1
     
     if surface.s=='sphere':
         for j in range(3): #cycling through the three dimensions of the force (because scipy doesn't do vector integration)
             i=j
             #tplquad returns the triple integral of the force
             F.append(tplquad(Force_element_sphere,0,np.pi,lambda theta:0, lambda theta: 2*np.pi,
                              lambda phi,theta: 0, lambda phi, theta: surface.dim,epsrel=0.4)[0]) 
    
     elif surface.s =='disk' :     
         for j in range(3):
             i=j
             #tplquad returns the triple integral of the force
             F.append(dblquad(Force_element_disk,0,2*np.pi,lambda theta: 0, lambda theta: surface.dim,epsrel=0.4)[0])
     
     elif surface.s=='torus':
         for j in range(3):
             i=j
             #tplquad returns the triple integral of the force
             F.append(tplquad(Force_element_torus,surface.dim-a,surface.dim+a,lambda r: 0,lambda r: np.sqrt(a**2 - (r-surface.dim)**2),
                              lambda z,r: 0, lambda z,r: 2*np.pi,epsrel=0.4)[0])
     
     
     elif surface.s=='cube':
         for j in range(3):
             i=j
             #tplquad returns the triple integral of the force
             F.append(tplquad(Force_element_cube,-surface.dim,surface.dim,lambda x: -surface.dim, lambda x: surface.dim, lambda x,y: -surface.dim, lambda x,y: surface.dim, epsrel=0.3)[0])
     
     
     return F
コード例 #33
0
ファイル: WignerSeitzABC.py プロジェクト: trvsst/aqpolypy
    def vol(self, dn, rad=0):
        """
        computes in d=2,3 the area (volume) of each wedge within the Wigner-Seitz cell

        :param dn: radius of the inscribed sphere (smallest of all distances)
        :param rad: radius of a cylinder(sphere) contained and whose center is at the origin of the wigner-seitz cell
        :return: area, volume (ndarray)
        """

        if rad > dn:
            return 0

        ws_vol = np.zeros(self.distinct_wedges)

        def ze(x):
            return 0

        if self.dim == 2:

            def fun(x, y):
                return y + rad

            def h(x):
                return self.h_size(x, dn, rad)

            for ind, wg in enumerate(self.wedges):
                a, b = wg[0]
                ws_vol[ind] = integrate.dblquad(fun, a, b, ze, h)
        elif self.dim == 3:

            def fun(z, y, x):
                return np.sin(y) * (z + rad)**2

            def h3(x, y):
                return self.h_size(y, dn, rad)

            def z3(x, y):
                return ze(y)

            for ind, wg in enumerate(self.wedges):
                a, b = wg[0]
                f1, f2 = wg[1]
                val = integrate.tplquad(fun, a, b, f1, f2, z3, h3)
                ws_vol[ind] = val[0]
        else:
            ws_vol[:] = dn - rad

        return ws_vol
コード例 #34
0
ファイル: utils.py プロジェクト: jainajinkya/deep_bingham
def eaad_von_mises(kappas, integral_options=None):
    """ Expected Absolute Angular Deviation of Bingham Random Vector

    Arguments:
        kappas: Von Mises kappa parameters for roll, pitch, yaw.
        integral_options: Options to pass on to the scipy integrator for
            computing the eaad and the bingham normalization constant.
    """
    def aad(quat_a, quat_b):
        acos_val = np.arccos(np.abs(np.dot(quat_a, quat_b)))
        diff_ang = 2.0 * acos_val
        return diff_ang

    if integral_options is None:
        integral_options = {"epsrel": 1e-2, "epsabs": 1e-2}

    param_mu = np.array([0., 0., 0.])  # radians
    quat_mu = convert_euler_to_quaternion(math.degrees(param_mu[0]),
                                          math.degrees(param_mu[1]),
                                          math.degrees(param_mu[2]))
    param_kappa = kappas

    direct_norm_const = 8.0 * (np.pi ** 3) \
        * scipy.special.iv(0, param_kappa[0]) \
        * scipy.special.iv(0, param_kappa[1]) \
        * scipy.special.iv(0, param_kappa[2])

    def integrand_aad(phi1, phi2, phi3):
        return np.exp(param_kappa[0] * np.cos(phi1)) \
               * np.exp(param_kappa[1] * np.cos(phi2)) \
               * np.exp(param_kappa[2] * np.cos(phi3)) \
               * aad(quat_mu,
                     convert_euler_to_quaternion(
                         math.degrees(phi1), math.degrees(phi2),
                         math.degrees(phi3)
                     ))

    eaad_int = integrate.tplquad(
        integrand_aad,
        0.0,
        2.0 * np.pi,  # phi3
        lambda x: 0.0,
        lambda x: 2. * np.pi,  # phi2
        lambda x, y: 0.0,
        lambda x, y: 2. * np.pi,  # phi1
        **integral_options)

    return eaad_int[0] / direct_norm_const
コード例 #35
0
def calculate_dE_1(K, beta, mu, density_of_state_scale):
    if beta > 0:
        min_x = min(K, mu + 1800 / beta) if beta > 0 else max(0, mu + 1800 / beta)
        max_x = min(2 * K, mu + 1800 / beta) if beta > 0 else max(2 * K, mu + 1800 / beta)
        min_y = lambda x: min(max(0, mu - 600 / beta), (2 * mu + 1200 / beta) - x)
        max_y = lambda x: min(max(2 * K - x, mu - 600 / beta), (2 * mu + 1200 / beta) - x)
        min_z = lambda x, y: max(min(x + y - K, mu + 600 / beta), x + y - (mu + 600 / beta))
        max_z = lambda x, y: max(min(K, mu + 600 / beta), x + y - (mu + 600 / beta))
    else:
        min_x = max(0, mu + 1800 / beta)
        max_x = max(2 * K, mu + 1800 / beta)
        min_y = lambda x: max(min(0, mu - 600 / beta), (2 * mu + 1200 / beta) - x)
        max_y = lambda x: max(min(2 * K - x, mu - 600 / beta), (2 * mu + 1200 / beta) - x)
        min_z = lambda x, y: min(max(x + y - K, mu + 600 / beta), x + y - (mu + 600 / beta))
        max_z = lambda x, y: min(max(K, mu + 600 / beta), x + y - (mu + 600 / beta))
    return  integrate.tplquad(dE_1_kernel, min_x, max_x, min_y, max_y, min_z, max_z, args=(beta, mu, density_of_state_scale))
コード例 #36
0
def normalize2(psi,lBound = -np.inf, rBound = np.inf, funcType='real'):
        if funcType.lower() == 'real':
            if type(lBound) == list:
                if len(lBound) == len(rBound):
                    if len(lBound) == 1:
                        a = integrate.quad(lambda x: psi(x)**2,lBound[0], rBound[0])
                        return 1/np.sqrt(float(a[0]))
                    if len(lBound) == 2:
                        a = integrate.dblquad(lambda x,y: psi(x,y)**2,lBound[0], rBound[0],lBound[1], rBound[1])
                        return 1/np.sqrt(float(a[0]))
                    if len(lBound) == 3:
                        a = integrate.tplquad(lambda x,y,z: psi(x,y,z)**2,lBound[0], rBound[0],lBound[1], rBound[1], lBound[2],rBound[2])
                        return 1/np.sqrt(float(a[0]))
            else:
                a = integrate.quad(lambda x: psi(x)**2,lBound, rBound)
                return 1/np.sqrt(float(a[0]))
コード例 #37
0
def _scipy_integrate(f, lb, ub):
    """
Returns the integral of an n-dimensional function f from lb to ub
(where n = 1, 2, or 3), using scipy.integrate

Inputs:
    f -- a function that takes a list and returns a number.
    lb -- a list of lower bounds
    ub -- a list of upper bounds
"""
    from scipy.integrate import quad, dblquad, tplquad
    if len(lb) == 3:

        def func(z, y, x):
            return f([x, y, z])

        def qf(x, y):
            return lb[2]

        def rf(x, y):
            return ub[2]

        def gf(x):
            return lb[1]

        def hf(x):
            return ub[1]

        expectation, confidence = tplquad(func, lb[0], ub[0], gf, hf, qf, rf)
        return expectation
    if len(lb) == 2:

        def func(y, x):
            return f([x, y])

        def gf(x):
            return lb[1]

        def hf(x):
            return ub[1]

        expectation, confidence = dblquad(func, lb[0], ub[0], gf, hf)
        return expectation
    if len(lb) == 1:
        expectation, confidence = quad(f, lb[0], ub[0])
        return expectation
コード例 #38
0
    def integral(r, R_sn):
    
        def q_adams(R,z):
            return ((R_sn)/(4*np.pi*H0*R0**2))*np.exp(-R/R0)*np.exp(-(np.abs(z))/H0)
    
    #f = lambda b, l, r: q_adams(R,z)*r**2*np.cos(b) 
    
        def integrand(b,l,r): 
            R = (R_sun**2+(r*np.cos(b))**2-2*R_sun*np.cos(b)*np.cos(l*r))**(1/2)
            z = r*np.sin(b)
            q=q_adams(R,z)
            return q*r**2*np.cos(b) 

    #f_TEST = lambda b,l,r: (r**2)*np.cos(b)
        i = integrate.tplquad(integrand, 0,r, lambda r: 0, lambda r: 2*np.pi,
                                    lambda r, l: -np.pi/2, lambda r, l: np.pi/2)      
        return (i)
コード例 #39
0
    def test_integration_3_vars(self):
        """Testing integration against brute-force solution for 3 processes.
        Should work in most cases"""
        counts = np.random.randint(0, 10, size=(3, 2))

        def integrand(p2, p1, p0):
            p = np.array([p0, p1, p2])
            return np.multiply.reduce(p**counts[:, 0] *
                                      (1.0 - p)**counts[:, 1])

        brute_force, err = igr.tplquad(integrand, 0.0001, 0.9999,
                                       lambda x: 0.0, lambda x: x,
                                       lambda x, y: 0.0, lambda x, y: y)
        brute_force = np.log(brute_force)
        sum_prod = integrate_log_p_joint(counts, 0.0001)

        self.assertAlmostEqual(brute_force, sum_prod, 5)
コード例 #40
0
 def prob(psi, lBound, rBound, lNorm=-inf, rNorm=inf):
     if nParam(psi) == 1:
         b = psiTools.normalize(lambda x: psi(x), lNorm, rNorm)
     if nParam(psi) == 2:
         b = psiTools.normalize(lambda x, y: psi(x, y), lNorm, rNorm)
     if nParam(psi) == 3:
         b = psiTools.normalize(lambda x, y, z: psi(x, y, z), lNorm, rNorm)
     if nParam(psi) == 1:
         a = quad(lambda x: (b * psi(x))**2, lBound, rBound)
     if nParam(psi) == 2:
         a = integrate.dblquad(lambda x, y: (b * psi(x, y))**2, lBound[0],
                               rBound[0], lBound[1], rBound[1])
     if nParam(psi) == 3:
         a = integrate.tplquad(lambda x, y, z: (b * psi(x, y, z))**2,
                               lBound[0], rBound[0], lBound[1], rBound[1],
                               lBound[2], rBound[2])
     return a[0]
コード例 #41
0
ファイル: tests.py プロジェクト: gaberosser/crime-fighter
    def test_mvn3d(self):
        mvn = kernels.MultivariateNormal([0, 0, 0], [1, 1, 1])
        self.assertEqual(mvn.ndim, 3)

        q = tplquad(partial(quad_pdf_fun, func=mvn.pdf), -5, 5, lambda x: -5, lambda x: 5, lambda x, y: -5, lambda x, y: 5)
        self.assertAlmostEqual(q[0], 1.0, places=5)

        # test with absolute values
        x = np.meshgrid(*([np.linspace(-1, 1, 10)]*3))
        x = np.vstack((x[0].flatten(), x[1].flatten(), x[2].flatten())).transpose().reshape(1000, 3)
        y = mvn.pdf(x)
        y_expct = multivariate_normal.pdf(x, mean=[0, 0, 0], cov=np.eye(3))
        self.assertEqual(np.sum(np.abs((y - y_expct)).flatten()>1e-12), 0) # no single difference > 1e-12

        # repeat with Data type
        x = DataArray(x)
        y = mvn.pdf(x)
        self.assertEqual(np.sum(np.abs((y - y_expct)).flatten()>1e-12), 0) # no single difference > 1e-12
コード例 #42
0
 def getAnalyticSolutionIntegral(self, start, end):
     if self.dim == 3:
         f = lambda x, y, z: self.eval_with_normal([x, y, z])
         normalization = 1
         for d in range(len(start)):
             S = norm.cdf(self.b_global[d]) - norm.cdf(self.a_global[d])
             normalization *= 1.0 / (S * math.sqrt(2 * math.pi * 1))
         return normalization * \
                integrate.tplquad(f, start[2], end[2], lambda x: start[1], lambda x: end[1], lambda x, y: start[0],
                                  lambda x, y: end[0])[0]
     elif self.dim == 2:
         f = lambda x, y: self.eval_with_normal([x, y])
         normalization = 1
         for d in range(len(start)):
             S = norm.cdf(self.b_global[d]) - norm.cdf(self.a_global[d])
             normalization *= 1.0 / (S * math.sqrt(2 * math.pi * 1))
         return normalization * integrate.dblquad(
             f, start[1], end[1], lambda x: start[0], lambda x: end[0])[0]
コード例 #43
0
def ball_tplquad(R, func):
    ylbound = lambda x: -np.sqrt(R**2 - x**2)
    yhbound = lambda x: np.sqrt(R**2 - x**2)
    zlbound = lambda x, y: -np.sqrt(R**2 - x**2 - y**2)
    zhbound = lambda x, y: np.sqrt(R**2 - x**2 - y**2)
    #e_abs = 1.5e-7
    #e_rel = 1e-4
    e_abs = 1.5e-8
    e_rel = 1.5e-8
    return integrate.tplquad(lambda z, y, x: func(x, y, z),
                             -R,
                             R,
                             ylbound,
                             yhbound,
                             zlbound,
                             zhbound,
                             epsabs=e_abs,
                             epsrel=e_rel)
コード例 #44
0
def get_integrated_Fz(z_mag):
    """Calculates the force on the magnet caused by the magnetic field of the
    solenoid. The magnet and solenoid axes are aligned, and z_mag measures the
    distance of the magnet center from the solenoid center.

    The integral calculates the total force by integrating B*M over the magnet
    volume in cylindrical coordinates.
    """
    return tplquad(
        lambda z, theta, r: M * get_dBdz(z) * r,
        0,
        r_mag,
        lambda theta: 0,
        lambda theta: 2 * np.pi,
        lambda theta, z: z_mag - l_mag / 2,
        lambda theta, phi: z_mag + l_mag / 2,
        epsabs=1e-04,
        epsrel=1e-04,
    )
コード例 #45
0
def Exact(f, ax, bx, ay, by, az, bz, numberOfVariables):
    f.replace("exp", "np.exp")
    f.replace("log", "np.log")
    if (numberOfVariables == 1):
        fe = lambda x: eval(f)
        exact = integrate.quad(fe, ax, bx)
        exact = exact[0]
        return exact
    if (numberOfVariables == 2):
        fe = lambda y, x: eval(f)
        exact = integrate.dblquad(fe, ax, bx, lambda x: ay, lambda x: by)
        exact = exact[0]
        return exact
    if (numberOfVariables == 3):
        fe = lambda z, y, x: eval(f)
        exact = integrate.tplquad(fe, ax, bx, lambda x: ay, lambda x: by,
                                  lambda x, y: az, lambda x, y: bz)
        exact = exact[0]
        return exact
コード例 #46
0
ファイル: tests.py プロジェクト: gaberosser/crime-fighter
    def test_norming(self):
        # 1D
        if self.min_nd < 2:
            q = quad(partial(quad_pdf_fun, func=self.kernels[1].pdf),
                     *self.limits(1))
            self.assertAlmostEqual(q[0], 1.0, places=self.tol_places)


        # 2D
        if self.min_nd < 3:
            q = dblquad(partial(quad_pdf_fun, func=self.kernels[2].pdf),
                        *self.limits(2)
                        )
            self.assertAlmostEqual(q[0], 1.0, places=self.tol_places)

        # 3D
        q = tplquad(partial(quad_pdf_fun, func=self.kernels[3].pdf),
                    *self.limits(3)
                    )
        self.assertAlmostEqual(q[0], 1.0, places=self.tol_places)
コード例 #47
0
def cyl_integral(function, cyl_radius, height, args):
    """
    Try to do a cylindrical integral of a function
    """
    from scipy.integrate import tplquad

    # z bounds
    qfun = lambda y,z: -height #0
    rfun = lambda y,z:  height #2*np.pi

    # y bounds
    gfun = lambda y: 0
    hfun = lambda y: 2*np.pi

    # x bounds
    llim_a = 0
    ulim_b = cyl_radius

    return tplquad(function, a=llim_a, b=ulim_b, gfun=gfun, hfun=hfun,
                   qfun=qfun, rfun=rfun, args=args)
コード例 #48
0
def volume(f, lambdaRange, muRange, thetaRange):
    """ Compute the volume within a prolate-spheroid region
    """
    from scipy.integrate import tplquad

    def jacobian(theta, mu, lmbda):
        """ Compute sqrt(det(G_ij)), where G_ij is the covariant
            metric tensor for the transformation from prolate-spheroid
            coordinates to rectangular cartesian
        """
        return f ** 3 * sinh(lmbda) * sin(mu) * (sinh(lmbda) ** 2 + sin(mu) ** 2)

    # Note: Function to integrate has arguments reversed compared
    # to order of limits in tplquad arguments
    vol, err = tplquad(jacobian,
        lambdaRange[0], lambdaRange[1],
        lambda l: muRange[0], lambda _: muRange[1],
        lambda l, m: thetaRange[0], lambda l, m: thetaRange[1],
        epsabs=1.0e-10, epsrel=1.0e-10)

    return vol
コード例 #49
0
def Compute_detection_rate(time_resolution,
                           channel_number,
                           DM_min,
                           DM_max,
                           f=Rate_integrand):
    '''
    Total number of detectable events per day for the instrument. 
    Return the triple integral of func(z, y, x) from x = a..b, y = gfun(x)..hfun(x), and z = qfun(x,y)..rfun(x,y).
    Note that the order of arguments are counter-intuitive: (z, y, x) 
    '''
    #return integrate.tplquad(f, -90.0, 90.0, lambda y: DM_min, lambda y: DM_max, lambda x: 0, lambda x: np.inf, args=[time_resolution, channel_number, DM_min, DM_max], epsabs=1e-4, epsrel=1e-4)
    return integrate.tplquad(
        f,
        -5.0,
        5.0,
        lambda x: DM_min,
        lambda x: DM_max,
        lambda x, y: 0,
        lambda x, y: np.inf,
        args=[time_resolution, channel_number, DM_min, DM_max],
        epsabs=1e-4,
        epsrel=1e-4)
コード例 #50
0
def sph_integral(function, sphere_radius, args):
    """
    Try to do a spherical integral of a function
    """
    from scipy.integrate import tplquad

    # x bounds
    qfun = lambda y,z: 0
    rfun = lambda y,z: sphere_radius

    # y bounds
    gfun = lambda y: 0
    hfun = lambda y: np.pi

    # z bounds
    llim_a = 0
    ulim_b = 2*np.pi

    def f(r,th,ph):
        return function(r,th,ph,*args) * r**2 * np.sin(th)

    return tplquad(f, a=llim_a, b=ulim_b, gfun=gfun, hfun=hfun,
                   qfun=qfun, rfun=rfun)
コード例 #51
0
def halo_integral(v_escape, v_circular):
    min_vel = velmin(m_chi)
    theta_min = 0
    theta_max = math.pi
    phi_min = 0
    phi_max = 2*math.pi
    #v_earth = velocityEarth()
    #v_earth_1 = v_earth[0]
    #v_earth_2 = v_earth[1]
    #v_earth_3 = v_earth[2]
    # use instead solar circular velocity as approximation:
    v_earth_1 = 0
    v_earth_2 = 220
    v_earth_3 = 0
    N_esc = normalisation(v_escape, v_circular)
    if min_vel <= v_escape:
    func =  lambda theta, phi, v: MaxwellB(N_esc, v, v_earth_1, v_earth_2, v_earth_3, theta, phi, v_circular)*v*math.sin(theta)
    else:
        func = lambda theta, phi, v: 0
        print(min_vel, v_escape)
        print("mass too small, so v_min larger than v_escape")
    halo_int = integrate.tplquad(func , min_vel, v_escape, lambda v: phi_min, lambda v: phi_max, lambda v, phi: theta_min, lambda v, phi: theta_max)
    return halo_int[0], min_vel
コード例 #52
0
ファイル: test_distributions.py プロジェクト: s-hertel/pymc3
def integrate_nd(f, domain, shape, dtype):
    if shape == () or shape == (1,):
        if dtype in continuous_types:
            return integrate.quad(f, domain.lower, domain.upper, epsabs=1e-8)[0]
        else:
            return sum(f(j) for j in range(domain.lower, domain.upper + 1))
    elif shape == (2,):
        def f2(a, b):
            return f([a, b])

        return integrate.dblquad(f2, domain.lower[0], domain.upper[0],
                                 lambda _: domain.lower[1],
                                 lambda _: domain.upper[1])[0]
    elif shape == (3,):
        def f3(a, b, c):
            return f([a, b, c])

        return integrate.tplquad(f3, domain.lower[0], domain.upper[0],
                                 lambda _: domain.lower[1],
                                 lambda _: domain.upper[1],
                                 lambda _, __: domain.lower[2],
                                 lambda _, __: domain.upper[2])[0]
    else:
        raise ValueError("Dont know how to integrate shape: " + str(shape))
コード例 #53
0
from scipy.integrate import tplquad
from scipy.special import jv

from scipy.integrate import tplquad
from numpy import pi, exp, sqrt

# def f(x):
#     return jv(2.5, x)
#
# x = np.linspace(0, 10)
# p = plt.plot(x, f(x), 'k-')
# plt.show()



def func(Vz,Vy,Vx):
    return (1.0/(sigma**2*2*pi)**(3./2)) * exp( - ( ((Vx**2)/2) + ((Vy**2)/2) + ((Vz**2)/2) )/sigma**2 )

def Vymax(Vx):
    return sqrt(Vmax**2 - Vx**2)

def Vzmax(Vx,Vy):
    return sqrt(Vmax**2 - Vx**2 - Vy**2)

Vmax = 500
sigma = 1

integral = tplquad(func,0,Vmax,lambda a: 0, Vymax,lambda a, y: 0, Vzmax)

print integral
コード例 #54
0

def diff_volume(p,t,r):
  return r**2*np.sin(t)
  
def new_diff_Uabs(p,t,r):
  out = interp(r,t,p)*r**2.*np.sin(t)
  #out = r**(1.22)*r**2.*np.sin(t)
  #print out
  #print r, t, p
  if isnan(out):
    print 'oh f**k'
    print r, t, p
    die
  else:
    return out

volume = tplquad(diff_volume, r1, r3, lambda r:   t1, lambda r:   t2,
                                      lambda r,t: p1, lambda r,t: p2)[0]
print 'volume check (' + str(4./3.*np.pi*(r3)**3.) + '): ' + str(volume)


Uabs_T = tplquad(new_diff_Uabs, r1, r3, lambda r:   t1, lambda r:   t2,
                                      lambda r,t: p1, lambda r,t: p2)[0]

eps0 = 8.854187E-12
mu0 = 4.*np.pi*1.E-7
Ap = np.pi*radshell*radshell
Qabs_corrected = Uabs_T/Ap/(1./2.*np.sqrt(eps0/mu0))
print 'my calc divided by sqrt(eps0/mu0) = ' + str(Qabs_corrected*1.E-6)
コード例 #55
0
from FuncDesigner import *
from openopt import IP
x, y, z = oovars('x y z') 
# f = ff(z, y, x)
# or 
f = exp(-(x+0.15)**2/(2*sigma)) / sqrt(2*pi*sigma) + cos(y)*sin(z)*cos(2*x) + 1e-1*x*y*z

domain = {x: bounds_x, y: bounds_y,  z: bounds_z}
p = IP(f, domain, ftol = 0.05)
r = p.solve('interalg', maxIter = 50000, maxActiveNodes = 150, maxNodes = 500000, iprint = 100)
print('interalg result: %f' % p._F)
''' Solver:   Time Elapsed = 2.03 	CPU Time Elapsed = 2.0
objFunValue: 0.24019923 (feasible, MaxResidual = 0.0470517)
interalg result: 0.240199 (usually solution, obtained by interalg, has real residual 10-100 times less 
than required tolerance, because interalg works with "most worst case" that extremely rarely occurs. 
Unfortunately, real obtained residual cannot be revealed).
Now let's ensure scipy.integrate tplquad fails to solve the problem and mere lies about obtained residual:'''

from scipy.integrate import tplquad
val, abserr = tplquad(ff, bounds_x[0], bounds_x[1], lambda y: bounds_y[0], lambda y: bounds_y[1], \
                      lambda y, z: bounds_z[0], lambda y, z: bounds_z[1])
print('scipy.integrate dblquad value: %f   declared residual: %f' % (val, abserr)) 
''' scipy.integrate tplquad value: 0.000000   declared residual: 0.000000
While scipy tplquad fails already for sigma = 10^-5, interalg works perfectly even for sigma  = 10^-10:
Solver:   Time Elapsed = 2.05 	CPU Time Elapsed = 2.06
interalg result: 0.240005 '''

# for bounds_z = (-0.2, 0.34) and sigma = 10^-5 interalg result: 0.328808 (ftol = 0.05, time elapsed ~ 1 min)
# scipy.integrate dblquad value: 0.004813   declared residual: 0.000000
コード例 #56
0
ファイル: reanalysis.py プロジェクト: cedavidyang/pyStRe
    def direct_msr(self, tol=1e-7, intLb=-6, intUb=6):
        def integrnd(beta, r, cutset, systype, *param):
            nparam = len(param)
            s = param
            ps = stats.norm.cdf((-beta - np.dot(r, s)) / np.sqrt(1 - np.sum(r ** 2, axis=-1)))
            if systype.lower() == "parallel":
                intval = np.prod(ps) * stats.multivariate_normal.pdf(s, mean=None, cov=np.eye(nparam))
            elif systype.lower() == "series":
                intval = np.prod(1 - ps) * stats.multivariate_normal.pdf(s, mean=None, cov=np.eye(nparam))
            if systype.lower() == "general":
                p = _prob_vector(ps)
                intval = np.dot(cutset.T, p) * stats.multivariate_normal.pdf(s, mean=None, cov=np.eye(nparam))
                # how to get cutset need to be further coded
            return intval

        systype = self.systype
        # cutset = self.cutset
        cutset = None
        beta = self.beta
        if (self.nCSrv is not None) and (self.rmtx is not None):
            ncsrv = self.nCSrv
            r = self.rmtx
        else:
            print ("assign common source random variables first")
            sys.exit(1)
        import scipy.integrate as intg

        if self.nCSrv == 1:
            intsol = intg.quad(lambda x: integrnd(beta, r, cutset, systype, x), intLb, intUb, epsabs=tol)
        elif self.nCSrv == 2:
            intsol = intg.dblquad(
                lambda x, y: integrnd(beta, r, cutset, systype, x, y),
                intLb,
                intUb,
                lambda x: intLb,
                lambda x: intUb,
                epsabs=tol,
            )
        elif self.nCSrv == 3:
            intsol = intg.tplquad(
                lambda x, y, z: integrnd(beta, r, cutset, systype, x, y, z),
                intLb,
                intUb,
                lambda x: intLb,
                lambda x: intUb,
                lambda x, y: intLb,
                lambda x, y: intUb,
                epsabs=tol,
            )
        else:
            print "Direct integration does not support nCSrv>3"
            sys.exit(1)

        if systype == "series":
            syspf = 1.0 - intsol[0]
        else:
            syspf = intsol[0]
        sysbeta = stats.norm.ppf(1 - syspf)
        results = ReliabilityResults(sysbeta, syspf)

        return results
コード例 #57
0
ファイル: Lab5.py プロジェクト: Slejpnir/Lab5
plt.legend(loc="best")
plt.xlabel("x")
plt.grid()
plt.show()

t=np.linspace(-1,1,10000)
def ff(der,t):
    xx,v,yy,w = der
    #yy,w=y_der[1]
    return [v,w+np.sin(t),w, -v*yy+np.cos(t)]
sol2 = odeint(ff,[0,0,0,0],t)
#import matplotlib.pyplot as plt
#plt.plot(t, sol2[:, 0], 'b', label='x(t)')
plt.plot(sol2[:, 0], sol2[:, 2], 'g', label='y(x)')
plt.legend(loc='best')
plt.xlabel('x')
plt.grid()
plt.show()

x1 = lambda x: x*np.sin(x)
print(integrate.quad(x1, 0, 1))
x2=lambda x,y:x*np.cos(x+y)
gfun=lambda x:0
hfun=lambda x:1
print(integrate.dblquad(x2, 0, 1,gfun,hfun))
x3=lambda x,y,z:1
gfun3=lambda x:0
hfun3=lambda x:1
rfun3=lambda x,y:0
qfun3=lambda x,y:1
print(integrate.tplquad(x3, 0, 1,gfun3,hfun3,rfun3,qfun3))
コード例 #58
0
ファイル: test_prior.py プロジェクト: jmeyers314/DPMM
def test_NormInvWish(full=False):
    mu_0 = np.r_[0.2, 0.1]
    kappa_0 = 2.0
    Lam_0 = np.eye(2)+0.1
    nu_0 = 3

    # Create a Normal-Inverse-Wishart prior.
    niw = dpmm.NormInvWish(mu_0, kappa_0, Lam_0, nu_0)

    # Check that we can draw samples from NormInvWish.
    niw.sample()
    niw.sample(size=10)

    # Check that we can evaluate a likelihood given data.
    theta = np.zeros(1, dtype=niw.model_dtype)
    theta['mu'] = np.r_[1.0, 1.0]
    theta['Sig'] = np.eye(2)+0.12
    D = np.array([[0.1, 0.2], [0.2, 0.3], [0.1, 0.2], [0.4, 0.3]])
    niw.likelihood(D, theta)

    # Evaluate prior
    niw(theta)

    if __name__ == "__main__" and full:
        # Check prior predictive density
        with warnings.catch_warnings():
            warnings.simplefilter('ignore')
            r = dblquad(lambda x, y: niw.pred(np.r_[x, y]), -np.inf, np.inf,
                        lambda x: -np.inf, lambda x: np.inf)
        np.testing.assert_almost_equal(r[0], 1.0, 5,
                                       "NormInvWish prior predictive density does not integrate to 1.0")

    # Check posterior predictive density
    r = dblquad(lambda x, y: niw.post(D).pred(np.r_[x, y]), -np.inf, np.inf,
                lambda x: -np.inf, lambda x: np.inf)
    np.testing.assert_almost_equal(
        r[0], 1.0, 5, "NormInvWish posterior predictive density does not integrate to 1.0")

    # Check that the likelihood of a single point in 2 dimensions integrates to 1.
    r = dblquad(lambda x, y: niw.like1(np.r_[x, y], np.r_[1.2, 1.1], np.eye(2)+0.12),
                -np.inf, np.inf, lambda x: -np.inf, lambda x: np.inf)
    np.testing.assert_almost_equal(r[0], 1.0, 10,
                                   "NormInvWish likelihood does not integrate to 1.0")

    if __name__ == "__main__" and full:
        # Check that likelihood of a single point in 3 dimensions integrates to 1.
        niw3 = dpmm.NormInvWish(np.r_[1, 1, 1], 2.0, np.eye(3), 3)
        r = tplquad(lambda x, y, z: niw3.like1(np.r_[x, y, z], np.r_[0.1, 0.2, 0.3], np.eye(3)+0.1),
                    -np.inf, np.inf,
                    lambda x: -np.inf, lambda x: np.inf,
                    lambda x, y: -np.inf, lambda x, y: np.inf)
        np.testing.assert_almost_equal(r[0], 1.0, 8,
                                       "NormInvWish likelihood does not integrate to 1.0")

    # Check that posterior is proportional to prior * likelihood
    D = np.array([[0.1, 0.2], [0.2, 0.3], [0.1, 0.2], [0.4, 0.3]])
    mus = [np.r_[2.1, 1.1], np.r_[0.9, 1.2], np.r_[0.9, 1.1]]
    Sigs = [np.eye(2)*1.5, np.eye(2)*0.7, np.array([[1.1, -0.1], [-0.1, 1.2]])]
    posts = [niw.post(D)(mu, Sig) for mu, Sig in zip(mus, Sigs)]
    posts2 = [niw(mu, Sig)*niw.likelihood(D, mu, Sig) for mu, Sig, in zip(mus, Sigs)]

    np.testing.assert_array_almost_equal(
        posts/posts[0], posts2/posts2[0], 5,
        "NormInvWish posterior not proportional to prior * likelihood.")

    # Check that posterior = prior * likelihood / evidence
    mus = [np.r_[1.1, 1.1], np.r_[1.1, 1.2], np.r_[0.7, 1.3]]
    Sigs = [np.eye(2)*0.2, np.eye(2)*0.1, np.array([[2.1, -0.1], [-0.1, 2.2]])]
    post = niw.post(D)
    post1 = [niw(mu, Sig) * niw.likelihood(D, mu, Sig) / niw.evidence(D)
             for mu, Sig in zip(mus, Sigs)]
    post2 = [post(mu, Sig) for mu, Sig in zip(mus, Sigs)]
    np.testing.assert_array_almost_equal(post1, post2, 10,
                                         "NormInvWish posterior != prior * likelihood / evidence")
コード例 #59
0
from scipy import integrate

def f(x, y, z):  return x*y*z

print(integrate.tplquad(f, 0, 1,\
                     lambda x:0, lambda x:1,\
                     lambda x,y:0, lambda x,y:1 ))
#(0.010416666666666668, 4.101620128472366e-16)
print(integrate.nquad(f, [[0.0,1.0],[0.0,1],[0,1]] ))

コード例 #60
0
LowerLimit_y = 0.0
UpperLimit_y = 2.0

LowerLimit_z = 0.0
UpperLimit_z = 3.0

#Defining Function
def function(x,y,z):
	return (x**2)+(y**2)+(z**2)

# Turning the constant limits into a function. This makes the code callable (work).
def Lfy(x): # The function is in terms of x (constant).
	return LowerLimit_y
def Ufy(x):
	return UpperLimit_y

def Lfz(x,y): # The function is in terms of x and y (constant).
	return LowerLimit_z
def Ufz(x,y):
	return UpperLimit_z

#Using Scipy.Integrate.dblQuad inputs of the function, the lower integration limit and the upper integration limit	
Answer = tplquad(function,LowerLimit_x,UpperLimit_x,Lfy,Ufy,Lfz,Ufz)

#Returns the Definite intergral and an estimate of the absolute error in an array
#Answer[0] (first term) = The numerical value for the integration
#Answer[1] (second term) = The Error on your integration
print Answer