Beispiel #1
0
def test_cosmology_repr():
    """Check that we can make a Cosmology object from its repr."""
    import pyccl  # noqa: F401

    cosmo = ccl.Cosmology(
        Omega_c=0.25, Omega_b=0.05, h=0.7, A_s=2.1e-9, n_s=0.96,
        m_nu=[0.02, 0.1, 0.05], m_nu_type='list',
        z_mg=[0.0, 1.0], df_mg=[0.01, 0.0])

    cosmo2 = eval(str(cosmo))
    assert_(
        ccl.comoving_radial_distance(cosmo, 0.5) ==
        ccl.comoving_radial_distance(cosmo2, 0.5))

    cosmo3 = eval(repr(cosmo))
    assert_(
        ccl.comoving_radial_distance(cosmo, 0.5) ==
        ccl.comoving_radial_distance(cosmo3, 0.5))

    # same test with arrays to be sure
    cosmo = ccl.Cosmology(
        Omega_c=0.25, Omega_b=0.05, h=0.7, A_s=2.1e-9, n_s=0.96,
        m_nu=np.array([0.02, 0.1, 0.05]), m_nu_type='list',
        z_mg=np.array([0.0, 1.0]), df_mg=np.array([0.01, 0.0]))

    cosmo2 = eval(str(cosmo))
    assert_(
        ccl.comoving_radial_distance(cosmo, 0.5) ==
        ccl.comoving_radial_distance(cosmo2, 0.5))

    cosmo3 = eval(repr(cosmo))
    assert_(
        ccl.comoving_radial_distance(cosmo, 0.5) ==
        ccl.comoving_radial_distance(cosmo3, 0.5))
def test_power_mu_sigma_sigma8norm(tf):
    cosmo = ccl.Cosmology(
        Omega_c=0.27, Omega_b=0.045, h=0.67, sigma8=0.8, n_s=0.96,
        transfer_function=tf)

    cosmo_musig = ccl.Cosmology(
        Omega_c=0.27, Omega_b=0.045, h=0.67, sigma8=0.8, n_s=0.96,
        transfer_function=tf, mu_0=0.1, sigma_0=0.2)

    # make sure sigma8 is correct
    assert np.allclose(ccl.sigma8(cosmo_musig), 0.8)

    if tf != 'boltzmann_isitgr':
        # make sure P(k) ratio is right
        a = 0.8
        gfac = (
            ccl.growth_factor(cosmo, a) / ccl.growth_factor(cosmo_musig, a))**2
        pk_rat = (
            ccl.linear_matter_power(cosmo, 1e-4, a) /
            ccl.linear_matter_power(cosmo_musig, 1e-4, a))
        assert np.allclose(pk_rat, gfac)

    with mock.patch.dict(sys.modules, {'isitgr': None}):
        with assert_raises(ImportError):
            get_isitgr_pk_lin(cosmo)
    # Importing ccl without isitgr is fine.  No ImportError triggered.
    with mock.patch.dict(sys.modules, {'isitgr': None}):
        reload(ccl.boltzmann)
Beispiel #3
0
def test_input_nonlin_power_spectrum():
    cosmo = ccl.Cosmology(Omega_c=0.27, Omega_b=0.05, h=0.7, n_s=0.965,

                          A_s=2e-9)
    a_arr = np.linspace(0.1, 1.0, 50)
    k_arr = np.logspace(np.log10(2e-4), np.log10(1), 1000)
    pk_arr = np.empty(shape=(len(a_arr), len(k_arr)))
    for i, a in enumerate(a_arr):
        pk_arr[i] = ccl.power.nonlin_matter_power(cosmo, k_arr, a)

    chi_from_ccl = ccl.background.comoving_radial_distance(cosmo, a_arr)
    hoh0_from_ccl = ccl.background.h_over_h0(cosmo, a_arr)
    growth_from_ccl = ccl.background.growth_factor(cosmo, a_arr)
    fgrowth_from_ccl = ccl.background.growth_rate(cosmo, a_arr)

    cosmo_input = ccl.Cosmology(Omega_c=0.27, Omega_b=0.05, h=0.7, n_s=0.965,
                                A_s=2e-9,)
    cosmo_input._set_background_from_arrays(a_array=a_arr,
                                            chi_array=chi_from_ccl,
                                            hoh0_array=hoh0_from_ccl,
                                            growth_array=growth_from_ccl,
                                            fgrowth_array=fgrowth_from_ccl)
    cosmo_input._set_nonlin_power_from_arrays(a_arr, k_arr, pk_arr)

    pk_CCL_input = ccl.power.nonlin_matter_power(cosmo_input, k_arr, 0.5)
    pk_CCL = ccl.power.nonlin_matter_power(cosmo, k_arr, 0.5)

    assert np.allclose(pk_CCL_input, pk_CCL, atol=0., rtol=1e-5)
