本文整理汇总了Python中scipy.integrate.romb函数的典型用法代码示例。如果您正苦于以下问题:Python romb函数的具体用法?Python romb怎么用?Python romb使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了romb函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: clarray
def clarray(aps, lmax, zarray, zromb=3, zwidth=None):
"""Calculate an array of C_l(z, z').
Parameters
----------
aps : function
The angular power spectrum to calculate.
lmax : integer
Maximum l to calculate up to.
zarray : array_like
Array of z's to calculate at.
zromb : integer
The Romberg order for integrating over frequency samples.
zwidth : scalar, optional
Width of frequency channel to integrate over. If None (default),
calculate from the separation of the first two bins.
Returns
-------
aps : np.ndarray[lmax+1, len(zarray), len(zarray)]
Array of the C_l(z,z') values.
"""
if zromb == 0:
return aps(np.arange(lmax+1)[:, np.newaxis, np.newaxis],
zarray[np.newaxis, :, np.newaxis], zarray[np.newaxis, np.newaxis, :])
else:
zsort = np.sort(zarray)
zhalf = np.abs(zsort[1] - zsort[0]) / 2.0 if zwidth is None else zwidth / 2.0
zlen = zarray.size
zint = 2**zromb + 1
zspace = 2.0*zhalf / 2**zromb
za = (zarray[:, np.newaxis] + np.linspace(-zhalf, zhalf, zint)[np.newaxis, :]).flatten()
lsections = np.array_split(np.arange(lmax+1), lmax / 50)
cla = np.zeros((lmax+1, zlen, zlen), dtype=np.float64)
for lsec in lsections:
clt = aps(lsec[:, np.newaxis, np.newaxis],
za[np.newaxis, :, np.newaxis], za[np.newaxis, np.newaxis, :])
clt = clt.reshape(-1, zlen, zint, zlen, zint)
clt = si.romb(clt, dx=zspace, axis=4)
clt = si.romb(clt, dx=zspace, axis=2)
cla[lsec] = clt / (2*zhalf)**2 # Normalise
return cla
示例2: ricker_int_1d
def ricker_int_1d(p, u):
"""Equação a diferenças do tipo Ricker com difusão espacial:
v[t+1] (x) = a * \int K(y-x) * v[t](y) * exp(-g * v[t](y)) dy
Com K(y-x) := exp(-(y-x)^2 / s^2)
v representa uma população de larvas.
"""
n = len(u) - 1
uu = np.zeros(u.size)
for i in range(1, u.size):
uu[i] = p['a'] * romb(u * np.exp(- p['g'] * u) * p['K'][n-i:-i], p['dx'])
uu[0] = p['a'] * romb(u * np.exp(- p['g'] * u) * p['K'][n:], p['dx'])
return [uu]
示例3: calc_ip_numint
def calc_ip_numint(f, g, rs, method=0):
"""
f : continuum wave function
g : L2 function which is not normalized
"""
fgs = np.array([f(r) * g(r) for r in rs])
ggs = np.array([g(r) * g(r) for r in rs])
if method == 0:
int_fgs = integrate.simps(fgs, rs)
int_ggs = integrate.simps(ggs, rs)
else:
int_fgs = integrate.romb(fgs, rs[1]-rs[0])
int_ggs = integrate.romb(ggs, rs[1]-rs[0])
return int_fgs / np.sqrt(int_ggs)
示例4: integrate_f_jnjn
def integrate_f_jnjn(f, n, mean, delta, x_max):
"""Doesn't work for n=0, because we set f=0 for the first point.
"""
if n == 0:
raise NotImplementedError()
x_max = float(x_max)
mean = float(mean)
delta = float(delta)
# Reduce x_max if envelope is significant.
if delta == 0:
envelop_width = 1000 * x_max
else:
envelop_width = 5 * (2 * np.pi / delta)
x_max = min(x_max, 5 * envelop_width)
x, ntuple, delta_tuple = sample_jnjn(n, mean, delta, x_max)
# Envelope of a Gaussian with width of several oscillations. This
# controls the oscillations out to high k.
envelope = np.exp(-0.5*(x - n / mean)**2 / envelop_width**2)
f_eval = np.empty_like(x)
f_eval[0] = 0
f_eval[1:] = f(x[1:])
lower = np.s_[:ntuple[0] + 1]
jnjn_lower = np.empty_like(x[lower])
jnjn_lower[0] = 0
jnjn_lower[1:] = jnjn(n, mean, delta, x[lower][1:])
integral = integrate.romb(f_eval[lower] * jnjn_lower, dx=delta_tuple[0])
if ntuple[1]:
upper = np.s_[ntuple[0]:]
jnjn_upper = approx_jnjn(n, mean, delta, x[upper])
integral += integrate.romb(f_eval[upper] * jnjn_upper * envelope[upper],
dx=delta_tuple[1])
# XXX
#print "n points:", ntuple
#plt.plot(x[lower], jnjn_lower * f_eval[lower])
#plt.plot(x[upper], jnjn_upper * f_eval[upper])
#plt.plot(x[lower], jnjn_lower * f_eval[lower] * envelope[lower])
#plt.plot(x[upper], jnjn_upper * f_eval[upper] * envelope[upper])
#plt.show()
return integral
示例5: spectralWeight
def spectralWeight(self, limits=None):
"""Calculates the spectral weight of the model. If an energy
window is give, a partial spectral weight is returned.
Parameter:
limits -- A tuple indicating beginning and end where to calculate
the partial spectral weight of the model.
Returns:
The calculated dielectric function.
"""
_sw = 0.0
if not limits:
for oscillator in self.__oscillators:
_sw += oscillator.spectralWeight
else:
# Using Romberg: See http://young.physics.ucsc.edu/242/romberg.pdf
interval = limits[1]-limits[0]
# Finding minimal k for a smaller than 0.02 integration step
k = ceil(log(interval/0.02-1)/log(2))
# Determining final step size
dx = interval/(2.0**k)
# Create a 2**k+1 equally spaced sample
x = np.linspace(limits[0], limits[1], 2**k+1)
_sw = romb(np.imag(self.dielectricFunction(x)), dx)
return _sw
示例6: dlnsdlnM
def dlnsdlnM(self,M):
"""
Uses a top-hat window function to calculate |dlnsigma/dlnM| at a given radius.
Input: R: the radius of the top-hat function.
Output: integral: the derivatiave of log sigma with respect to log Mass.
"""
R = self.Radius(M)
# define the vector g = kR
g = np.exp(self.k_extended)*R
# Find the mass variance.
sigma = np.sqrt(self.MassVariance(M))
# Define the derivative of the window function squared.
window = (np.sin(g)-g*np.cos(g))*(np.sin(g)*(1-3.0/(g**2))+3.0*np.cos(g)/g)
# Compile into the integrand.
integrand = (np.exp(self.power_spectrum)/np.exp(self.k_extended))*window
# Integrate using romberg integration and multiply by pre-factors.
integral =(3.0/(2.0*sigma**2*np.pi**2*R**4))*intg.romb(integrand,dx=self.steps)
return integral
示例7: integrator_linspace
def integrator_linspace(y, dx=1, method="simps", axis=-1):
"""
Integrate y using samples along the given axis with spacing dx.
method is in ['simps', 'trapz', 'romb']. Note that romb requires len(y) = 2**k + 1.
Example:
>>> nx = 2**8+1
>>> x = np.linspace(0, np.pi, nx)
>>> dx = np.pi/(nx-1)
>>> y = np.sin(x)
>>> for method in ["simps", "trapz", "romb"]: print(integrator_linspace(y, dx=dx, method=method))
2.00000000025
1.99997490024
2.0
"""
from scipy.integrate import simps, trapz, romb
if method == "simps":
return simps(y, x=None, dx=dx, axis=axis, even='avg')
elif method == "trapz":
return trapz(y, x=None, dx=dx, axis=axis)
elif method == "romb":
return romb(y, dx=dx, axis=axis, show=False)
else:
raise ValueError("Wrong method: %s" % method)
示例8: diff_off_diag
def diff_off_diag(p, u, v):
"""Equação a diferenças tipo logística com difusão espacial:
u[t+1] (x) = a1 * v[t] * (1 - g1 * v[t])
v[t+1] (x) = a2 * \int K(y-x) * u[t](y) dy
Com K(y-x) := exp(-(y-x)^2 / s^2)
u representa uma população de moscas e v a quantidade de larvas.
"""
n = len(u) - 1
uu = p['a1'] * v * (1 - p['g1'] * v)
vv = np.zeros(v.size)
for i in range(1, v.size):
vv[i] = p['a2'] * romb(u * p['K'][n-i:-i], p['dx'])
vv[0] = p['a2'] * romb(u * p['K'][n:], p['dx'])
return [uu, vv]
示例9: _compute_std_romberg
def _compute_std_romberg(self, psi, p_sep, xmin, xmax):
'''
Compute the variance of the distribution function psi from xmin to xmax
along the contours p_sep using numerical integration methods.
'''
x_arr = np.linspace(xmin, xmax, 257)
dx = x_arr[1] - x_arr[0]
Q, V = 0, 0
for x in x_arr:
y = np.linspace(0, p_sep(x), 257)
dy = y[1] - y[0]
z = psi(x, y)
Q += romb(z, dy)
z = x**2 * psi(x, y)
V += romb(z, dy)
Q *= dx
V *= dx
return np.sqrt(V/Q)
示例10: test_romb_gh_3731
def test_romb_gh_3731(self):
# Check that romb makes maximal use of data points
x = np.arange(2 ** 4 + 1)
y = np.cos(0.2 * x)
val = romb(y)
val2, err = quad(lambda x: np.cos(0.2 * x), x.min(), x.max())
assert_allclose(val, val2, rtol=1e-8, atol=0)
# should be equal to romb with 2**k+1 samples
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=AccuracyWarning)
val3 = romberg(lambda x: np.cos(0.2 * x), x.min(), x.max(), divmax=4)
assert_allclose(val, val3, rtol=1e-12, atol=0)
示例11: test_romb_gh_3731
def test_romb_gh_3731(self):
# Check that romb makes maximal use of data points
x = np.arange(2**4+1)
y = np.cos(0.2*x)
val = romb(y)
val2, err = quad(lambda x: np.cos(0.2*x), x.min(), x.max())
assert_allclose(val, val2, rtol=1e-8, atol=0)
# should be equal to romb with 2**k+1 samples
with suppress_warnings() as sup:
sup.filter(AccuracyWarning, "divmax .4. exceeded")
val3 = romberg(lambda x: np.cos(0.2*x), x.min(), x.max(), divmax=4)
assert_allclose(val, val3, rtol=1e-12, atol=0)
示例12: Cmp_XC_Energy
def Cmp_XC_Energy(Nc,MM,LL,mumesh,Ximesh,in12,index,R0,FX=1.0,FC=1.0):
"Computes XC energy within LDA"
code1="""
#line 117 "LDA.py"
double rho=0.0;
for (int i=0; i<an12.extent(0); i++){
int i1 = andex(an12(i,0));
int i2 = andex(an12(i,1));
rho += MM(i1,ix)*LL(i1,ir)*Nc(i)*MM(i2,ix)*LL(i2,ir);
}
return_val = rho/(2*M_PI*R0*R0*R0/8);
"""
exc = ExchangeCorrelation()
Exc = zeros((len(mumesh),len(Ximesh)),dtype=float)
an12 = array(in12)
andex = array(index)
for ix,eta in enumerate(mumesh):
for ir,xi in enumerate(Ximesh):
rho = weave.inline(code1, ['ir', 'ix', 'Nc','an12','andex','MM','LL','R0'], type_converters=weave.converters.blitz, compiler = 'gcc')
if rho<0.0:
print 'WARNING: rho<0 for ', eta, xi, 'rho=', rho
#print 'Nc=', Nc
#dsum=0.0
#for i,(i1,i2) in enumerate(in12):
# print i1, i2, MM[i1,ix]*LL[i1,ir]*Nc[i]*MM[i2,ix]*LL[i2,ir], dsum
# dsum += MM[i1,ix]*LL[i1,ir]*Nc[i]*MM[i2,ix]*LL[i2,ir]
rho=1e-300
rs = pow(3/(4*pi*rho),1/3.)
Exc[ix,ir] = (2*exc.Ex(rs)*rho*FX + 2*exc.Ec(rs)*rho*FC)*(xi**2-eta**2)*(2*pi*R0**3/8)
Ene = zeros(len(mumesh),dtype=float)
for ix,eta in enumerate(mumesh):
Ene[ix] = integrate.romb(Exc[ix,:]*(Ximesh-1.),dhXi)
return integrate.romb(Ene,mumesh[1]-mumesh[0])
示例13: kpc2pix
def kpc2pix(H, Om, z0):
''' Converts physical distances in kiloparsec to Chandra pixels at redshift z0
H = Hubble constant in km/sec/Mpc
Om = total matter density
'''
N = 64 # Number of evaluation points
c = 3e5 # speed of light in km/s
z = linspace(0, z0, N+1)
E = sqrt( Om*(1+z)**3 + 1-Om )
dC = 1e3 * c/H * romb(1/E, 1.*z0/N) # Comoving distance in Mpc
dA = dC / (1+z0) # Angular diameter distance
rad2arcsec = 180*3600/pi
px2arcsec = 0.492
return 1/dA * rad2arcsec / px2arcsec #kpc2px
示例14: cmp_MPM
def cmp_MPM(Ny, maxm,maxl, ist, ak, Modd):
Xx = linspace(-1,1,Ny)
MPM = zeros((len(ist),maxl+1),dtype=float)
MPxM = zeros((len(ist),maxl+1),dtype=float)
for i,(i1,i2) in enumerate(ist):
(R1,Ene1,m1,p1,A1) = Sol[i1]
(R2,Ene2,m2,p2,A2) = Sol[i2]
print 'i1=', i1, 'i2=', i2, 'm1=', m1, 'm2=', m2 #, MPM,MPxM
m = abs(m1-m2)
Plm_all = array([special.lpmn(maxm,maxl,x)[0] for x in Xx])
MM = array([Mm(x,m1,p1,ak[i1]) * Mm(x,m2,p2,ak[i2]) for x in Xx])
Plm = transpose(Plm_all[:,m])
for il in range(m,maxl+1):
odd = (Modd[i1]+Modd[i2]+il+m)%2
if not odd: # If the function is odd, we do not calculate!
MMP = MM*Plm[il,:]
MMPx = MMP * Xx**2
MPM [i,il] = integrate.romb(MMP, Xx[1]-Xx[0])
MPxM[i,il] = integrate.romb(MMPx,Xx[1]-Xx[0])
return (MPM,MPxM)
示例15: test_marginalization
def test_marginalization():
# Integrating out one of the variables of a 2D Gaussian should
# yield a 1D Gaussian
mean = np.array([2.5, 3.5])
cov = np.array([[.5, 0.2], [0.2, .6]])
n = 2 ** 8 + 1 # Number of samples
delta = 6 / (n - 1) # Grid spacing
v = np.linspace(0, 6, n)
xv, yv = np.meshgrid(v, v)
pos = np.empty((n, n, 2))
pos[:, :, 0] = xv
pos[:, :, 1] = yv
pdf = multivariate_normal.pdf(pos, mean, cov)
# Marginalize over x and y axis
margin_x = romb(pdf, delta, axis=0)
margin_y = romb(pdf, delta, axis=1)
# Compare with standard normal distribution
gauss_x = norm.pdf(v, loc=mean[0], scale=cov[0, 0] ** 0.5)
gauss_y = norm.pdf(v, loc=mean[1], scale=cov[1, 1] ** 0.5)
assert_allclose(margin_x, gauss_x, rtol=1e-2, atol=1e-2)
assert_allclose(margin_y, gauss_y, rtol=1e-2, atol=1e-2)