예제 #1
0
def test_gh295():
    def f(x):
        return 1e-20 * numpy.sin(x)

    # import scipy.integrate
    # out = scipy.integrate.quad(f, 0.0, 1.0, epsabs=0.0, epsrel=1.0e-10)
    quadpy.quad(f, 0.0, 1.0, epsabs=1.0e-8, epsrel=1.0e-8)
예제 #2
0
def test_infinite_limits():
    tol = 1.0e-9
    val, err = quadpy.quad(lambda x: numpy.exp(-(x**2)), -numpy.inf, numpy.inf)
    assert abs(val - numpy.sqrt(numpy.pi)) < tol
    assert err < tol

    val, err = quadpy.quad(lambda x: numpy.exp(-x), 0.0, numpy.inf)
    assert abs(val - 1.0) < tol
    assert err < tol

    val, err = quadpy.quad(lambda x: numpy.exp(+x), -numpy.inf, 0)
    assert abs(val - 1.0) < tol
    assert err < tol
예제 #3
0
def calculate_nth_constant(
        n: int, constant_func: FLOAT_TO_COMPLEX) -> complex:

    def array_f(array: np.array):
        return np.array(list(map(constant_func, array)))

    return quad(array_f, 0., 1., limit=30000)[0]
예제 #4
0
def test_236():
    # https://github.com/nschloe/quadpy/issues/236
    def f(x):
        return numpy.exp(-1.0 / (1 - x**2))

    val, err = quadpy.quad(f, -1, 1)
    assert err < 1.0e-9
예제 #5
0
def test_245():
    # https://github.com/nschloe/quadpy/issues/245
    def f(x):
        return x + x * 1j

    val, err = quadpy.quad(f, 0, 1)
    assert err < 1.0e-9
예제 #6
0
def test_args():
    val, err = quadpy.quad(lambda x, a: numpy.sin(a * x) - x,
                           0.0,
                           6.0,
                           args=(1, ))

    ref = -17 - numpy.cos(6)
    assert abs(val - ref) < 1.0e-8 * abs(ref)
예제 #7
0
def test_complex_valued():
    def f(x):
        return numpy.exp(1j * x)

    # import scipy.integrate
    # out = scipy.integrate.quad(f, 0.0, 1.0, epsabs=0.0, epsrel=1.0e-10)
    val, _ = quadpy.quad(f, 0.0, 1.0, epsabs=1.0e-8, epsrel=1.0e-8)
    exact = numpy.sin(1.0) - 1j * (numpy.cos(1.0) - 1.0)
    assert numpy.abs(val - exact) < 1.0e-10
예제 #8
0
def test_gh255a():
    # https://github.com/nschloe/quadpy/issues/255
    T = 2 * numpy.pi

    def ex1(t):
        return numpy.where(numpy.logical_and((t % T >= 0), (t % T < numpy.pi)),
                           t % T, numpy.pi)

    a = 3.15
    val, err = quadpy.quad(ex1, 0.0, a, epsabs=1.0e-13)

    ref = 0.5 * numpy.pi**2 + (a - numpy.pi) * numpy.pi

    assert abs(val - ref) < 1.0e-8 * abs(ref), "\n" + "\n".join([
        f"reference = {ref}", f"computed  = {val}",
        f"error     = {abs(val-ref)}"
    ])
예제 #9
0
def test_gh255b():
    # https://github.com/nschloe/quadpy/issues/255
    T = 2 * numpy.pi

    def ex1(t):
        return numpy.where(numpy.logical_and((t % T >= 0), (t % T < numpy.pi)),
                           t % T, numpy.pi)

    a = 6.3
    val, err = quadpy.quad(ex1, 0.0, a, epsabs=1.0e-13, limit=100)

    # ref = 14.804547973620716
    ref = 1.5 * numpy.pi**2 + (a - 2 * numpy.pi)**2 / 2
    assert abs(val - ref) < 1.0e-8 * abs(ref), "\n" + "\n".join([
        f"reference = {ref}", f"computed  = {val}",
        f"error     = {abs(val-ref)}"
    ])
예제 #10
0
def test_sin_x():
    val, err = quadpy.quad(lambda x: numpy.sin(x) - x, 0.0, 6.0)

    ref = -17 - numpy.cos(6)
    assert abs(val - ref) < 1.0e-8 * abs(ref)
예제 #11
0
 def V(x):
     return qp.quad(compute_2, low, high, args=(x, ))[0]
예제 #12
0
        def quad_fn(x):
            v, e = quad(x, a=self.int_lower, b=self.int_upper)

            assert np.all(e < 1e-6)
            return v
예제 #13
0
def test_x():
    val, _ = quadpy.quad(lambda x: x, -1.0, 1.0)
    exact = 0.0
    assert abs(exact - val) < 1.0e-10