Beispiel #4
0
def test_power_sigma8norm_norms_consistent(tf):
    # make a cosmo with A_s
    cosmo = ccl.Cosmology(Omega_c=0.27,
                          Omega_b=0.045,
                          h=0.67,
                          A_s=2e-9,
                          n_s=0.96,
                          transfer_function=tf)
    sigma8 = ccl.sigma8(cosmo)

    # remake same but now give sigma8
    cosmo_s8 = ccl.Cosmology(Omega_c=0.27,
                             Omega_b=0.045,
                             h=0.67,
                             sigma8=sigma8,
                             n_s=0.96,
                             transfer_function=tf)

    # make sure they come out the same-ish
    assert np.allclose(ccl.sigma8(cosmo), ccl.sigma8(cosmo_s8))

    # and that the power spectra look right
    a = 0.8
    gfac = (ccl.growth_factor(cosmo, a) / ccl.growth_factor(cosmo_s8, a))**2
    pk_rat = (ccl.linear_matter_power(cosmo, 1e-4, a) /
              ccl.linear_matter_power(cosmo_s8, 1e-4, a))
    assert np.allclose(pk_rat, gfac)
Beispiel #5
0
def test_pk2d_from_model_emu():
    pars = [0.3643, 0.071075, 0.55, 0.8333, 0.9167, -0.7667, 0.1944]
    cosmo_fixed = ccl.Cosmology(Omega_c=pars[0],
                                Omega_b=pars[1],
                                h=pars[2],
                                sigma8=pars[3],
                                n_s=pars[4],
                                w0=pars[5],
                                wa=pars[6],
                                Neff=3.04,
                                Omega_g=0,
                                Omega_k=0,
                                transfer_function='bbks')
    cosmo = ccl.Cosmology(Omega_c=pars[0],
                          Omega_b=pars[1],
                          h=pars[2],
                          sigma8=pars[3],
                          n_s=pars[4],
                          w0=pars[5],
                          wa=pars[6],
                          Neff=3.04,
                          Omega_g=0,
                          Omega_k=0,
                          transfer_function='bbks',
                          matter_power_spectrum='emu')
    pk = ccl.Pk2D.pk_from_model(cosmo_fixed, model='emu')
    ks = np.geomspace(1E-3, 1E1, 128)
    for z in [0., 0.5, 2.]:
        a = 1. / (1 + z)
        pk1 = pk.eval(ks, a, cosmo)
        pk2 = ccl.nonlin_matter_power(cosmo, ks, a)
        maxdiff = np.amax(np.fabs(pk1 / pk2 - 1))
        assert maxdiff < 1E-10
Beispiel #6
0
def test_camb_class_consistent_smoke(kwargs=None, pkerr=1e-3):
    kwargs = kwargs or {}
    print('kwargs:', kwargs)

    c_camb = ccl.Cosmology(Omega_c=0.25,
                           Omega_b=0.05,
                           h=0.7,
                           n_s=0.95,
                           A_s=2e-9,
                           transfer_function='boltzmann_camb',
                           **kwargs)

    c_class = ccl.Cosmology(Omega_c=0.25,
                            Omega_b=0.05,
                            h=0.7,
                            n_s=0.95,
                            A_s=2e-9,
                            transfer_function='boltzmann_class',
                            **kwargs)

    rel_sigma8 = np.abs(ccl.sigma8(c_camb) / ccl.sigma8(c_class) - 1)

    a = 0.845
    k = np.logspace(-3, 1, 100)
    pk_camb = ccl.linear_matter_power(c_camb, k, a)
    pk_class = ccl.linear_matter_power(c_class, k, a)
    rel_pk = np.max(np.abs(pk_camb / pk_class - 1))

    print('rel err pk:', rel_pk)
    print('rel err sigma8:', rel_sigma8)

    assert rel_sigma8 < 3e-3
    assert rel_pk < pkerr
