コード例 #1
0
ファイル: test_cbook.py プロジェクト: data-exp-lab/matplotlib
 def test_results_bootstrapped(self):
     results = cbook.boxplot_stats(self.data, bootstrap=10000)
     res = results[0]
     for key in list(self.known_bootstrapped_ci.keys()):
         assert_approx_equal(
             res[key],
             self.known_bootstrapped_ci[key]
         )
コード例 #2
0
def test_tau_instant():
    """Check the optical depth we get using the WMAP z_reion. 
    """
    dz = 0.1
    z = numpy.arange(80., 0. - 1.5 * dz, -1. * dz)

    # Can't match WMAP7 optical depths exactly. Need to look into new
    # treatment in CAMB as mentioned in the WMAP7 paper (see
    # parameters.py).
    cosmos = [cparam.WMAP7_BAO_H0_mean(flat=True),
              cparam.WMAP7_ML(flat=True),
              cparam.WMAP5_BAO_SN_mean(flat=True),
              cparam.WMAP5_ML(flat=True),
              cparam.WMAP5_mean(flat=True)]

    # The WMAP5 numbers apparently assume He is neutral, while WMAP7
    # includes simultaneous singly ionized He plus Helium (double)
    # reionization at z=3.5.
    x_ionHe_list = [1.0, 1.0, 0, 0, 0]
    z_rHe_list = [3.5, 3.5, None, None, None] #[3.5, None, None, None]
    for cosmo in cosmos:
        # Fully ionized H
        x_ionH = 1.0

        # He ionization with H?
        x_ionHe = x_ionHe_list.pop(0)

        # Redshift for Helium double reionization?
        z_rHe = z_rHe_list.pop(0)

        zr = cosmo['z_reion']
        tau_zr = cosmo['tau']
        tau_calc = cr.optical_depth_instant(zr, 
                                            x_ionH=x_ionH, 
                                            x_ionHe=x_ionHe,
                                            z_rHe=z_rHe,
                                            verbose = 1,
                                            **cosmo)

        print "z_r = %f, testing tau:" % zr,
        print tu.fractional_diff_string(tau_zr, tau_calc, 3)

        ntest.assert_approx_equal(tau_calc, tau_zr, significant=2, 
                                  err_msg="Optical depth doesn't match WMAP")
コード例 #3
0
def test_t_0():
    """Check the age of the universe we get using WMAP cosmologies.

    We only find agreement to 3 sig figs, not the 4 specified in the
    WMAP paper.

    The results of test_age.py show that we're doing the integral
    correctly, so I think the problem is that we're not taking into
    account some of the higher-order effects included in the WMAP
    numbers.

    """

    dz = 0.1
    z = numpy.arange(80., 0. - 1.5 * dz, -1. * dz)

    flat = True
    cosmos = [cparam.WMAP7_BAO_H0_mean(flat=True),
              cparam.WMAP7_ML(flat=True),
              cparam.WMAP5_BAO_SN_mean(flat=True),
              cparam.WMAP5_ML(flat=True),
              cparam.WMAP5_mean(flat=True)]

    for cosmo in cosmos:
        age = cd.age(0.0, **cosmo)
        age_flat = cd.age_flat(0.0, **cosmo)
        gyr = 1e9 * cc.yr_s
        age /= gyr
        age_flat /= gyr

        print "integrated age: ",
        print tu.fractional_diff_string(age, cosmo['t_0'], 4)
        ntest.assert_approx_equal(age, cosmo['t_0'], significant=3, 
                                  err_msg="Integrated age doesn't match WMAP")

        print "analytical age: ",
        print tu.fractional_diff_string(age_flat, cosmo['t_0'], 4)
        ntest.assert_approx_equal(age_flat, cosmo['t_0'], significant=3, 
                                  err_msg="Analytical age doesn't match WMAP")
コード例 #4
0
def test_GBL_tau_star():
    """Test tau_* against GB&L astro-ph/9812125v3.

    tau_* is a quantity used in optical_depth_instant.
    """
    z = 1.0

    # Fully ionized H and He
    x_ionH = 1.0
    x_ionHe = 2.0

    cosmo = {}
    cosmo['omega_M_0'] = numpy.array([[0.3],[0.6],[1.0]])
    cosmo['omega_lambda_0'] = 1. - cosmo['omega_M_0']
    cosmo['h'] = 0.65
    cosmo['omega_b_0'] = 0.02 / cosmo['h']**2.
    cosmo['Y_He'] = 0.24
    cd.set_omega_k_0(cosmo)

    tau_inst, tau_star = cr.optical_depth_instant(z, 
                                                  x_ionH=x_ionH, 
                                                  x_ionHe=x_ionHe, 
                                                  return_tau_star=True,
                                                  **cosmo)
    print "tau_star = %.7f" % tau_star
    print ("tau_star/(h Omega_b) = %.7f =? 0.061" % 
           (tau_star / (cosmo['h'] * cosmo['omega_b_0'])))

    ntest.assert_approx_equal(tau_star / (cosmo['h'] * cosmo['omega_b_0']),
                              0.061,
                              2)

    print "(1 - Y_He/2) = %.3f =? 0.88" % (1. - (cosmo['Y_He']/2.))
    ntest.assert_approx_equal((1. - (cosmo['Y_He']/2.)),
                              0.88,
                              7)

    H_0 = cc.H100_s * cosmo['h']

    # s^-1 * Mpc s^-1 * Mpc^2 / Mpc^3 msun^-1 s^-2 / Msun -> 
    tau_star_explicit =  ((1. - (cosmo['Y_He']/2.)) * 
                          ((3. * H_0 * cosmo['omega_b_0'] * cc.c_light_Mpc_s *
                            cc.sigma_T_Mpc) / 
                           (8. * math.pi * cc.G_const_Mpc_Msun_s * 
                            (cc.m_p_g/cc.M_sun_g))))

    print "tau_star_explicit = %.7f =? tau_star" % tau_star_explicit
    ntest.assert_approx_equal(tau_star, tau_star_explicit, 3)
コード例 #5
0
def test_tau_BKP():
    """Reionization consistency check with BK&P 2009MNRAS.397..971B

    Bagla J.~S., Kulkarni G., Padmanabhan T., 2009 (2009MNRAS.397..971B).
    
    Take their cannonical set of cosmological parameters and ionization
    coefficients and make sure I get the same optical depth value.

    The first figure demonstrates the calculation of the ionization
    fraction and the optical depth (not shown in the paper).

    The second figure shows dependence of the f_* f_esc,gamma values on
    tau (actually calculated the other way around, f_* f_esc,gamma ->
    tau). The plotted point (x) marks the value from the paper. The
    agreement between the calculated optical depth and the WMAP tau value
    is printed in the text output.
    
    """
    N_gamma = 6804.

    # f_* f_esc N_gamma
    f_ion = numpy.transpose(numpy.atleast_2d(numpy.arange(10., 200., 10.)))
    
    alpha_B = 1e-13 # cm^3 s^-1
    m_min = 1e8 # M_sun

    x_ionHe = 2.0

    dz = 0.1
    z = numpy.arange(20., 6. - 1.5 * dz, -1. * dz)
    #z = numpy.arange(6., 20. + 1.5 * dz, dz)

    cosmos = [cparam.WMAP5_ML(flat=True),
              cparam.WMAP5_mean(flat=True)]    

    pylab.figure(figsize=(8,8))
    colors=['r', 'k']
    names = ["WMAP5 ML", "WMAP5 mean"]
    i = -1
    for cosmo in cosmos:
        i += 1
        print
        print names[i]
        # calculate ionized fraction, including recombinations
        x_rec, w_rec, t = cr.integrate_ion_recomb_collapse(z, f_ion,
                                                           m_min,
                                                           passed_min_mass=True,
                                                           alpha_B=alpha_B,
                                                           **cosmo)
        # calculate the optical depth in this scenario
        tau_z0 = cr.optical_depth_instant(z[-1],
                                          x_ionH=1.0,
                                          x_ionHe=2.0,
                                          **cosmo)

        tau_later = cr.integrate_optical_depth(x_rec, x_ionHe * x_rec, 
                                               z, **cosmo)
        tau_0 = tau_later[:, -1] + tau_z0

        tau = tau_later

        print "tau(WMAP) = %.3f" % cosmo['tau']
        for j in range(len(f_ion.flat)):
            if round(f_ion[j],1) != 50.0:
                continue
            print "with f_* f_esc_gamma N_gamma = %.1f:" % f_ion[j]
            pylab.plot(z, x_rec[j], ls='-', color=colors[i])
            pylab.plot(z, w_rec[j], ls=':', color=colors[i])
            #pylab.plot(z, 10. * tau[j], ls='--', color=colors[i])
            pylab.plot(z, 10. * (tau_0[j] - tau[j]), ls='--', color=colors[i])
            pylab.axhline(y=10. * tau_0[j], ls='--', color=colors[i])
            print "tau(z=0)  = %.4f" % tau_0[j]
            print " fractional diff. = %.3g" % ((tau_0[j] - cosmo['tau']) / 
                                                cosmo['tau'])
            if i==1:
                # Make sure we recover the WMAP value.
                ntest.assert_approx_equal(tau_0[j], cosmo['tau'], 2)

    pylab.ylim(0,1.01)
    pylab.xlabel("redshift z")
    pylab.ylabel(r"ionized fraction or optical depth $\tau \times 10$")

    pylab.figure(figsize=(8,8))
    pylab.plot(tau_0, f_ion / N_gamma, '-', color='k')
    pylab.plot([cosmo['tau']], [50.0 / N_gamma], 'x', color='b')
    pylab.xlim(0.06, 0.12)
    pylab.ylim(0., 0.022)
    pylab.xlabel(r'$\tau$')
    pylab.ylabel(r'$f_* f_{esc,\gamma}$')