예제 #14
0
def test_ln():
    val, err = quadpy.quad(lambda x: numpy.log(x), 0.5, 5.0)

    ref = (numpy.log(5) * 5 - 5) - (numpy.log(0.5) * 0.5 - 0.5)
    assert abs(val - ref) < 1.0e-8 * abs(ref)
예제 #15
0
def test_vector():
    val, err = quadpy.quad(lambda x: [numpy.sin(x) - x, x], 0.0, 6.0)

    ref = [-17 - numpy.cos(6), 18]
    assert numpy.all(numpy.abs(val - ref) < 1.0e-8 * numpy.abs(ref))
예제 #16
0
 def pi_hat_star(u, x):  # action given state
     numerator = compute(u, x)
     denominator = qp.quad(compute, low, high, args=(x, ))[0]
     return numerator / denominator
예제 #17
0
def Fish(cosmo,
         kmin,
         kmax,
         data,
         iz,
         recon,
         derPalpha,
         BAO_only=True,
         GoFast=False):
    """ Computes the Fisher information on cosmological parameters biases*sigma8, fsigma8, alpha_perp and alpha_par
        for a given redshift bin by integrating a separate function (CastNet) over k and mu.

    Parameters
    ----------
    cosmo: CosmoResults object
        An instance of the CosmoResults class. Holds the power spectra, BAO damping parameters and
        other cosmological parameters such as f and sigma8 as a function of redshift.
    data: InputData object
        An instance of the InputData class. Holds the galaxy bias and number density for each sample
        as a function of redshift
    iz: int
        The index of the redshift bin we are considering. Used to access the correct parts of data,
        cosmo, recon.
    recon: np.ndarray
        An array containing the expected reduction in BAO damping scales at each redshift. Pre-computed
        using the compute_recon function.
    derPalpha: list
        A list containing 2 scipy.interpolate.RegularGridInterpolator instances. Each one holds an object that
        can be called to return the derivative of power spectrum (full or BAO_only) at a particular k or mu
        value. The first element in the list is dP(k')/alpha_perp, the second is dP(k')/dalpha_par
    BAO_only: logical
        If True compute derivatives w.r.t. to alpha_perp and alpha_par using only the BAO feature in the
        power spectra. Otherwise use the full power spectrum and the kaiser factor. The former matches a standard
        BAO analysis, the latter is more akin to a 'full-shape' analysis. Default = True
    GoFast: logical
        If True uses Simpson's rule for the k and mu integration with 400 k-bins and 100 mu-bins, so fast but
        but approximate. Otherwise, use vector-valued quadrature integration. This latter option can be very slow for
        many tracers. Default = False.

    Returns
    -------
    ManyFish: np.ndarray
        The complete Fisher information on the parameters [b_0*sigma8 ... b_npop*sigma8], fsigma8, alpha_perp, alpha_par
        at the redshift corresponding to index iz. Has size (npop + 3)
    """

    npop = np.shape(data.nbar)[0]
    npk = int(npop * (npop + 1) / 2)

    # Uses Simpson's rule or adaptive quadrature to integrate over all k and mu.
    if GoFast:

        # mu and k values for Simpson's rule
        muvec = np.linspace(0.0, 1.0, 100)
        kvec = np.linspace(kmin, kmax, 400)

        # 2D integration
        ManyFish = simps(
            simps(CastNet(muvec, kvec, iz, npop, npk, data, cosmo, recon,
                          derPalpha, BAO_only),
                  x=muvec,
                  axis=-1),
            x=kvec,
            axis=-1,
        )

    else:
        # Integral over mu
        OneFish = lambda *args: quad(CastNet,
                                     0.0,
                                     1.0,
                                     args=args,
                                     limit=1000,
                                     epsabs=1.0e-5,
                                     epsrel=1.0e-5)[0]

        # Integral over k
        ManyFish = quad(
            OneFish,
            kmin,
            kmax,
            args=(iz, npop, npk, data, cosmo, recon, derPalpha, BAO_only),
            limit=1000,
            epsabs=1.0e-5,
            epsrel=1.0e-5,
        )[0]

    # Multiply by the necessary prefactors
    ManyFish *= cosmo.volume[iz] / (2.0 * np.pi**2)

    return ManyFish