Beispiel #7
0
def test_mgrowth():
    """
    Compare the modified growth function computed by CCL against the exact 
    result for a particular modification of the growth rate.
    """
    # Define differential growth rate arrays
    nz_mg = 128
    z_mg = np.zeros(nz_mg)
    df_mg = np.zeros(nz_mg)
    for i in range(0, nz_mg):
        z_mg[i] = 4. * (i + 0.0) / (nz_mg - 1.)
        df_mg[i] = 0.1 / (1. + z_mg[i])

    # Define two test cosmologies, without and with modified growth respectively
    p1 = ccl.Parameters(Omega_c=0.25,
                        Omega_b=0.05,
                        Omega_k=0.,
                        N_nu_rel=0.,
                        N_nu_mass=0.,
                        m_nu=0.,
                        w0=-1.,
                        wa=0.,
                        h=0.7,
                        A_s=2.1e-9,
                        n_s=0.96)
    p2 = ccl.Parameters(Omega_c=0.25,
                        Omega_b=0.05,
                        Omega_k=0.,
                        N_nu_rel=0.,
                        N_nu_mass=0.,
                        m_nu=0.,
                        w0=-1.,
                        wa=0.,
                        h=0.7,
                        A_s=2.1e-9,
                        n_s=0.96,
                        z_mg=z_mg,
                        df_mg=df_mg)
    cosmo1 = ccl.Cosmology(p1)
    cosmo2 = ccl.Cosmology(p2)

    # We have included a growth modification \delta f = K*a, with K==0.1
    # (arbitrarily). This case has an analytic solution, given by
    # D(a) = D_0(a)*exp(K*(a-1)). Here we compare the growth computed by CCL
    # with the analytic solution.
    a = 1. / (1. + z_mg)

    d1 = ccl.growth_factor(cosmo1, a)
    d2 = ccl.growth_factor(cosmo2, a)
    f1 = ccl.growth_rate(cosmo1, a)
    f2 = ccl.growth_rate(cosmo2, a)

    f2r = f1 + 0.1 * a
    d2r = d1 * np.exp(0.1 * (a - 1.))

    # Check that ratio of calculated and analytic results is within tolerance
    assert_allclose(d2r / d2, np.ones(d2.size), rtol=GROWTH_TOLERANCE)
    assert_allclose(f2r / f2, np.ones(f2.size), rtol=GROWTH_TOLERANCE)
Beispiel #8
0
def test_input_nonlin_raises():
    cosmo_input = ccl.Cosmology(Omega_c=0.27, Omega_b=0.05, h=0.7, n_s=0.965,
                                A_s=2e-9)
    with pytest.raises(ValueError):
        cosmo_input._set_nonlin_power_from_arrays()
    with pytest.raises(ValueError):
        cosmo_input.compute_nonlin_power()
        cosmo_input._set_nonlin_power_from_arrays()
    cosmo_input = ccl.Cosmology(Omega_c=0.27, Omega_b=0.05, h=0.7, n_s=0.965,
                                A_s=2e-9)
    with pytest.raises(ValueError):
        cosmo_input._compute_nonlin_power_from_arrays()
Beispiel #9
0
def test_pk2d_from_model(model):
    cosmo_fixed = ccl.Cosmology(
        Omega_c=0.27, Omega_b=0.045, h=0.67, sigma8=0.8, n_s=0.96)
    cosmo = ccl.Cosmology(
        Omega_c=0.27, Omega_b=0.045, h=0.67, sigma8=0.8, n_s=0.96,
        transfer_function=model)
    pk = ccl.Pk2D.pk_from_model(cosmo_fixed, model=model)
    ks = np.geomspace(1E-3, 1E1, 128)
    for z in [0., 0.5, 2.]:
        a = 1./(1+z)
        pk1 = pk.eval(ks, a, cosmo)
        pk2 = ccl.linear_matter_power(cosmo, ks, a)
        maxdiff = np.amax(np.fabs(pk1/pk2-1))
        assert maxdiff < 1E-10
Beispiel #10
0
def reference_models():
    """
    Create a set of reference Cosmology() objects.
    """
    # Standard LCDM model
    p1 = ccl.Parameters(Omega_c=0.27,
                        Omega_b=0.045,
                        h=0.67,
                        A_s=1e-10,
                        n_s=0.96)
    cosmo1 = ccl.Cosmology(p1)

    # LCDM model with curvature
    p2 = ccl.Parameters(Omega_c=0.27,
                        Omega_b=0.045,
                        h=0.67,
                        A_s=1e-10,
                        n_s=0.96,
                        Omega_k=0.05)
    cosmo2 = ccl.Cosmology(p2)

    # wCDM model
    p3 = ccl.Parameters(Omega_c=0.27,
                        Omega_b=0.045,
                        h=0.67,
                        A_s=1e-10,
                        n_s=0.96,
                        w0=-0.95,
                        wa=0.05)
    cosmo3 = ccl.Cosmology(p3)

    # BBKS Pk
    p4 = ccl.Parameters(Omega_c=0.27,
                        Omega_b=0.045,
                        h=0.67,
                        sigma8=0.8,
                        n_s=0.96)
    cosmo4 = ccl.Cosmology(p4, transfer_function='bbks')

    # E&H Pk
    p5 = ccl.Parameters(Omega_c=0.27,
                        Omega_b=0.045,
                        h=0.67,
                        sigma8=0.8,
                        n_s=0.96)
    cosmo5 = ccl.Cosmology(p5, transfer_function='eisenstein_hu')

    # Return (only do one cosmology for now, for speed reasons)
    return [cosmo1, cosmo4, cosmo5]  # cosmo2, cosmo3