コード例 #6
0
def test_symbolic_vector():
    # XXX: doesn't work without global
    global q0, q1
    p0 = Var("p0")
    q0 = Var(p0 + 3, "q0")
    q1 = Var(Diff(1 + Sin(Pow(p0, 3) + q0), p0), "q1")

    qv = Var([q0, q1], "q")
    assert str(qv()) == "[q0,q1]"
    assert str(qv.eval()) == "[(p0+3),(3*Pow(p0,2)*Cos(Pow(p0,3)+(p0+3)))]"

    v = Var("v")
    w = Var("w")
    f = Var([-3 * Pow((2 * v + 1), 3) + 2 * (w + v), -w / 2], "f")

    df = Diff(f, [v, w])
    assert str(df) == "[[-3*6*Pow((2*v+1),2)+2,2],[0,-0.5]]"
    dfe = df.eval(v=3, w=10).tonumeric()
    assert_allclose(dfe, [[-880.0, 2.0], [0.0, -0.5]])
    assert isinstance(dfe, ndarray)
    assert isinstance(df.fromvector(), list)

    y0 = Var("y0")
    y1 = Var("y1")
    y2 = Var("y2")
    t = Var("t")

    ydot0 = Fun(-0.04 * y0 + 1e4 * y1 * y2, [y0, y1, y2], "ydot0")
    ydot2 = Fun(3e7 * y1 * y1, [y0, y1, y2], "ydot2")
    ydot1 = Fun(-ydot0(y0, y1, y2) - ydot2(y0, y1, y2), [y0, y1, y2], "ydot1")

    F = Fun([ydot0(y0, y1, y2), ydot1(y0, y1, y2), ydot2(y0, y1, y2)], [y0, y1, y2], "F")
    assert F.dim == 3
    DF = Diff(F, [y0, y1, y2])
    DF0, DF1, DF2 = DF.fromvector()
    assert_approx_equal(DF0.fromvector()[0].tonumeric(), -0.04)
    # str(Diff(F,[y0,y1,y2])) should be (to within numerical rounding errors):
    # '[[-0.04,10000*y2,10000*y1],[0.040000000000000001,(-10000*y2)-30000000*2*y1,-10000*y1],[0,30000000*2*y1,0]]')

    jac = Fun(Diff(F, [y0, y1, y2]), [t, y0, y1, y2], "Jacobian")
    assert jac(t, 0.1, y0 + 1, 0.5).eval(y0=0) == jac(t, 0.1, 1 + y0, 0.5).eval(y0=0)
    assert jac(t, 0.1, y0, 0.5) == jac(t, 0.1, 0 + y0, 0.5)

    x = Var("x")
    y = Var("y")

    f1 = Fun([-3 * x ** 3 + 2 * (x + y), -y / 2], [x, y], "f1")
    f2 = ["-3*x**3+2*(x+y)", "-y/2"]
    f3 = [-3 * x ** 3.0 + 2 * (x + y), -y / 2.0]
    assert str(f1) == "f1"
    assert str(f2) == "['-3*x**3+2*(x+y)', '-y/2']"
    assert str(f3) == "[QuantSpec __result__ (ExpFuncSpec), QuantSpec __result__ (ExpFuncSpec)]"

    f4 = [-3 * Pow((2 * x + 1), 3) + 2 * (x + y), -y / 2]
    xx = QuantSpec("dummy", "x")
    f5 = Var([-3 * Pow((2 * x + 1), 3) + 2 * (x + y), -y / 2], "f5")

    assert Diff(f1, x) == Diff(f1, "x")
    assert str(Diff(f1, x)) == "[-3*3*Pow(x,2)+2,0]"
    assert str(Diff(f3, x)) == "[-3*3*Pow(x,2)+2,0]"
    assert str(Diff(f3, xx)) == "[-3*3*Pow(x,2)+2,0]"
    assert str(Diff(f4, x)) == "[-3*6*Pow((2*x+1),2)+2,0]"
    assert str(Diff(f4, xx)) == "[-3*6*Pow((2*x+1),2)+2,0]"

    # Examples of Jacobian Diff(f, [x,y])...
    assert Diff(f1, [x, y]) == Diff(f1, ["x", "y"]) == Diff(f1(x, y), [x, y])
    assert str(Diff(f2, ["x", "y"])) == "[[-3*3*Pow(x,2)+2,2],[0,-0.5]]"
    assert str(Diff(f3, ["x", "y"])) == "[[-3*3*Pow(x,2)+2,2],[0,-0.5]]"
    assert str(Diff(f1, [xx, y])) == "[[-3*3*Pow(x,2)+2,2],[0,-0.5]]"
    assert str(Diff(f1, [xx, "y"])) == "[[-3*3*Pow(x,2)+2,2],[0,-0.5]]"
    assert str(Diff(f2, [x, y])) == "[[-3*3*Pow(x,2)+2,2],[0,-0.5]]"
    assert str(Diff(f3, [x, y])) == "[[-3*3*Pow(x,2)+2,2],[0,-0.5]]"
    assert str(Diff(f4, [x, y])) == "[[-3*6*Pow((2*x+1),2)+2,2],[0,-0.5]]"
    df5 = Diff(f5, [x, y])
    assert str(df5) == "[[-3*6*Pow((2*x+1),2)+2,2],[0,-0.5]]"
    assert_allclose(df5.eval(x=3, y=10).tonumeric(), [[-880.0, 2.0], [0.0, -0.5]])
    # FIXME: segmentation fault!
    # assert_allclose(df5.eval(x=3,y=10).fromvector(0), [-880.0,2.0])
    assert str(df5.eval(x=3, y=10).fromvector(0)) == "[-880.0,2]"
    assert str(df5.fromvector(0)) == "[-3*6*Pow((2*x+1),2)+2,2]"
    assert isinstance(df5.fromvector(), list)
    a = df5.fromvector(0).eval(x=3, y=10).tonumeric()
    b = df5.eval(x=3, y=10).tonumeric()[0]
    assert a[0] == b[0] and a[1] == b[1]
コード例 #7
0
y0 = Var('y0')
y1 = Var('y1')
y2 = Var('y2')
t = Var('t')

ydot0 = Fun(-0.04 * y0 + 1e4 * y1 * y2, [y0, y1, y2], 'ydot0')
ydot2 = Fun(3e7 * y1 * y1, [y0, y1, y2], 'ydot2')
ydot1 = Fun(-ydot0(y0, y1, y2) - ydot2(y0, y1, y2), [y0, y1, y2], 'ydot1')

F = Fun([ydot0(y0, y1, y2),
         ydot1(y0, y1, y2),
         ydot2(y0, y1, y2)], [y0, y1, y2], 'F')
assert F.dim == 3
DF = Diff(F, [y0, y1, y2])
DF0, DF1, DF2 = DF.fromvector()
assert_approx_equal(DF0.fromvector()[0].tonumeric(), -0.04)
# str(Diff(F,[y0,y1,y2])) should be (to within numerical rounding errors):
#'[[-0.04,10000*y2,10000*y1],[0.040000000000000001,(-10000*y2)-30000000*2*y1,-10000*y1],[0,30000000*2*y1,0]]')

jac = Fun(Diff(F, [y0, y1, y2]), [t, y0, y1, y2], 'Jacobian')
assert jac(t, 0.1, y0 + 1, 0.5).eval(y0=0) == jac(t, 0.1, 1 + y0,
                                                  0.5).eval(y0=0)
assert jac(t, 0.1, y0, 0.5) == jac(t, 0.1, 0 + y0, 0.5)

x = Var('x')
y = Var('y')