예제 #18
0
for i in range(3):
    funr = lambda theta,r,z: (P_theta[i](theta)*np.cos(theta)*np.sin(theta)*special.jv(1,k*r*np.sin(theta))*np.exp(1j*k*z*np.cos(theta)))
    funphi = lambda theta,r,z: (P_theta[i](theta)*np.sin(theta)*special.jv(1,k*r*np.sin(theta))*np.exp(1j*k*z*np.cos(theta)))
    funz = lambda theta,r,z: (P_theta[i](theta)*np.cos(theta)*np.sin(theta**2)*special.jv(0,k*r*np.sin(theta))*np.exp(1j*k*z*np.cos(theta)))

    z=0

    I_phi = np.zeros((len(xArray),len(yArray)), dtype = complex)
    I_r = np.zeros((len(xArray),len(yArray)), dtype = complex)
    I_z = np.zeros((len(xArray),len(yArray)), dtype = complex)

    for l in range(len(xArray)):

        for m in range(len(yArray)):
            r = np.sqrt(xArray[l]**2+yArray[m]**2)
            I_r[l,m] = quadpy.quad(lambda t: funr(t,r,z), 0, theta_max)[0]
            I_phi[l,m] = quadpy.quad(lambda t: funphi(t,r,z), 0, theta_max)[0]
            I_z[l,m] = quadpy.quad(lambda t: funz(t,r,z), 0, theta_max)[0]
    
    BeamResults[6*i+0] = np.abs(coeff*np.cos(varphi0)*np.real_if_close(I_r))**2 #E_rxy^2;
    BeamResults[6*i+1] = np.abs(coeff*np.sin(varphi0)*np.real_if_close(I_phi))**2 #E_phixy^2
    BeamResults[6*i+2] = np.abs(1j*coeff*np.cos(varphi0)*np.real_if_close(I_z))**2#E_zxy^2

    for l in range(len(zArray)):
        z = zArray[l]

        for m in range(len(rArray)):
            r = rArray[m]
            I_r[l,m] = quadpy.quad(lambda t: funr(t,r,z), 0, theta_max)[0]
            I_phi[l,m] = quadpy.quad(lambda t: funphi(t,r,z), 0, theta_max)[0]
            I_z[l,m] = quadpy.quad(lambda t: funz(t,r,z), 0, theta_max)[0]
예제 #19
0
    return probs

    # return observable_fn(conf, lj_params)*np.exp(-U/kT)


temperature = 300.0
kT = BOLTZ * temperature
int_lower = 0.01
int_upper = 0.99

Z_integrand = functools.partial(pdf,
                                observable_fn=lambda conf, params: 1.0,
                                kT=kT)

# compute the partition function with observable returning identity
Z, Z_err = quad(Z_integrand, int_lower, int_upper)

print("Z", Z)

# return the coordinate of the particle
avg_x_integrand = functools.partial(
    pdf, observable_fn=lambda conf, params: conf[1][0], kT=BOLTZ * temperature)

avg_x = quad(avg_x_integrand, int_lower, int_upper)[0] / Z  # 0.50000

print("<O(x)>", avg_x)

# deriv w.r.t. the 0.1 value in sigma
avg_du_dp_integrand = functools.partial(
    pdf,
    observable_fn=lambda conf, params: dU_dp(conf, params)[0],
예제 #20
0
import math
import scipy.integrate as sci
import scipy as sc
import cmath
import numpy as np
import quadpy


#val = sci.quad(lambda t: cmath.e ** (-2 * cmath.pi * t * complex(0, 1)), 0, 1)[0].real
def f(t):
    return cmath.e**(4 * cmath.pi * t * complex(0, 1))


result = quadpy.quad(f, 0, 1)
print(result[0].imag)

other = result[0] * cmath.e**(-2 * cmath.pi * 2)
예제 #21
0
def test_sin_x_other_way():
    val, err = quadpy.quad(lambda x: numpy.sin(x) - x, 1.0, 0.0)
    # import scipy.integrate
    # val, err = scipy.integrate.quad(lambda x: numpy.sin(x) - x, 1.0, 0.0)
    ref = -0.5 + numpy.cos(1)
    assert abs(val - ref) < 1.0e-8 * abs(ref)
예제 #22
0
                          action_bounds,
                          reward,
                          timesteps=5,
                          lamb=100)

#%%
start_state = X[:, 0]
# possible_actions = [2.77, 1, 5, 12, 8.95]
possible_actions = np.arange(0, bound + 0.5, 0.5)
for possible_action in possible_actions:
    print(f"{possible_action}:", pi(possible_action, start_state))
    print(f"{-possible_action}:", pi(-possible_action, start_state))
# I think -8.95 is the 'right' one

# %%
int_pi = qp.quad(pi, action_bounds[0], action_bounds[1],
                 args=(start_state, ))[0]
assert (int_pi == 1.0)

#%% Dictionary functions
psi = observables.monomials(6)

#%% Variable definitions
mu = -0.1
lamb = 1
A = np.array([[mu, 0], [0, lamb]])
A2 = np.array([[mu, 0, 0], [0, lamb, -lamb], [0, 0, 2 * mu]])
B = np.array([[0], [1]])
D_y = np.append(B, [[0]], axis=0)
Q = np.identity(2)
Q2 = np.identity(3)
R = 1