Beispiel #11
0
def compare_distances_mnu_hiz(z, chi_bench, dm_bench, Omega_v, w0, wa,
                              Neff_mnu, mnu):
    """
    Compare distances calculated by pyccl with the distances in the benchmark
    file.
    """
    # Set Omega_K in a consistent way
    Omega_k = 1.0 - Omega_c - Omega_b - Omega_v

    cosmo = ccl.Cosmology(Omega_c=Omega_c,
                          Omega_b=Omega_b,
                          Neff=Neff,
                          h=h,
                          A_s=A_s,
                          n_s=n_s,
                          Omega_k=Omega_k,
                          w0=w0,
                          wa=wa,
                          m_nu=mnu)

    # Calculate distance using pyccl
    a = 1. / (1. + z)
    chi = ccl.comoving_radial_distance(cosmo, a)
    # Compare to benchmark data
    assert_allclose(chi, chi_bench, atol=1e-12, rtol=DISTANCES_TOLERANCE_MNU)

    # compare distance moudli where a!=1
    a_not_one = (a != 1).nonzero()
    dm = ccl.distance_modulus(cosmo, a[a_not_one])

    assert_allclose(dm,
                    dm_bench[a_not_one],
                    atol=1e-3,
                    rtol=DISTANCES_TOLERANCE_MNU)
Beispiel #12
0
def compare_distances_hiz(z, chi_bench, Omega_v, w0, wa):
    """
    Compare distances calculated by pyccl with the distances in the benchmark
    file.
    This test is only valid when radiation is explicitly set to 0.
    """
    # Set Omega_K in a consistent way
    Omega_k = 1.0 - Omega_c - Omega_b - Omega_v

    cosmo = ccl.Cosmology(Omega_c=Omega_c,
                          Omega_b=Omega_b,
                          Neff=Neff,
                          h=h,
                          A_s=A_s,
                          n_s=n_s,
                          Omega_k=Omega_k,
                          w0=w0,
                          wa=wa,
                          Omega_g=0)

    # Calculate distance using pyccl
    a = 1. / (1. + z)
    chi = ccl.comoving_radial_distance(cosmo, a) * h
    # Compare to benchmark data
    assert_allclose(chi, chi_bench, atol=1e-12, rtol=DISTANCES_TOLERANCE)
Beispiel #13
0
def compare_distances(z, chi_bench, dm_bench, Omega_v, w0, wa):
    """
    Compare distances calculated by pyccl with the distances in the benchmark
    file.
    This test is only valid when radiation is explicitly set to 0.
    """
    # Set Omega_K in a consistent way
    Omega_k = 1.0 - Omega_c - Omega_b - Omega_v

    cosmo = ccl.Cosmology(Omega_c=Omega_c,
                          Omega_b=Omega_b,
                          Neff=Neff,
                          h=h,
                          A_s=A_s,
                          n_s=n_s,
                          Omega_k=Omega_k,
                          w0=w0,
                          wa=wa,
                          Omega_g=0)

    # Calculate distance using pyccl
    a = 1. / (1. + z)
    chi = ccl.comoving_radial_distance(cosmo, a) * h
    # Compare to benchmark data
    assert_allclose(chi, chi_bench, atol=1e-12, rtol=DISTANCES_TOLERANCE)

    # compare distance moudli where a!=1
    a_not_one = (a != 1).nonzero()
    dm = ccl.distance_modulus(cosmo, a[a_not_one])

    assert_allclose(dm,
                    dm_bench[a_not_one],
                    atol=1e-3,
                    rtol=DISTANCES_TOLERANCE * 10)
Beispiel #14
0
def test_power_mg(model):
    mu_0 = [0., 0.1, -0.1, 0.1, -0.1]
    sigma_0 = [0., 0.1, -0.1, -0.1, 0.1]

    cosmo = ccl.Cosmology(
        Omega_c=0.25,
        Omega_b=0.05,
        h=0.7,
        A_s=2.1e-9,
        n_s=0.96,
        Neff=3.046,
        mu_0=mu_0[model],
        sigma_0=sigma_0[model],
        Omega_k=0,
        matter_power_spectrum='linear',
        transfer_function='boltzmann_class')

    data = np.loadtxt("./benchmarks/data/model%d_pk_MG.dat" % model)

    a = 1
    k = data[:, 0] * cosmo['h']
    pk = data[:, 1] / (cosmo['h']**3)
    pk_ccl = ccl.linear_matter_power(cosmo, k, a)
    err = np.abs(pk_ccl/pk - 1)

    if model == 0:
        assert np.allclose(err, 0, rtol=0, atol=POWER_MG_TOL)
    else:
        msk = data[:, 0] > 5e-3
        assert np.allclose(err[msk], 0, rtol=0, atol=POWER_MG_TOL)