f1 = Fun([-3 * x**3 + 2 * (x + y), -y / 2], [x, y], 'f1')
f2 = ['-3*x**3+2*(x+y)', '-y/2']
f3 = [-3 * x**3. + 2 * (x + y), -y / 2.]
print("\n\nVector-valued function f(x,y) =", f1)
コード例 #8
0
def test_symbolic_vector():
    # XXX: doesn't work without global
    global q0, q1
    p0 = Var('p0')
    q0 = Var(p0 + 3, 'q0')
    q1 = Var(Diff(1 + Sin(Pow(p0, 3) + q0), p0), 'q1')

    qv = Var([q0, q1], 'q')
    assert str(qv()) == '[q0,q1]'
    assert str(qv.eval()) == '[(p0+3),(3*Pow(p0,2)*Cos(Pow(p0,3)+(p0+3)))]'

    v = Var('v')
    w = Var('w')
    f = Var([-3 * Pow((2 * v + 1), 3) + 2 * (w + v), -w / 2], 'f')

    df = Diff(f, [v, w])
    assert str(df) == '[[-3*6*Pow((2*v+1),2)+2,2],[0,-0.5]]'
    dfe = df.eval(v=3, w=10).tonumeric()
    assert_allclose(dfe, [[-880.0, 2.0], [0.0, -0.5]])
    assert isinstance(dfe, ndarray)
    assert isinstance(df.fromvector(), list)

    y0 = Var('y0')
    y1 = Var('y1')
    y2 = Var('y2')
    t = Var('t')

    ydot0 = Fun(-0.04 * y0 + 1e4 * y1 * y2, [y0, y1, y2], 'ydot0')
    ydot2 = Fun(3e7 * y1 * y1, [y0, y1, y2], 'ydot2')
    ydot1 = Fun(-ydot0(y0, y1, y2) - ydot2(y0, y1, y2), [y0, y1, y2], 'ydot1')

    F = Fun([ydot0(y0, y1, y2),
             ydot1(y0, y1, y2),
             ydot2(y0, y1, y2)], [y0, y1, y2], 'F')
    assert F.dim == 3
    DF = Diff(F, [y0, y1, y2])
    DF0, DF1, DF2 = DF.fromvector()
    assert_approx_equal(DF0.fromvector()[0].tonumeric(), -0.04)
    # str(Diff(F,[y0,y1,y2])) should be (to within numerical rounding errors):
    # '[[-0.04,10000*y2,10000*y1],[0.040000000000000001,(-10000*y2)-30000000*2*y1,-10000*y1],[0,30000000*2*y1,0]]')

    jac = Fun(Diff(F, [y0, y1, y2]), [t, y0, y1, y2], 'Jacobian')
    assert jac(t, 0.1, y0 + 1, 0.5).eval(y0=0) == jac(t, 0.1, 1 + y0,
                                                      0.5).eval(y0=0)
    assert jac(t, 0.1, y0, 0.5) == jac(t, 0.1, 0 + y0, 0.5)

    x = Var('x')
    y = Var('y')

    f1 = Fun([-3 * x**3 + 2 * (x + y), -y / 2], [x, y], 'f1')
    f2 = ['-3*x**3+2*(x+y)', '-y/2']
    f3 = [-3 * x**3. + 2 * (x + y), -y / 2.]
    assert str(f1) == 'f1'
    assert str(f2) == '[\'-3*x**3+2*(x+y)\', \'-y/2\']'
    assert str(
        f3
    ) == '[QuantSpec __result__ (ExpFuncSpec), QuantSpec __result__ (ExpFuncSpec)]'

    f4 = [-3 * Pow((2 * x + 1), 3) + 2 * (x + y), -y / 2]
    xx = QuantSpec('dummy', 'x')
    f5 = Var([-3 * Pow((2 * x + 1), 3) + 2 * (x + y), -y / 2], 'f5')

    assert Diff(f1, x) == Diff(f1, 'x')
    assert str(Diff(f1, x)) == '[-3*3*Pow(x,2)+2,0]'
    assert str(Diff(f3, x)) == '[-3*3*Pow(x,2)+2,0]'
    assert str(Diff(f3, xx)) == '[-3*3*Pow(x,2)+2,0]'
    assert str(Diff(f4, x)) == '[-3*6*Pow((2*x+1),2)+2,0]'
    assert str(Diff(f4, xx)) == '[-3*6*Pow((2*x+1),2)+2,0]'

    # Examples of Jacobian Diff(f, [x,y])...
    assert Diff(f1, [x, y]) == Diff(f1, ['x', 'y']) == Diff(f1(x, y), [x, y])
    assert str(Diff(f2, ['x', 'y'])) == '[[-3*3*Pow(x,2)+2,2],[0,-0.5]]'
    assert str(Diff(f3, ['x', 'y'])) == '[[-3*3*Pow(x,2)+2,2],[0,-0.5]]'
    assert str(Diff(f1, [xx, y])) == '[[-3*3*Pow(x,2)+2,2],[0,-0.5]]'
    assert str(Diff(f1, [xx, 'y'])) == '[[-3*3*Pow(x,2)+2,2],[0,-0.5]]'
    assert str(Diff(f2, [x, y])) == '[[-3*3*Pow(x,2)+2,2],[0,-0.5]]'
    assert str(Diff(f3, [x, y])) == '[[-3*3*Pow(x,2)+2,2],[0,-0.5]]'
    assert str(Diff(f4, [x, y])) == '[[-3*6*Pow((2*x+1),2)+2,2],[0,-0.5]]'
    df5 = Diff(f5, [x, y])
    assert str(df5) == '[[-3*6*Pow((2*x+1),2)+2,2],[0,-0.5]]'
    assert_allclose(
        df5.eval(x=3, y=10).tonumeric(), [[-880.0, 2.0], [0.0, -0.5]])
    # FIXME: segmentation fault!
    # assert_allclose(df5.eval(x=3,y=10).fromvector(0), [-880.0,2.0])
    assert str(df5.eval(x=3, y=10).fromvector(0)) == '[-880.0,2]'
    assert str(df5.fromvector(0)) == '[-3*6*Pow((2*x+1),2)+2,2]'
    assert isinstance(df5.fromvector(), list)
    a = df5.fromvector(0).eval(x=3, y=10).tonumeric()
    b = df5.eval(x=3, y=10).tonumeric()[0]
    assert a[0] == b[0] and a[1] == b[1]
コード例 #9
0
def test_tau_BKP():
    """Reionization consistency check with BK&P 2009MNRAS.397..971B

    Bagla J.~S., Kulkarni G., Padmanabhan T., 2009 (2009MNRAS.397..971B).
    
    Take their cannonical set of cosmological parameters and ionization
    coefficients and make sure I get the same optical depth value.

    The first figure demonstrates the calculation of the ionization
    fraction and the optical depth (not shown in the paper).

    The second figure shows dependence of the f_* f_esc,gamma values on
    tau (actually calculated the other way around, f_* f_esc,gamma ->
    tau). The plotted point (x) marks the value from the paper. The
    agreement between the calculated optical depth and the WMAP tau value
    is printed in the text output.
    
    """
    N_gamma = 6804.

    # f_* f_esc N_gamma
    f_ion = numpy.transpose(numpy.atleast_2d(numpy.arange(10., 200., 10.)))

    alpha_B = 1e-13  # cm^3 s^-1
    m_min = 1e8  # M_sun

    x_ionHe = 2.0

    dz = 0.1
    z = numpy.arange(20., 6. - 1.5 * dz, -1. * dz)
    #z = numpy.arange(6., 20. + 1.5 * dz, dz)

    cosmos = [cparam.WMAP5_ML(flat=True), cparam.WMAP5_mean(flat=True)]

    pylab.figure(figsize=(8, 8))
    colors = ['r', 'k']
    names = ["WMAP5 ML", "WMAP5 mean"]
    i = -1
    for cosmo in cosmos:
        i += 1
        print
        print names[i]
        # calculate ionized fraction, including recombinations
        x_rec, w_rec, t = cr.integrate_ion_recomb_collapse(
            z, f_ion, m_min, passed_min_mass=True, alpha_B=alpha_B, **cosmo)
        # calculate the optical depth in this scenario
        tau_z0 = cr.optical_depth_instant(z[-1],
                                          x_ionH=1.0,
                                          x_ionHe=2.0,
                                          **cosmo)

        tau_later = cr.integrate_optical_depth(x_rec, x_ionHe * x_rec, z,
                                               **cosmo)
        tau_0 = tau_later[:, -1] + tau_z0

        tau = tau_later

        print "tau(WMAP) = %.3f" % cosmo['tau']
        for j in range(len(f_ion.flat)):
            if round(f_ion[j], 1) != 50.0:
                continue
            print "with f_* f_esc_gamma N_gamma = %.1f:" % f_ion[j]
            pylab.plot(z, x_rec[j], ls='-', color=colors[i])
            pylab.plot(z, w_rec[j], ls=':', color=colors[i])
            #pylab.plot(z, 10. * tau[j], ls='--', color=colors[i])
            pylab.plot(z, 10. * (tau_0[j] - tau[j]), ls='--', color=colors[i])
            pylab.axhline(y=10. * tau_0[j], ls='--', color=colors[i])
            print "tau(z=0)  = %.4f" % tau_0[j]
            print " fractional diff. = %.3g" % (
                (tau_0[j] - cosmo['tau']) / cosmo['tau'])
            if i == 1:
                # Make sure we recover the WMAP value.
                ntest.assert_approx_equal(tau_0[j], cosmo['tau'], 2)

    pylab.ylim(0, 1.01)
    pylab.xlabel("redshift z")
    pylab.ylabel(r"ionized fraction or optical depth $\tau \times 10$")

    pylab.figure(figsize=(8, 8))
    pylab.plot(tau_0, f_ion / N_gamma, '-', color='k')
    pylab.plot([cosmo['tau']], [50.0 / N_gamma], 'x', color='b')
    pylab.xlim(0.06, 0.12)
    pylab.ylim(0., 0.022)
    pylab.xlabel(r'$\tau$')
    pylab.ylabel(r'$f_* f_{esc,\gamma}$')
コード例 #10
0
def test_power():
    """Check that the power module is working."""
    import cosmolopy.EH.power as power
    power.TFmdm_set_cosm(0.3, 0.04, 0.0, 0, 0.7, 0.72, 0.0)
    ntest.assert_approx_equal(power.TFmdm_onek_hmpc(100.0), 1.48236347286e-06)