Beispiel #15
0
def compare_distances(z, chi_bench, Omega_v, w0, wa):
    """
    Compare distances calculated by pyccl with the distances in the benchmark 
    file.
    """
    # Set Omega_K in a consistent way
    Omega_k = 1.0 - Omega_c - Omega_b - Omega_n - Omega_v

    # Create new Parameters and Cosmology objects
    p = ccl.Parameters(Omega_c=Omega_c,
                       Omega_b=Omega_b,
                       Omega_n=Omega_n,
                       h=h,
                       A_s=A_s,
                       n_s=n_s,
                       Omega_k=Omega_k,
                       w0=w0,
                       wa=wa)
    p.parameters.Omega_g = 0.  # Hack to set to same value used for benchmarks
    cosmo = ccl.Cosmology(p)

    # Calculate distance using pyccl
    a = 1. / (1. + z)
    chi = ccl.comoving_radial_distance(cosmo, a) * h

    # Compare to benchmark data
    assert_allclose(chi, chi_bench, atol=1e-12, rtol=DISTANCES_TOLERANCE)
Beispiel #16
0
def test_pk2d_init():
    """
    Test initialization of Pk2D objects
    """

    cosmo = ccl.Cosmology(Omega_c=0.27,
                          Omega_b=0.045,
                          h=0.67,
                          A_s=1e-10,
                          n_s=0.96)

    # If no input
    assert_raises(ValueError, ccl.Pk2D)

    # Input function has incorrect signature
    assert_raises(ValueError, ccl.Pk2D, pkfunc=pk1d)
    ccl.Pk2D(pkfunc=lpk2d, cosmo=cosmo)

    # Input function but no cosmo
    assert_raises(ValueError, ccl.Pk2D, pkfunc=lpk2d)

    # Input arrays have incorrect sizes
    lkarr = -4. + 6 * np.arange(100) / 99.
    aarr = 0.05 + 0.95 * np.arange(100) / 99.
    pkarr = np.zeros([len(aarr), len(lkarr)])
    assert_raises(ValueError,
                  ccl.Pk2D,
                  a_arr=aarr,
                  lk_arr=lkarr,
                  pk_arr=pkarr[1:])
Beispiel #17
0
def S8z(mcmc, a, MG=False, size=None):
    p = mcmc.getParams()
    if size is None:
        size = p.A_s.size
    S8_ar = np.zeros((size, a.size))

    for i in range(size):
        cosmo = ccl.Cosmology(h=p.h[i],
                              Omega_c=p.Omega_c[i],
                              Omega_b=p.Omega_b[i],
                              A_s=1e-9 * p.A_s[i],
                              n_s=p.n_s[i],
                              w0=-1,
                              wa=0,
                              transfer_function='boltzmann_class')
        # Compute everything
        sigma8 = ccl.sigma8(cosmo)
        Dz = ccl.background.growth_factor(cosmo, a)
        Om = ccl.background.omega_x(cosmo, 1, 'matter')

        if MG:
            d1 = p.dpk1[i]
        else:
            d1 = 0

        S8_ar[i] = (1 + d1 * (1 - a)) * Dz * sigma8 * (Om / 0.3)**0.5

    return S8_ar
Beispiel #18
0
def test_power_mg(model):
    mu_0 = [0., 0.1, -0.1, 0.1, -0.1]
    sigma_0 = [0., 0.1, -0.1, -0.1, 0.1]
    h0 = 0.7
    cosmo = ccl.Cosmology(Omega_c=0.112 / h0**2,
                          Omega_b=0.0226 / h0**2,
                          h=h0,
                          A_s=2.1e-9,
                          n_s=0.96,
                          Neff=3.046,
                          mu_0=mu_0[model],
                          sigma_0=sigma_0[model],
                          Omega_k=0,
                          m_nu=0,
                          T_CMB=2.7255,
                          matter_power_spectrum='linear',
                          transfer_function='boltzmann_isitgr')

    data = np.loadtxt("./benchmarks/data/model%d_pk_MG_matterpower.dat" %
                      model)

    a = 1
    k = data[:, 0] * cosmo['h']
    pk = data[:, 1] / (cosmo['h']**3)
    pk_ccl = ccl.linear_matter_power(cosmo, k, a)
    err = np.abs(pk_ccl / pk - 1)

    # cut two points due to cosmic variance
    cut = data[:, 0] > 1e-04
    assert np.allclose(err[cut], 0, rtol=0, atol=POWER_MG_TOL)
Beispiel #19
0
def test_cosmology_output():
    """
    Check that status messages and other output from Cosmology() object works
    correctly.
    """
    # Create test cosmology object
    cosmo = ccl.Cosmology(Omega_c=0.25, Omega_b=0.05, h=0.7, A_s=2.1e-9,
                          n_s=0.96)

    # Return and print status messages
    assert_no_warnings(cosmo.status)
    assert_no_warnings(print, cosmo)

    # Test status methods for different precomputable quantities
    assert_(cosmo.has_distances is False)
    assert_(cosmo.has_growth is False)
    assert_(cosmo.has_linear_power is False)
    assert_(cosmo.has_nonlin_power is False)
    assert_(cosmo.has_sigma is False)

    # Check that quantities can be precomputed
    assert_no_warnings(cosmo.compute_distances)
    assert_no_warnings(cosmo.compute_growth)
    assert_no_warnings(cosmo.compute_linear_power)
    assert_no_warnings(cosmo.compute_nonlin_power)
    assert_no_warnings(cosmo.compute_sigma)
    assert_(cosmo.has_distances is True)
    assert_(cosmo.has_growth is True)
    assert_(cosmo.has_linear_power is True)
    assert_(cosmo.has_nonlin_power is True)
    assert_(cosmo.has_sigma is True)
Beispiel #20
0
def test_parameters_set():
    """
    Check that a Cosmology object doesn't let parameters be set.
    """
    params = ccl.Cosmology(Omega_c=0.25,
                           Omega_b=0.05,
                           h=0.7,
                           A_s=2.1e-9,
                           n_s=0.96)

    # Check that values of sigma8 and A_s won't be misinterpreted by the C code
    assert_raises(ValueError,
                  ccl.Cosmology,
                  Omega_c=0.25,
                  Omega_b=0.05,
                  h=0.7,
                  A_s=2e-5,
                  n_s=0.96)
    assert_raises(ValueError,
                  ccl.Cosmology,
                  Omega_c=0.25,
                  Omega_b=0.05,
                  h=0.7,
                  sigma8=9e-6,
                  n_s=0.96)

    # Check that error is raised when unrecognized parameter requested
    assert_raises(KeyError, lambda: params['wibble'])
Beispiel #21
0
def compare_growth(z, gfac_bench, Omega_v, w0, wa):
    """
    Compare growth factor calculated by pyccl with the values in the benchmark 
    file. This test only works if radiation is explicitly set to 0.
    """

    # Set Omega_K in a consistent way
    Omega_k = 1.0 - Omega_c - Omega_b - Omega_v

    # Create new Parameters and Cosmology objects

    p = ccl.Parameters(Omega_c=Omega_c,
                       Omega_b=Omega_b,
                       Neff=Neff,
                       m_nu=m_nu,
                       h=h,
                       A_s=A_s,
                       n_s=n_s,
                       Omega_k=Omega_k,
                       w0=w0,
                       wa=wa)

    p.parameters.Omega_g = 0.  # Hack to set to same value used for benchmarks
    cosmo = ccl.Cosmology(p)

    # Calculate distance using pyccl
    a = 1. / (1. + z)
    gfac = ccl.growth_factor_unnorm(cosmo, a)

    # Compare to benchmark data
    assert_allclose(gfac, gfac_bench, atol=1e-12, rtol=GROWTH_TOLERANCE)
Beispiel #22
0
def execute(block, data):
    # Calculate the firecrown likelihood as a module
    # This function, which isn't designed for end users,
    # is the main connection between cosmosis and firecrown.
    # CosmoSIS builds the block, and passes it to us here.
    # The block contains all the sample parameters.

    # Create CCL cosmology
    ccl_params = ['Omega_k', 'Omega_b', 'Omega_c',
                  'h', 'n_s', 'A_s', 'w0', 'wa']
    ccl_values = {p: block['params', p] for p in ccl_params}
    cosmo = pyccl.Cosmology(**ccl_values)

    # Put all the parameters in the data dictionary,
    # both CCL-related and others, like nuisance params.
    all_params = data['parameters'].keys()
    for p in all_params:
        data['parameters'][p] = block['params', p]

    # Call out to the log likelihood
    loglike, stats = firecrown.compute_loglike(cosmo=cosmo, data=data)

    # Send result back to cosmosis
    block['likelihoods', 'firecrown_like'] = loglike

    # Unless in quiet mode, print out what we have done
    if not data['cosmosis'].get("quiet", True):
        print("params = {}".format(data['parameters']))
        print(f"loglike = {loglike}\n", flush=True)

    # Signal success.  An exception anywhere above will
    # be converted to a -inf likelihood by default.
    return 0
Beispiel #23
0
def compare_class_distances(z,
                            chi_bench,
                            dm_bench,
                            Neff=3.0,
                            m_nu=0.0,
                            Omega_k=0.0,
                            w0=-1.0,
                            wa=0.0):
    """
    Compare distances calculated by pyccl with the distances in the CLASS
    benchmark file.
    """
    cosmo = ccl.Cosmology(Omega_c=Omega_c,
                          Omega_b=Omega_b,
                          Neff=Neff,
                          h=h,
                          A_s=A_s,
                          n_s=n_s,
                          Omega_k=Omega_k,
                          m_nu=m_nu,
                          w0=w0,
                          wa=wa)

    # Calculate distance using pyccl
    a = 1. / (1. + z)
    chi = ccl.comoving_radial_distance(cosmo, a)
    # Compare to benchmark data
    assert_allclose(chi, chi_bench, rtol=DISTANCES_TOLERANCE_CLASS)

    # Compare distance moudli where a!=1
    a_not_one = a != 1
    dm = ccl.distance_modulus(cosmo, a[a_not_one])
    assert_allclose(dm, dm_bench[a_not_one], rtol=DISTANCES_TOLERANCE_CLASS)