コード例 #11
0
ファイル: delay.py プロジェクト: roban/EnrichPy
def test_Delay(plots=True, skip_asserts=False, delayfunc=None):
    import numpy.testing.utils as ntest
    
    maxTime = delayfunc.maxTime
    minTime = delayfunc.minTime

    # Set up mass and time coordinates.
    npoints = 1000
    #dmass = 0.01
    #mass = numpy.arange(delayfunc.lowMass, delayfunc.highMass + dmass, dmass)
    mass, dmass = numpy.linspace(delayfunc.lowMass, delayfunc.highMass, npoints,
                          retstep=True)
    
    #dlogt = 0.01
    #time = 10**numpy.arange(numpy.log10(minTime), numpy.log10(maxTime) + dlogt,
    #                        dlogt)
    #time = numpy.logspace(numpy.log10(minTime), numpy.log10(maxTime), npoints)
    time = numpy.linspace(0, maxTime, npoints)

    mass_from_time = delayfunc.m_star(time)
    time_from_mass = delayfunc.t_life(mass)
    
    # Calculate delay-function-related quantities.
    metal_mass_dist = delayfunc.metal_mass_dist(mass)
    metal_mass_dist_postinterp = delayfunc.metal_mass_dist_postinterp(mass)
    metal_mass_CCDF = delayfunc.metal_mass_CCDF(mass)
    metal_time_CDF = delayfunc.metal_time_CDF(time)
    metal_time_CDF_time_from_mass = delayfunc.metal_time_CDF(time_from_mass)
    metal_time_dist_binned, dtime_bin = delayfunc.metal_time_dist_binned(time)
    metal_time_dist_unbinned, dtime_ubin = \
                              delayfunc.metal_time_dist_unbinned(time)

    imf = delayfunc.imf(mass)
    yield_mass = delayfunc.yield_mass(mass)

    ### Test some relationships between the quantities. ###
    import scipy.integrate

    # Do a simple integral over the PDF:
    test_mass_CCDF = scipy.integrate.cumtrapz((dmass *
                                               metal_mass_dist)[::-1])[::-1]
    diff_mass_CCDF = test_mass_CCDF - metal_mass_CCDF[:-1]

    sum_metal_time_dist = \
                        numpy.cumsum(numpy.nan_to_num(metal_time_dist_binned))

    test_time_CDF = numpy.cumsum(metal_time_dist_unbinned * dtime_ubin)

    test_metal_mass_dist = imf * yield_mass / delayfunc._fCnorm
    
    if not skip_asserts:

        ### The CDF should be the integral of the metal dist. ###

        # The CDF should be the integral of the metal dist:
        ntest.assert_almost_equal(metal_mass_CCDF[:-1], test_mass_CCDF, 2)

        # The metal time CDF and metal mass CCDF should be
        # equal. (This could be 10 digits rather than four, except for
        # a small hicup in the time from mass conversion.)#
        ntest.assert_almost_equal(metal_time_CDF_time_from_mass,
                                  metal_mass_CCDF, 4)

        ### The CCDF and CDF should be close one at lowMass. ###
        marray = numpy.linspace(delayfunc.lowMass, delayfunc.highMass, 100)
        ccdf = delayfunc.metal_mass_CCDF(marray)
        cdf = delayfunc.metal_time_CDF(delayfunc.t_life(marray))
        ntest.assert_approx_equal(ccdf[0], 1., 4)
        ntest.assert_approx_equal(cdf[0], 1., 4)

        # The sum of the binned dist should be one over the norm
        # range.
        ntest.assert_approx_equal(sum_metal_time_dist[-1], 1., 4)

        ### The sum of the binned dist should be equal to the CDF ###
        ntest.assert_almost_equal(\
            numpy.cumsum(numpy.nan_to_num(metal_time_dist_binned)),
                         numpy.nan_to_num(metal_time_CDF))

        ### The integral of the time dist should be equal to the CDF ###
        ntest.assert_almost_equal(numpy.nan_to_num(metal_time_CDF),
                                  test_time_CDF, 10)

        ### The product of IMF and yield should be proportional to the metal
        ### mass distribution. ###
        ntest.assert_almost_equal(metal_mass_dist, test_metal_mass_dist, 10)

        ### The metal mass dist should be similar if we interpolate before
        ### or after the IMF multiplication. ###
        ntest.assert_almost_equal(metal_mass_dist,
                                  metal_mass_dist_postinterp, 2)

    ### Make some plots ###

    if plots:
        pylab.figure().set_label('metal_mass_CCDF')

        pylab.subplot(221)
        pylab.plot(mass[:-1], test_mass_CCDF, label="test")
        pylab.plot(mass, metal_mass_CCDF, label="CCDF")
        pylab.legend(loc='best')
        pylab.axvline(x=delayfunc.lowMass)
        pylab.axvline(x=delayfunc.highMass)
        pylab.twinx()
        pylab.plot(mass, metal_mass_dist, ':', label="PDF")

        pylab.subplot(222)
        pylab.plot(mass[:-1], diff_mass_CCDF, label="test diff")
        pylab.legend(loc='best')
        pylab.twinx()
        pylab.plot(mass, metal_mass_dist, ":", label="PDF")

        pylab.subplot(223)
        pylab.plot(time_from_mass, metal_mass_CCDF, label="CCDF")
        pylab.xscale('log')
        pylab.legend(loc='best')

        pylab.subplot(224)
        pylab.plot(mass, metal_mass_dist, ':', label="PDF")
        pylab.axvline(x=delayfunc.lowMass)
        pylab.axvline(x=delayfunc.highMass)
        pylab.legend(loc='best')

        pylab.figure().set_label('metal_mass_PDF')
        pylab.subplot(211)
        pylab.plot(mass, metal_mass_dist, ':', label="PDF")
        pylab.plot(mass, metal_mass_dist_postinterp, '-.', label="postinterp")
        pylab.plot(mass, test_metal_mass_dist, '--', label="~ IMF * yield")
        pylab.axvline(x=delayfunc.lowMass)
        pylab.axvline(x=delayfunc.highMass)
        pylab.legend(loc='best')
        pylab.subplot(212)
        pylab.plot(mass, metal_mass_dist -
                   test_metal_mass_dist, ':', label="PDF - c*(IMF * yield)")
        pylab.plot(mass, metal_mass_dist -
                   metal_mass_dist_postinterp, '-', label="PDF - postinterp")
        pylab.axvline(x=delayfunc.lowMass)
        pylab.axvline(x=delayfunc.highMass)
        pylab.legend(loc='best')

        pylab.figure().set_label('mass_time')
        pylab.subplot(211)
        pylab.plot(time, mass_from_time, label="mass from time")
        pylab.plot(time_from_mass, mass, label="time from mass")
        pylab.xscale('log')
        pylab.subplot(212)
        pylab.plot(mass_from_time, time, label="mass from time")
        pylab.plot(mass, time_from_mass, label="time from mass")
        pylab.yscale('log')
        pylab.legend(loc='best')
                
        pylab.figure().set_label('metal_time_CDF')

        pylab.subplot(221)
        pylab.plot(time, metal_time_CDF, label="CDF")
        pylab.plot(time, sum_metal_time_dist, label="sum of binned")
        pylab.plot(time, test_time_CDF, label="int of unbinned")
        pylab.legend(loc='best')
        pylab.xscale('log')
        pylab.axvline(x=minTime)
        pylab.axvline(x=maxTime)

        pylab.subplot(222)
        pylab.plot(mass_from_time, metal_time_CDF, label="CDF")
        pylab.plot(mass_from_time, sum_metal_time_dist, label="sum of binned")
        pylab.plot(mass_from_time, test_time_CDF, label="int of unbinned")
        pylab.axvline(x=delayfunc.lowMass)
        pylab.axvline(x=delayfunc.highMass)
        pylab.legend(loc='best')

        pylab.subplot(223)
        pylab.plot(time, sum_metal_time_dist - metal_time_CDF, label="sum-CDF")
        pylab.plot(time, test_time_CDF - metal_time_CDF, label="int-CDF")
        pylab.legend(loc='best')
        pylab.xscale('log')
        pylab.axvline(x=minTime)
        pylab.axvline(x=maxTime)

        pylab.subplot(224)
        pylab.plot(mass_from_time, sum_metal_time_dist - metal_time_CDF,
                   label="sum-CDF")
        pylab.plot(mass_from_time,
                   test_time_CDF - metal_time_CDF, label="int-CDF")
        pylab.legend(loc='best')
        pylab.axvline(x=delayfunc.lowMass)
        pylab.axvline(x=delayfunc.highMass)


        pylab.figure().set_label('metal_time_PDF_bin')
        pylab.plot(time, metal_time_dist_binned, label="binned")
        pylab.xscale('log')
        pylab.axvline(x=minTime)
        pylab.axvline(x=maxTime)
        pylab.legend(loc='best')

        pylab.figure().set_label('metal_time_PDF_unbin')
        pylab.plot(time, metal_time_dist_unbinned, label="unbinned")
        pylab.xscale('log')
        pylab.legend(loc='best')

        pylab.figure().set_label('CDF_CCDF')
        pylab.subplot(211)
        pylab.plot(mass, metal_mass_CCDF, label='mass CCDF')
        pylab.plot(mass, metal_time_CDF_time_from_mass, label='time CDF')
        pylab.legend(loc='best')
        pylab.subplot(212)
        pylab.plot(mass, metal_time_CDF_time_from_mass - metal_mass_CCDF, ':',
                   label='CDF - CCDF')
        pylab.legend(loc='best')
コード例 #12
0
def test_tf_fit():
    """Check that the tf_fit module is working."""
    import cosmolopy.EH.tf_fit as tf_fit
    tf_fit.TFset_parameters(0.136, 0.2, 2.728)
    ntest.assert_approx_equal(tf_fit.TFfit_onek(10.0), 3.69328954548e-05)
コード例 #13
0
def test_tf_fit():
    """Check that the tf_fit module is working."""
    import cosmolopy.EH.tf_fit as tf_fit
    tf_fit.TFset_parameters(0.136, 0.2, 2.728)
    ntest.assert_approx_equal( tf_fit.TFfit_onek(10.0),
                              3.69328954548e-05)
コード例 #14
0
sc1 = str(q.eval()) == '4'
print "q.eval() == 4? ", sc1
assert sc1
print "a=x/q"
a=x/q
sc2 = str(a) == 'xv/qv'
print "a == xv/qv? ", sc2
assert sc2
sc3 = str(a.eval())=='0.75'
print "a.eval() == 0.75? ", sc3
assert sc3
sc4 = str(a.eval(xv=5))=='5/qv'
print "a.eval(xv=5) == 5/q? ", sc4
assert sc4
sc5 = (str(a.eval(xv=5,qv=q())),'0.83333333333333337')
assert_approx_equal(*sc5)
print "assert_approx_equal(%s,%s)" % sc5
sc6 = (str(a.eval({'xv': 10, 'qv': q()})),'0.90909090909090906')
print "assert_approx_equal(%s,%s)" % sc6
assert_approx_equal(*sc6)

print "qs=QuantSpec('qsv','xsv+1')"
print "xs=QuantSpec('xsv','3')"
qs=QuantSpec('qsv','xsv+1')
xs=QuantSpec('xsv','3')
qse = qs.eval()
qt1 = str(qse) == '4'
print "qs.eval() == 4? ", qt1
assert qt1
assert qse.tonumeric() == 4
print "asq = xs/qs"
コード例 #15
0
ファイル: test_one_dim.py プロジェクト: andrely/mimir
def test_sign():
    assert_approx_equal(sign(.8, .4), .8)
    assert_approx_equal(sign(.4, -.8), -.4)
コード例 #16
0
assert isinstance(df.fromvector(), list)

y0=Var('y0')
y1=Var('y1')
y2=Var('y2')
t=Var('t')

ydot0=Fun(-0.04*y0 + 1e4*y1*y2, [y0, y1, y2], 'ydot0')
ydot2=Fun(3e7*y1*y1, [y0, y1, y2], 'ydot2')
ydot1=Fun(-ydot0(y0,y1,y2)-ydot2(y0,y1,y2), [y0, y1, y2], 'ydot1')