Beispiel #24
0
def compute_cls(oc,ob,h,s8,ns,w,fname_out=False) :
    #Fiducial cosmological parameters
    cosmo=ccl.Cosmology(Omega_c=oc,Omega_b=ob,h=h,sigma8=s8,n_s=ns,w0=w,
                        transfer_function='eisenstein_hu')
    print ccl.sigma8(cosmo)

    #Tracers
    tracers=[]
    for i in np.arange(nbins) :
        print i
#        tracers.append(ccl.ClTracer(cosmo,tracer_type='nc',z=zarr,n=nz_bins[i],bias=bzarr))
        tracers.append(ccl.ClTracer(cosmo,tracer_type='wl',z=zarr,n=nz_bins[i]))#,bias=bzarr))

    #Power spectra
    c_ij=np.zeros([LMAX+1,nbins,nbins])
    for i1 in np.arange(nbins) :
        for i2 in np.arange(i1,nbins) :
            print i1,i2
            if xcorr[i1,i2]<-1:#1E-6 :
                c_ij[:,i1,i2]=0
            else :
                c_ij[:,i1,i2]=ccl.angular_cl(cosmo,tracers[i1],tracers[i2],np.arange(LMAX+1))#,l_limber=100)
            if i1!=i2 :
                c_ij[:,i2,i1]=c_ij[:,i1,i2]
    if fname_out!=False :
        np.save(fname_out,c_ij)
    return c_ij
Beispiel #25
0
def compare_distances_hiz_muSig(z, chi_bench, Omega_v, w0, wa):
    """
    Compare distances calculated by pyccl with the distances in the benchmark
    file, for a ccl cosmology with mu / Sigma parameterisation of gravity.
    Nonzero mu / Sigma should NOT affect distances so we compare to the same
    benchmarks as the mu = Sigma = 0 case deliberately.
    """
    # Set Omega_K in a consistent way
    Omega_k = 1.0 - Omega_c - Omega_b - Omega_v

    # Create new Parameters and Cosmology objects
    cosmo = ccl.Cosmology(Omega_c=Omega_c,
                          Omega_b=Omega_b,
                          Neff=Neff,
                          h=h,
                          A_s=A_s,
                          n_s=n_s,
                          Omega_k=Omega_k,
                          w0=w0,
                          wa=wa,
                          mu_0=mu_0,
                          sigma_0=sigma_0,
                          Omega_g=0.)

    # Calculate distance using pyccl
    a = 1. / (1. + z)
    chi = ccl.comoving_radial_distance(cosmo, a) * h
    # Compare to benchmark data
    assert_allclose(chi, chi_bench, atol=1e-12, rtol=DISTANCES_TOLERANCE)
Beispiel #26
0
    def theory_corr(self, n_z2, xvals, lmax2, chi_max, zlo2, zhi2, cosmo_cat):
        '''compute the correlation function from limber integration over the CAMB power spectrum'''
        nz_int = self.compute_nz(n_z2)
        z_vals = np.linspace(zlo2, zhi2, 1000)
        n_vals = nz_int(z_vals)

        ns = getattr(cosmo_cat, 'n_s', 0.963)
        s8 = getattr(cosmo_cat, 'sigma8', 0.8)

        Omega_c = (cosmo_cat.Om0 - cosmo_cat.Ob0)
        Omega_b = cosmo_cat.Ob0
        h = cosmo_cat.H0.value / 100.

        cosmo_ccl = ccl.Cosmology(
            Omega_c=Omega_c, Omega_b=Omega_b, h=h, sigma8=s8, n_s=ns
        )  #, transfer_function='boltzmann_class', matter_power_spectrum='emu')

        ll = np.arange(0, 15000)
        lens1 = ccl.WeakLensingTracer(cosmo_ccl, dndz=(z_vals, n_vals))
        pp = ccl.angular_cl(cosmo_ccl, lens1, lens1, ll)

        pp3_2 = np.zeros((lmax2, 4))
        pp3_2[:, 1] = pp[:] * (ll * (ll + 1.)) / (2. * np.pi)
        cxvals = np.cos(xvals / (60.) / (180. / np.pi))
        vals = camb.correlations.cl2corr(pp3_2, cxvals)
        return xvals, vals[:, 1], vals[:, 2]
Beispiel #27
0
def test_parameters_nu(m_nu_type):
    cosmo = ccl.Cosmology(Omega_c=0.25,
                          Omega_b=0.05,
                          h=0.7,
                          A_s=2.1e-9,
                          n_s=0.96,
                          wa=0.01,
                          w0=-1,
                          Neff=3.046,
                          Omega_k=0.0,
                          m_nu=0.15,
                          m_nu_type=m_nu_type)

    if m_nu_type == 'inverted':
        assert np.allclose(cosmo['m_nu'][1]**2 - cosmo['m_nu'][0]**2,
                           ccl.physical_constants.DELTAM12_sq,
                           atol=1e-4,
                           rtol=0)
        assert np.allclose(cosmo['m_nu'][2]**2 - cosmo['m_nu'][0]**2,
                           ccl.physical_constants.DELTAM13_sq_neg,
                           atol=1e-4,
                           rtol=0)
    elif m_nu_type == 'normal':
        assert np.allclose(cosmo['m_nu'][1]**2 - cosmo['m_nu'][0]**2,
                           ccl.physical_constants.DELTAM12_sq,
                           atol=1e-4,
                           rtol=0)
        assert np.allclose(cosmo['m_nu'][2]**2 - cosmo['m_nu'][0]**2,
                           ccl.physical_constants.DELTAM13_sq_pos,
                           atol=1e-4,
                           rtol=0)
    elif m_nu_type == 'single':
        assert np.allclose(cosmo['m_nu'][0], 0.15, atol=1e-4, rtol=0)
        assert np.allclose(cosmo['m_nu'][1], 0., atol=1e-4, rtol=0)
        assert np.allclose(cosmo['m_nu'][2], 0., atol=1e-4, rtol=0)
Beispiel #28
0
def test_pk2d_cls():
    """
    Test interplay between Pk2D and the Limber integrator
    """

    cosmo = ccl.Cosmology(Omega_c=0.27,
                          Omega_b=0.045,
                          h=0.67,
                          A_s=1e-10,
                          n_s=0.96)
    z = np.linspace(0., 1., 200)
    n = np.exp(-((z - 0.5) / 0.1)**2)
    lens1 = ccl.WeakLensingTracer(cosmo, (z, n))
    ells = np.arange(2, 10)

    # Check that passing no power spectrum is fine
    cells = ccl.angular_cl(cosmo, lens1, lens1, ells)
    assert all_finite(cells)

    # Check that passing a bogus power spectrum fails as expected
    assert_raises(ValueError,
                  ccl.angular_cl,
                  cosmo,
                  lens1,
                  lens1,
                  ells,
                  p_of_k_a=1)

    # Check that passing a correct power spectrum runs as expected
    psp = ccl.Pk2D(pkfunc=lpk2d, cosmo=cosmo)
    cells = ccl.angular_cl(cosmo, lens1, lens1, ells, p_of_k_a=psp)
    assert all_finite(cells)
Beispiel #29
0
def reference_models_nu():
    """
    Create a set of reference cosmological models with massive neutrinos.
    This is separate because certain functionality is not yes implemented
    for massive neutrino cosmologies so will throw errors.
    """

    # Emulator Pk w/neutrinos list
    cosmo1 = ccl.Cosmology(Omega_c=0.27,
                           Omega_b=0.022 / 0.67**2,
                           h=0.67,
                           sigma8=0.8,
                           n_s=0.96,
                           Neff=3.04,
                           m_nu=[0.02, 0.02, 0.02],
                           transfer_function='boltzmann_class',
                           matter_power_spectrum='emu')

    # Emulator Pk with neutrinos, force equalize
    #p2 = ccl.Parameters(Omega_c=0.27, Omega_b=0.022/0.67**2, h=0.67, sigma8=0.8,
    #                    n_s=0.96, Neff=3.04, m_nu=0.11)
    #cosmo2 = ccl.Cosmology(p1, transfer_function='emulator',
    #                       matter_power_spectrum='emu', emulator_neutrinos='equalize')

    return [cosmo1]
Beispiel #30
0
def test_parameters_read_write():
    """Check that Cosmology objects can be read and written"""
    params = ccl.Cosmology(Omega_c=0.25,
                           Omega_b=0.05,
                           h=0.7,
                           A_s=2.1e-9,
                           n_s=0.96,
                           m_nu=[0.02, 0.1, 0.05],
                           m_nu_type='list',
                           z_mg=[0.0, 1.0],
                           df_mg=[0.01, 0.0])

    # Make a temporary file name
    with tempfile.NamedTemporaryFile(delete=False) as tmpfile:
        temp_file_name = tmpfile.name

    # Write out and then eead in the parameters from that file
    params.write_yaml(temp_file_name)
    params2 = ccl.Cosmology.read_yaml(temp_file_name)

    # Check the read-in params are equal to the written out ones
    assert_almost_equal(params['Omega_c'], params2['Omega_c'])
    assert_almost_equal(params['Neff'], params2['Neff'])
    assert_almost_equal(params['sum_nu_masses'], params2['sum_nu_masses'])

    # Now make a file that will be deleted so it does not exist
    # and check the right error is raise
    with tempfile.NamedTemporaryFile(delete=True) as tmpfile:
        temp_file_name = tmpfile.name

    assert_raises(IOError, ccl.Cosmology.read_yaml, filename=temp_file_name)
    assert_raises(IOError,
                  params.read_yaml,
                  filename=temp_file_name +
                  "/nonexistent_directory/params.yml")