F = Fun([ydot0(y0,y1,y2),ydot1(y0,y1,y2),ydot2(y0,y1,y2)], [y0,y1,y2], 'F')
assert F.dim == 3
DF = Diff(F,[y0,y1,y2])
DF0,DF1,DF2 = DF.fromvector()
assert_approx_equal(DF0.fromvector()[0].tonumeric(), -0.04)
# str(Diff(F,[y0,y1,y2])) should be (to within numerical rounding errors):
#'[[-0.04,10000*y2,10000*y1],[0.040000000000000001,(-10000*y2)-30000000*2*y1,-10000*y1],[0,30000000*2*y1,0]]')

jac=Fun(Diff(F,[y0,y1,y2]), [t, y0, y1, y2], 'Jacobian')
assert jac(t, 0.1,y0+1,0.5).eval(y0=0) == jac(t, 0.1,1+y0,0.5).eval(y0=0)
assert jac(t, 0.1,y0,0.5) == jac(t, 0.1,0+y0,0.5)

x=Var('x')
y=Var('y')

f1 = Fun([-3*x**3+2*(x+y),-y/2], [x,y], 'f1')
f2 = ['-3*x**3+2*(x+y)','-y/2']
f3 = [-3*x**3.+2*(x+y),-y/2.]
print "\n\nVector-valued function f(x,y) =", f1
print "The function string can be passed to Diff in various ways..."
コード例 #17
0
def test_symbolic():
    assert doneg('-x-y') == 'x+y'
    assert doneg('(-x-y)') == '(x+y)'
    assert doneg('-(-x-y)') == '(-x-y)'
    assert dosub('1', '-x-y') == '(1+x+y)'

    g2 = expr2fun('1-max([0., -a+b*x])', **{'a': 3, 'b': 1.5})
    assert g2._args == ['x']
    assert g2(1) == 1.0
    assert g2(10) == -11.0

    ds = {'a': 3, 'bbb': 1}
    f=expr2fun('1+ds["a"]')
    assert f._args == ['ds']
    assert f(ds) == 4
    f2=expr2fun('1+ds["a"]')
    assert f2(**{'ds':ds}) == 4
    assert f2._args == ['ds']
    g=expr2fun('1+ds["bbb"]', ds=ds)
    assert g() == 2
    # g must be dynamic and not based on static eval of ds on initialization
    ds['bbb'] = 2
    assert g._args == []
    assert g() == 3

    m = args(pars=copy(ds))
    h = expr2fun('m.pars["a"]+c', m=m, c=1)
    assert h() == 4
    assert h._args == []
    h2 = expr2fun('1 + m.pars["a"]/2.', m=m)
    assert h2() == 2.5
    assert h2._args == []

    def func(x, y):
        return x * (y+1)

    m.func = func
    i = expr2fun('1+func(x,y)+b', func=m.func, b=0.5)
    assert 1+func(2,3)+0.5 == i(2,3)

    j = expr2fun('i(x,func(2,y))*2', i=i, func=m.func)
    assert j(1,0) == 9

    fnspec = {'f': (['x','y'], 'x+1+2*y-a')}
    # a is expected to be in scope like a FuncSpec parameter
    # so can't use the above method of providing explicit functions
    k = expr2fun('-f(c,d)+b', f=fnspec['f'], b=0.5, a=1)
    assert k(1,2) == -4.5

    s='1+a/(f(x,y)-3)+h(2)'
    t=s.replace('y','g(x,z)')
    u=t.replace('z','f(z)')
    r1, d1 = replaceCallsWithDummies(s, ['f','g','h'])
    r2, d2 = replaceCallsWithDummies(t, ['f','g','h'])
    r3, d3 = replaceCallsWithDummies(u, ['f','g','h'])

    assert r1 == '1+a/(__dummy1__-3)+__dummy2__'
    assert len(d1) == 2
    assert r2 == '1+a/(__dummy2__-3)+__dummy3__'
    assert len(d2) == 3
    assert r2 == '1+a/(__dummy2__-3)+__dummy3__'
    assert len(d3) == 4

    ps = 'abs((HB9_fs_Vq-HB9_fs_V)*(-((HB9_fs_Lk_g*(HB9_fs_V-HB9_fs_Lk_vrev))+(-HB9_fs_Iapp_Ibias)+((HB9_fs_Na_g*(1.0/(1.0+exp((HB9_fs_V-HB9_fs_Na_theta_m)/HB9_fs_Na_k_m)))*(1.0/(1.0+exp((HB9_fs_V-HB9_fs_Na_theta_m)/HB9_fs_Na_k_m)))*(1.0/(1.0+exp((HB9_fs_V-HB9_fs_Na_theta_m)/HB9_fs_Na_k_m)))*(1-HB9_fs_K_n))*(HB9_fs_V-HB9_fs_Na_vrev))+(HB9_fs_K_g*HB9_fs_K_n*HB9_fs_K_n*HB9_fs_K_n*HB9_fs_K_n*(HB9_fs_V-HB9_fs_K_vrev))+(HB9_fs_isyn_g*(HB9_fs_V-HB9_fs_isyn_vrev))+(HB9_fs_esyn_g*(HB9_fs_V-HB9_fs_esyn_vrev)))/HB9_fs_C)+(HB9_fs_Knq-HB9_fs_K_n)*(((1.0/(1.0+exp((HB9_fs_V-HB9_fs_K_theta_n)/HB9_fs_K_k_n)))-HB9_fs_K_n)/(HB9_fs_K_taun_bar/cosh((HB9_fs_V-HB9_fs_K_theta_n)/(2*HB9_fs_K_k_n)))))/(sqrt(HB9_fs_Vq*HB9_fs_Vq+HB9_fs_Knq*HB9_fs_Knq)+sqrt(pow((-((HB9_fs_Lk_g*(HB9_fs_V-HB9_fs_Lk_vrev))+(-HB9_fs_Iapp_Ibias)+((HB9_fs_Na_g*(1.0/(1.0+exp((HB9_fs_V-HB9_fs_Na_theta_m)/HB9_fs_Na_k_m)))*(1.0/(1.0+exp((HB9_fs_V-HB9_fs_Na_theta_m)/HB9_fs_Na_k_m)))*(1.0/(1.0+exp((HB9_fs_V-HB9_fs_Na_theta_m)/HB9_fs_Na_k_m)))*(1-HB9_fs_K_n))*(HB9_fs_V-HB9_fs_Na_vrev))+(HB9_fs_K_g*HB9_fs_K_n*HB9_fs_K_n*HB9_fs_K_n*HB9_fs_K_n*(HB9_fs_V-HB9_fs_K_vrev))+(HB9_fs_isyn_g*(HB9_fs_V-HB9_fs_isyn_vrev))+(HB9_fs_esyn_g*(HB9_fs_V-HB9_fs_esyn_vrev)))/HB9_fs_C),2)+pow((((1.0/(1.0+exp((HB9_fs_V-HB9_fs_K_theta_n)/HB9_fs_K_k_n)))-HB9_fs_K_n)/(HB9_fs_K_taun_bar/cosh((HB9_fs_V-HB9_fs_K_theta_n)/(2*HB9_fs_K_k_n)))),2)))'
    parnames = ['HB9_fs_Vq', 'HB9_fs_Lk_g', 'HB9_fs_Lk_vrev', 'HB9_fs_Iapp_Ibias', 'HB9_fs_Na_g', 'HB9_fs_Na_theta_m', 'HB9_fs_Na_k_m', 'HB9_fs_Na_vrev', 'HB9_fs_K_g', 'HB9_fs_K_vrev', 'HB9_fs_isyn_g', 'HB9_fs_isyn_vrev', 'HB9_fs_esyn_g', 'HB9_fs_esyn_vrev', 'HB9_fs_C', 'HB9_fs_Knq', 'HB9_fs_K_theta_n', 'HB9_fs_K_k_n', 'HB9_fs_K_taun_bar']
    varnames = ['HB9_fs_V', 'HB9_fs_K_n']
    ps2 = convertPowers(ps, 'pow')
    for n in parnames+varnames:
        v=rand(1)[0]+1e-5
        ps2=ps2.replace(n,str(v))
        ps=ps.replace(n,str(v))
    eps=eval(ps)
    eps2=eval(ps2)
    assert eps==eps2

    a = Par('3.5', 'a')
    qa = Var(['a*3', 'b'], 'array_test')
    assert str(qa.eval(a=1)) == '[3,b]'
    # explicit exporting 'a' to globals to make this work as expected
    globals()['a'] = a
    assert str(qa.eval()) == '[10.5,b]'

    testq = QuantSpec('d', 'a')
    testq.simplify()
    assert testq() == 'a'
    assert str(testq.eval(a=3)) == '3'
    q = QuantSpec('q', 'zeta(yrel(y,initcond(y)),z)-1')
    print q.eval({})
    assert 'initcond' in str(q.eval({}))
    q2=QuantSpec('q','Exp(-spikeTable+b)/k')
    assert 'spikeTable' in q2.freeSymbols

    #    x = Var('x')
    #    print x.isDefined()
    #    xs = QuantSpec('x', '1-rel - 2*x + cos(z) + 2e10', 'RHSfuncSpec')
    #    x.bindSpec(xs)
    #    print x.isDefined(),"\n"

    x = Var(QuantSpec('x', '1-rel - 2*x + cos(z) + 2e10', 'RHSfuncSpec'))
    p = Par('p')
    az = Var(QuantSpec('z', 'myfunc(0,z)+abs(x+1)', 'RHSfuncSpec'))
    w = Var('x-1/w[i]', 'w[i,0,1]', specType='RHSfuncSpec')



    myLeaf1.compatibleContainers=(myNode,)
    myLeaf2.compatibleContainers=(myNode,)
    myNode.compatibleSubcomponents=(myLeaf1,myLeaf2)

    c = myLeaf1('leaf1')

    assert c.isDefined() == False
    c.add(x)
    print c.freeSymbols, c.isDefined()
    c.add(az)
    print c.freeSymbols, c.isDefined()
    c.add(w)
    print c.freeSymbols, c.isDefined()

    c.compileFuncSpec()
    print c.funcSpecDict

    empty_fn = Fun('1+exp(1)', [], 'dumb_fn')
    print empty_fn()

    q = Par('qpar')
    y = Var(QuantSpec('rel', 'v+p'), domain=[0,1])
    g = Fun(QuantSpec('qfunc', '-1.e-05+sin(qpar)*(10.e-5-xtol)'), ['xtol'])
    d = myLeaf2('leaf2')
    ##    d.add(y)
    q_dummy = Var(QuantSpec('q_notpar', '-2+sin(30)'))
    g_dummy = Fun(QuantSpec('qfunc_dummy', 'sin(q_notpar)*(10.e-5-xtol)'), ['xtol'])
    d.add([q_dummy, g_dummy])  # will delete these later
    d.add([q,g])

    d2 = myLeaf2('leaf3')
    d2.add([q,g])

    v = Var(QuantSpec('v', 'v * myfunc(rel,v) - sin(p)*t', 'RHSfuncSpec'))
    # p is a global parameter so this is ok in v
    f = Fun(QuantSpec('myfunc', '2.0+s-t+exp(p)'), ['s','t'])
    # t is just a local argument here, so it won't clash with its
    # occurrence in v (which we'll see is declared as a global
    # when we call flattenSpec()).
    ipar = Par('ipar')
    z = Var('z[i]+v/(i*ipar)', 'z[i,0,5]', specType='RHSfuncSpec')
    a = myNode('sys1')

    a.add([f,p,y])
    print a.isDefined(True)
    a.add(c)
    print a.freeSymbols, a.isDefined(), a.isComplete()
    a.add(d)
    print a.freeSymbols, a.isDefined(), a.isComplete()
    a.add(d2)
    print a.freeSymbols, a.isDefined(), a.isComplete()
    a.add(v)
    print "Added v"
    print a.freeSymbols, a.isDefined(), a.isComplete()
    print "Removed v"
    a.remove(v)
    print a.freeSymbols, a.isDefined(), a.isComplete()
    a.add([z,ipar])
    print a.freeSymbols, a.isDefined(), a.isComplete()
    print "\na._registry -->  "
    print a._registry
    print "Re-added v"
    a.add(v)
    print a.freeSymbols, a.isDefined(), a.isComplete()
    print "\nv in a -->", v in a

    print "\n"
    with pytest.raises(TypeError):
        a.compileFuncSpec()
    a.remove(['leaf2.qfunc_dummy', 'leaf2.q_notpar'])

    print "---------  sys1: funcSpecDict ---------------------"
    a.compileFuncSpec()
    info(a.funcSpecDict)

    print "\n\n-------------  Flatten spec with unravelling\n"
    print "\n\ninfo(a.flattenSpec()) --> \n"
    info(a.flattenSpec(globalRefs=['t']), "Model specification")
    print "\n\n-------------  Flatten spec with no unravelling\n"
    print "\n\ninfo(a.flattenSpec(False, globalRefs=['t'])) --> \n"
    info(a.flattenSpec(False, globalRefs=['t']), "Model specification")

    print "\n\nDemos for functions (results are strings):\n"
    h = f(p, -x)
    z = QuantSpec('zero','0')
    print "h = f(p, -x) --> ", h
    print "z = QuantSpec('zero','0') --> ", z
    print "f(g(3)*1,h) --> ", f(g(3)*1,h)
    print "f(g(p),h) --> ", f(g(p),h)
    print "f(g(p),0*h) --> ", f(g(p),0*h)
    print "f(g(x),h+z) --> ", f(g(x),h+z)
    # e is the math constant, but it doesn't evaluate to a float!
    print "f(g(x()),(e+h)/2) --> ", f(g(x()),(e+h)/2)
    print "f(g(x()),-h) --> ", f(g(x()),-h)
    print "f(g(x()),.5-h+0) --> ", f(g(x()),.5-h+0)
    print "Sin(pi+q) --> ", Sin(pi+q)
    qsin=QuantSpec('qsin','zv-sin(beta)')
    assert str(qsin.eval()) == 'zv-sin(beta)'

    print "\n\nDemos for local scope evaluation and **:\n"
    print "q=Var('xv+1','qv')"
    print "x=Var('3','xv')"
    q=Var('xv+1','qv')
    x=Var('3','xv')
    globals()['x'] = x
    globals()['q'] = q
    sc1 = str(q.eval()) == '4'
    print "q.eval() == 4? ", sc1
    assert sc1
    print "a=x/q"
    a=x/q
    sc2 = str(a) == 'xv/qv'
    print "a == xv/qv? ", sc2
    assert sc2
    sc3 = str(a.eval())=='0.75'
    print "a.eval() == 0.75? ", sc3
    assert sc3
    sc4 = str(a.eval(xv=5))=='5/qv'
    print "a.eval(xv=5) == 5/q? ", sc4
    assert sc4
    sc5 = (str(a.eval(xv=5,qv=q())),'0.83333333333333337')
    assert_approx_equal(*sc5)
    print "assert_approx_equal(%s,%s)" % sc5
    sc6 = (str(a.eval({'xv': 10, 'qv': q()})),'0.90909090909090906')
    print "assert_approx_equal(%s,%s)" % sc6
    assert_approx_equal(*sc6)

    print "qs=QuantSpec('qsv','xsv+1')"
    print "xs=QuantSpec('xsv','3')"
    qs=QuantSpec('qsv','xsv+1')
    xs=QuantSpec('xsv','3')
    globals()['qs'] = qs
    globals()['xs'] = xs
    qse = qs.eval()
    qt1 = str(qse) == '4'
    print "qs.eval() == 4? ", qt1
    assert qt1
    assert qse.tonumeric() == 4
    print "asq = xs/qs"
    asq=xs/qs
    qt2 = str(asq) == '3/(xsv+1)'
    print "asq == 3/(xsv+1)? ", qt2
    assert qt2
    qt3 = str(asq.eval()) == '0.75'
    print "as.eval() == 0.75? ", qt3
    assert qt3
    ps = asq**xs
    print "ps = as**xs"
    qt4 = str(ps) == 'Pow(3/(xsv+1),3)'
    print "ps == Pow(3/(xsv+1),3)? ", qt4
    assert qt4
    qt5 = str(ps.eval()) == str(0.75**3)
    print "ps.eval() == 0.421875? ", qt5
    assert qt5

    print "sq=QuantSpec('sv','sin(xsv)')"
    print "s2q=QuantSpec('s2v','Sin(xv)')"
    sq=QuantSpec('sv','sin(xsv)')
    s2q=QuantSpec('s2v','Sin(xv)')
    print "sq.eval() --> ", sq.eval()
    print "s2q.eval() --> ", s2q.eval()
    assert sq.eval().tonumeric() == s2q.eval().tonumeric()
    assert sq[:] == ['sin','(','xsv',')']

    print "\n\nDemos for multiple quantity definitions:\n"
    mp=QuantSpec('p','a + 3*z[4*i-2]')
    m=Var(mp, 'z[i,2,5]', specType='RHSfuncSpec')
    v=Var('3*z[i-1]+z4-i', 'z[i,1,5]', specType='RHSfuncSpec')
    print "mp=QuantSpec('p','a + 3*z[4*i-2]')"
    print "m=Var(mp, 'z[i,2,5]', specType='RHSfuncSpec')"
    print "v=Var('3*z[i-1]+z4-i', 'z[i,1,5]', specType='RHSfuncSpec')"
    print "v[3] -->", v[3]
    assert str(v[3])=='z3'
    print "v.freeSymbols -->", v.freeSymbols
    assert v.freeSymbols == ['z0']
    print "\nModelSpec a already contains 'z0', which was defined as part of"
    print "a multiple quantity definition, so check that attempting to add"
    print "v to a results in an error ..."
    with pytest.raises(AttributeError):
        a.add(v)
    print "\nTest of eval method, e.g. on a function f(s,t)..."
    print "f.eval(s='1', t='t_val') -->", f.eval(s='1', t='t_val')
    print "f.eval(s=1, t='t_val', p=0.5) -->", f.eval(s=1, t='t_val', p=0.5)
    print "\nTesting convertPowers():"
    cp_tests = ["phi1dot^m3", "1+phi1dot^m3*s",
                "phi1dot**m3", "1+phi1dot**m3*s",
                "sin(x^3)**4", "(2/3)^2.5", "3^cos(x)-pi",
                "3^(cos(x)-pi)", "2^(sin(y**p))"]
    for spec in cp_tests:
        print spec, " --> ", convertPowers(spec)


    globals().pop('a')
    qc=QuantSpec('t', "a+coot+b/'coot'")
    assert str(qc.eval()) == 'a+coot+b/"coot"'
    coot=QuantSpec('coot', "1.05")
    globals()['coot'] = coot
    assert str(qc.eval()) == 'a+1.05+b/"coot"'

    print "\nTest of function calling with argument names that clash with"
    print "bound names inside the function."
    x0=Var('x0')
    x1=Var('x1')
    x2=Var('x2')
    F=Fun([x0*x2,x0*5,x2**0.5], [x0,x1,x2], 'F')
    print "F=Fun([x0*x2,x0*5,x2**0.5], [x0,x1,x2], 'F')"
    print "F(3,2,Sin(x0))) = [3*Sin(x0),15,Pow(Sin(x0),0.5)] ..."
    print "  ... even though x0 is a bound name inside definition of F"
    assert str(F(3,2,Sin(x0)))=='[3*Sin(x0),15,Pow(Sin(x0),0.5)]'
コード例 #18
0
 def test_results_bootstrapped(self):
     results = cbook.boxplot_stats(self.data, bootstrap=10000)
     res = results[0]
     for key, value in self.known_bootstrapped_ci.items():
         assert_approx_equal(res[key], value)
コード例 #19
0
 def test_results_bootstrapped(self):
     results = cbook.boxplot_stats(self.data, bootstrap=10000)
     res = results[0]
     for key, value in self.known_bootstrapped_ci.items():
         assert_approx_equal(res[key], value)
コード例 #20
0
 def test_results_bootstrapped(self):
     results = cbook.boxplot_stats(self.data, bootstrap=10000)
     res = results[0]
     for key in list(self.known_bootstrapped_ci.keys()):
         assert_approx_equal(res[key], self.known_bootstrapped_ci[key])
コード例 #21
0
ファイル: test_symbolic.py プロジェクト: tclose/pydstool
def test_symbolic():
    assert doneg('-x-y') == 'x+y'
    assert doneg('(-x-y)') == '(x+y)'
    assert doneg('-(-x-y)') == '(-x-y)'
    assert dosub('1', '-x-y') == '(1+x+y)'

    g2 = expr2fun('1-max([0., -a+b*x])', **{'a': 3, 'b': 1.5})
    assert g2._args == ['x']
    assert g2(1) == 1.0
    assert g2(10) == -11.0

    ds = {'a': 3, 'bbb': 1}
    f = expr2fun('1+ds["a"]')
    assert f._args == ['ds']
    assert f(ds) == 4
    f2 = expr2fun('1+ds["a"]')
    assert f2(**{'ds': ds}) == 4
    assert f2._args == ['ds']
    g = expr2fun('1+ds["bbb"]', ds=ds)
    assert g() == 2
    # g must be dynamic and not based on static eval of ds on initialization
    ds['bbb'] = 2
    assert g._args == []
    assert g() == 3

    m = args(pars=copy(ds))
    h = expr2fun('m.pars["a"]+c', m=m, c=1)
    assert h() == 4
    assert h._args == []
    h2 = expr2fun('1 + m.pars["a"]/2.', m=m)
    assert h2() == 2.5
    assert h2._args == []

    def func(x, y):
        return x * (y + 1)

    m.func = func
    i = expr2fun('1+func(x,y)+b', func=m.func, b=0.5)
    assert 1 + func(2, 3) + 0.5 == i(2, 3)

    j = expr2fun('i(x,func(2,y))*2', i=i, func=m.func)
    assert j(1, 0) == 9

    fnspec = {'f': (['x', 'y'], 'x+1+2*y-a')}
    # a is expected to be in scope like a FuncSpec parameter
    # so can't use the above method of providing explicit functions
    k = expr2fun('-f(c,d)+b', f=fnspec['f'], b=0.5, a=1)
    assert k(1, 2) == -4.5

    # alternate scope and testing embedded dynamic pars in both
    # main expression and sub-expressions like f()
    l = expr2fun('-f(c,d)+b', ensure_dynamic={'a': 1, 'c': 2}, **fnspec)
    assert l._args == ['d', 'b']
    assert l._call_spec == "-self.f(self._pardict['c'],d)+b"
    assert l(1, 2) == -2

    s = '1+a/(f(x,y)-3)+h(2)'
    t = s.replace('y', 'g(x,z)')
    u = t.replace('z', 'f(z)')
    r1, d1 = replaceCallsWithDummies(s, ['f', 'g', 'h'])
    r2, d2 = replaceCallsWithDummies(t, ['f', 'g', 'h'])
    r3, d3 = replaceCallsWithDummies(u, ['f', 'g', 'h'])

    assert r1 == '1+a/(__dummy1__-3)+__dummy2__'
    assert len(d1) == 2
    assert r2 == '1+a/(__dummy2__-3)+__dummy3__'
    assert len(d2) == 3
    assert r2 == '1+a/(__dummy2__-3)+__dummy3__'
    assert len(d3) == 4

    ps = 'abs((HB9_fs_Vq-HB9_fs_V)*(-((HB9_fs_Lk_g*(HB9_fs_V-HB9_fs_Lk_vrev))+(-HB9_fs_Iapp_Ibias)+((HB9_fs_Na_g*(1.0/(1.0+exp((HB9_fs_V-HB9_fs_Na_theta_m)/HB9_fs_Na_k_m)))*(1.0/(1.0+exp((HB9_fs_V-HB9_fs_Na_theta_m)/HB9_fs_Na_k_m)))*(1.0/(1.0+exp((HB9_fs_V-HB9_fs_Na_theta_m)/HB9_fs_Na_k_m)))*(1-HB9_fs_K_n))*(HB9_fs_V-HB9_fs_Na_vrev))+(HB9_fs_K_g*HB9_fs_K_n*HB9_fs_K_n*HB9_fs_K_n*HB9_fs_K_n*(HB9_fs_V-HB9_fs_K_vrev))+(HB9_fs_isyn_g*(HB9_fs_V-HB9_fs_isyn_vrev))+(HB9_fs_esyn_g*(HB9_fs_V-HB9_fs_esyn_vrev)))/HB9_fs_C)+(HB9_fs_Knq-HB9_fs_K_n)*(((1.0/(1.0+exp((HB9_fs_V-HB9_fs_K_theta_n)/HB9_fs_K_k_n)))-HB9_fs_K_n)/(HB9_fs_K_taun_bar/cosh((HB9_fs_V-HB9_fs_K_theta_n)/(2*HB9_fs_K_k_n)))))/(sqrt(HB9_fs_Vq*HB9_fs_Vq+HB9_fs_Knq*HB9_fs_Knq)+sqrt(pow((-((HB9_fs_Lk_g*(HB9_fs_V-HB9_fs_Lk_vrev))+(-HB9_fs_Iapp_Ibias)+((HB9_fs_Na_g*(1.0/(1.0+exp((HB9_fs_V-HB9_fs_Na_theta_m)/HB9_fs_Na_k_m)))*(1.0/(1.0+exp((HB9_fs_V-HB9_fs_Na_theta_m)/HB9_fs_Na_k_m)))*(1.0/(1.0+exp((HB9_fs_V-HB9_fs_Na_theta_m)/HB9_fs_Na_k_m)))*(1-HB9_fs_K_n))*(HB9_fs_V-HB9_fs_Na_vrev))+(HB9_fs_K_g*HB9_fs_K_n*HB9_fs_K_n*HB9_fs_K_n*HB9_fs_K_n*(HB9_fs_V-HB9_fs_K_vrev))+(HB9_fs_isyn_g*(HB9_fs_V-HB9_fs_isyn_vrev))+(HB9_fs_esyn_g*(HB9_fs_V-HB9_fs_esyn_vrev)))/HB9_fs_C),2)+pow((((1.0/(1.0+exp((HB9_fs_V-HB9_fs_K_theta_n)/HB9_fs_K_k_n)))-HB9_fs_K_n)/(HB9_fs_K_taun_bar/cosh((HB9_fs_V-HB9_fs_K_theta_n)/(2*HB9_fs_K_k_n)))),2)))'
    parnames = [
        'HB9_fs_Vq', 'HB9_fs_Lk_g', 'HB9_fs_Lk_vrev', 'HB9_fs_Iapp_Ibias',
        'HB9_fs_Na_g', 'HB9_fs_Na_theta_m', 'HB9_fs_Na_k_m', 'HB9_fs_Na_vrev',
        'HB9_fs_K_g', 'HB9_fs_K_vrev', 'HB9_fs_isyn_g', 'HB9_fs_isyn_vrev',
        'HB9_fs_esyn_g', 'HB9_fs_esyn_vrev', 'HB9_fs_C', 'HB9_fs_Knq',
        'HB9_fs_K_theta_n', 'HB9_fs_K_k_n', 'HB9_fs_K_taun_bar'
    ]
    varnames = ['HB9_fs_V', 'HB9_fs_K_n']
    ps2 = convertPowers(ps, 'pow')
    for n in parnames + varnames:
        v = rand(1)[0] + 1e-5
        ps2 = ps2.replace(n, str(v))
        ps = ps.replace(n, str(v))
    eps = eval(ps)
    eps2 = eval(ps2)
    assert eps == eps2

    a = Par('3.5', 'a')
    qa = Var(['a*3', 'b'], 'array_test')
    assert str(qa.eval(a=1)) == '[3,b]'
    # explicit exporting 'a' to globals to make this work as expected
    globals()['a'] = a
    assert str(qa.eval()) == '[10.5,b]'

    testq = QuantSpec('d', 'a')
    testq.simplify()
    assert testq() == 'a'
    assert str(testq.eval(a=3)) == '3'
    q = QuantSpec('q', 'zeta(yrel(y,initcond(y)),z)-1')
    print(q.eval({}))
    assert 'initcond' in str(q.eval({}))
    q2 = QuantSpec('q', 'Exp(-spikeTable+b)/k')
    assert 'spikeTable' in q2.freeSymbols

    #    x = Var('x')
    #    print x.isDefined()
    #    xs = QuantSpec('x', '1-rel - 2*x + cos(z) + 2e10', 'RHSfuncSpec')
    #    x.bindSpec(xs)
    #    print x.isDefined(),"\n"

    x = Var(QuantSpec('x', '1-rel - 2*x + cos(z) + 2e10', 'RHSfuncSpec'))
    p = Par('p')
    az = Var(QuantSpec('z', 'myfunc(0,z)+abs(x+1)', 'RHSfuncSpec'))
    w = Var('x-1/w[i]', 'w[i,0,1]', specType='RHSfuncSpec')

    myLeaf1.compatibleContainers = (myNode, )
    myLeaf2.compatibleContainers = (myNode, )
    myNode.compatibleSubcomponents = (myLeaf1, myLeaf2)

    c = myLeaf1('leaf1')

    assert c.isDefined() == False
    c.add(x)
    print(c.freeSymbols, c.isDefined())
    c.add(az)
    print(c.freeSymbols, c.isDefined())
    c.add(w)
    print(c.freeSymbols, c.isDefined())

    c.compileFuncSpec()
    print(c.funcSpecDict)

    empty_fn = Fun('1+exp(1)', [], 'dumb_fn')
    print(empty_fn())

    q = Par('qpar')
    y = Var(QuantSpec('rel', 'v+p'), domain=[0, 1])
    g = Fun(QuantSpec('qfunc', '-1.e-05+sin(qpar)*(10.e-5-xtol)'), ['xtol'])
    d = myLeaf2('leaf2')
    ##    d.add(y)
    q_dummy = Var(QuantSpec('q_notpar', '-2+sin(30)'))
    g_dummy = Fun(QuantSpec('qfunc_dummy', 'sin(q_notpar)*(10.e-5-xtol)'),
                  ['xtol'])
    d.add([q_dummy, g_dummy])  # will delete these later
    d.add([q, g])

    d2 = myLeaf2('leaf3')
    d2.add([q, g])

    v = Var(QuantSpec('v', 'v * myfunc(rel,v) - sin(p)*t', 'RHSfuncSpec'))
    # p is a global parameter so this is ok in v
    f = Fun(QuantSpec('myfunc', '2.0+s-t+exp(p)'), ['s', 't'])
    # t is just a local argument here, so it won't clash with its
    # occurrence in v (which we'll see is declared as a global
    # when we call flattenSpec()).
    ipar = Par('ipar')
    z = Var('z[i]+v/(i*ipar)', 'z[i,0,5]', specType='RHSfuncSpec')
    a = myNode('sys1')

    a.add([f, p, y])
    print(a.isDefined(True))
    a.add(c)
    print(a.freeSymbols, a.isDefined(), a.isComplete())
    a.add(d)
    print(a.freeSymbols, a.isDefined(), a.isComplete())
    a.add(d2)
    print(a.freeSymbols, a.isDefined(), a.isComplete())
    a.add(v)
    print("Added v")
    print(a.freeSymbols, a.isDefined(), a.isComplete())
    print("Removed v")
    a.remove(v)
    print(a.freeSymbols, a.isDefined(), a.isComplete())
    a.add([z, ipar])
    print(a.freeSymbols, a.isDefined(), a.isComplete())
    print("\na._registry -->  ")
    print(a._registry)
    print("Re-added v")
    a.add(v)
    print(a.freeSymbols, a.isDefined(), a.isComplete())
    print("\nv in a -->", v in a)

    print("\n")
    with pytest.raises(TypeError):
        a.compileFuncSpec()
    a.remove(['leaf2.qfunc_dummy', 'leaf2.q_notpar'])

    print("---------  sys1: funcSpecDict ---------------------")
    a.compileFuncSpec()
    info(a.funcSpecDict)

    print("\n\n-------------  Flatten spec with unravelling\n")
    print("\n\ninfo(a.flattenSpec()) --> \n")
    info(a.flattenSpec(globalRefs=['t']), "Model specification")
    print("\n\n-------------  Flatten spec with no unravelling\n")
    print("\n\ninfo(a.flattenSpec(False, globalRefs=['t'])) --> \n")
    info(a.flattenSpec(False, globalRefs=['t']), "Model specification")

    print("\n\nDemos for functions (results are strings):\n")
    h = f(p, -x)
    z = QuantSpec('zero', '0')
    print("h = f(p, -x) --> ", h)
    print("z = QuantSpec('zero','0') --> ", z)
    print("f(g(3)*1,h) --> ", f(g(3) * 1, h))
    print("f(g(p),h) --> ", f(g(p), h))
    print("f(g(p),0*h) --> ", f(g(p), 0 * h))
    print("f(g(x),h+z) --> ", f(g(x), h + z))
    # e is the math constant, but it doesn't evaluate to a float!
    print("f(g(x()),(e+h)/2) --> ", f(g(x()), (e + h) / 2))
    print("f(g(x()),-h) --> ", f(g(x()), -h))
    print("f(g(x()),.5-h+0) --> ", f(g(x()), .5 - h + 0))
    print("Sin(pi+q) --> ", Sin(pi + q))
    qsin = QuantSpec('qsin', 'zv-sin(beta)')
    assert str(qsin.eval()) == 'zv-sin(beta)'

    print("\n\nDemos for local scope evaluation and **:\n")
    print("q=Var('xv+1','qv')")
    print("x=Var('3','xv')")
    q = Var('xv+1', 'qv')
    x = Var('3', 'xv')
    globals()['x'] = x
    globals()['q'] = q
    sc1 = str(q.eval()) == '4'
    print("q.eval() == 4? ", sc1)
    assert sc1
    print("a=x/q")
    a = x / q
    sc2 = str(a) == 'xv/qv'
    print("a == xv/qv? ", sc2)
    assert sc2
    sc3 = str(a.eval()) == '0.75'
    print("a.eval() == 0.75? ", sc3)
    assert sc3
    sc4 = str(a.eval(xv=5)) == '5/qv'
    print("a.eval(xv=5) == 5/q? ", sc4)
    assert sc4
    sc5 = (str(a.eval(xv=5, qv=q())), '0.83333333333333337')
    assert_approx_equal(*sc5)
    print("assert_approx_equal(%s,%s)" % sc5)
    sc6 = (str(a.eval({'xv': 10, 'qv': q()})), '0.90909090909090906')
    print("assert_approx_equal(%s,%s)" % sc6)
    assert_approx_equal(*sc6)

    print("qs=QuantSpec('qsv','xsv+1')")
    print("xs=QuantSpec('xsv','3')")
    qs = QuantSpec('qsv', 'xsv+1')
    xs = QuantSpec('xsv', '3')
    globals()['qs'] = qs
    globals()['xs'] = xs
    qse = qs.eval()
    qt1 = str(qse) == '4'
    print("qs.eval() == 4? ", qt1)
    assert qt1
    assert qse.tonumeric() == 4
    print("asq = xs/qs")
    asq = xs / qs
    qt2 = str(asq) == '3/(xsv+1)'
    print("asq == 3/(xsv+1)? ", qt2)
    assert qt2
    qt3 = str(asq.eval()) == '0.75'
    print("as.eval() == 0.75? ", qt3)
    assert qt3
    ps = asq**xs
    print("ps = as**xs")
    qt4 = str(ps) == 'Pow(3/(xsv+1),3)'
    print("ps == Pow(3/(xsv+1),3)? ", qt4)
    assert qt4
    qt5 = str(ps.eval()) == str(0.75**3)
    print("ps.eval() == 0.421875? ", qt5)
    assert qt5

    print("sq=QuantSpec('sv','sin(xsv)')")
    print("s2q=QuantSpec('s2v','Sin(xv)')")
    sq = QuantSpec('sv', 'sin(xsv)')
    s2q = QuantSpec('s2v', 'Sin(xv)')
    print("sq.eval() --> ", sq.eval())
    print("s2q.eval() --> ", s2q.eval())
    assert sq.eval().tonumeric() == s2q.eval().tonumeric()
    assert sq[:] == ['sin', '(', 'xsv', ')']

    print("\n\nDemos for multiple quantity definitions:\n")
    mp = QuantSpec('p', 'a + 3*z[4*i-2]')
    m = Var(mp, 'z[i,2,5]', specType='RHSfuncSpec')
    v = Var('3*z[i-1]+z4-i', 'z[i,1,5]', specType='RHSfuncSpec')
    print("mp=QuantSpec('p','a + 3*z[4*i-2]')")
    print("m=Var(mp, 'z[i,2,5]', specType='RHSfuncSpec')")
    print("v=Var('3*z[i-1]+z4-i', 'z[i,1,5]', specType='RHSfuncSpec')")
    print("v[3] -->", v[3])
    assert str(v[3]) == 'z3'
    print("v.freeSymbols -->", v.freeSymbols)
    assert v.freeSymbols == ['z0']
    print("\nModelSpec a already contains 'z0', which was defined as part of")
    print("a multiple quantity definition, so check that attempting to add")
    print("v to a results in an error ...")
    with pytest.raises(AttributeError):
        a.add(v)
    print("\nTest of eval method, e.g. on a function f(s,t)...")
    print("f.eval(s='1', t='t_val') -->", f.eval(s='1', t='t_val'))
    print("f.eval(s=1, t='t_val', p=0.5) -->", f.eval(s=1, t='t_val', p=0.5))
    print("\nTesting convertPowers():")
    cp_tests = [
        "phi1dot^m3", "1+phi1dot^m3*s", "phi1dot**m3", "1+phi1dot**m3*s",
        "sin(x^3)**4", "(2/3)^2.5", "3^cos(x)-pi", "3^(cos(x)-pi)",
        "2^(sin(y**p))"
    ]
    for spec in cp_tests:
        print(spec, " --> ", convertPowers(spec))

    globals().pop('a')
    qc = QuantSpec('t', "a+coot+b/'coot'")
    assert str(qc.eval()) == 'a+coot+b/"coot"'
    coot = QuantSpec('coot', "1.05")
    globals()['coot'] = coot
    assert str(qc.eval()) == 'a+1.05+b/"coot"'

    print("\nTest of function calling with argument names that clash with")
    print("bound names inside the function.")
    x0 = Var('x0')
    x1 = Var('x1')
    x2 = Var('x2')
    F = Fun([x0 * x2, x0 * 5, x2**0.5], [x0, x1, x2], 'F')
    print("F=Fun([x0*x2,x0*5,x2**0.5], [x0,x1,x2], 'F')")
    print("F(3,2,Sin(x0))) = [3*Sin(x0),15,Pow(Sin(x0),0.5)] ...")
    print("  ... even though x0 is a bound name inside definition of F")
    assert str(F(3, 2, Sin(x0))) == '[3*Sin(x0),15,Pow(Sin(x0),0.5)]'
コード例 #22
0
def test_power():
    """Check that the power module is working."""
    import cosmolopy.EH.power as power
    power.TFmdm_set_cosm(0.3, 0.04, 0.0, 0, 0.7, 0.72, 0.0)
    ntest.assert_approx_equal(power.TFmdm_onek_hmpc(100.0),
                              1.48236347286e-06)