Ejemplo n.º 1
0
def test_bcm_correct_smoke():
    k_arr = np.geomspace(1E-2, 1, 10)
    fka = ccl.bcm_model_fka(COSMO, k_arr, 0.5)
    pk_nobar = ccl.nonlin_matter_power(COSMO, k_arr, 0.5)
    ccl.bcm_correct_pk2d(COSMO, COSMO._pk_nl['delta_matter:delta_matter'])
    pk_wbar = ccl.nonlin_matter_power(COSMO, k_arr, 0.5)
    assert np.all(np.fabs(pk_wbar / (pk_nobar * fka) - 1) < 1E-5)
Ejemplo n.º 2
0
    def test_sampling_error(self):
        """
        P(k) is sampled within some finite window in the interval 
        `[kmin, kmax]`, where `kmin=2pi/L` and `kmax=2pi*sqrt(3)*(N/2)*(1/L)` 
        (for 3D FT). The lack of sampling in some regions of k-space means that 
        sigma8 can't be perfectly reconstructed (see U-L. Pen, 
        arXiv:astro-ph/9709261 for a discussion).
        
        This function calculates sigma8 from the realised box, and compares 
        this with the theoretical calculation for sigma8 over a large 
        k-window, and over a k-window of the same size as for the box.
        """

        # Calc. sigma8 from the realisation
        s8_real = self.sigma8()

        # Calc. theoretical sigma8 in same k-window as realisation
        _k = np.linspace(self.kmin, self.kmax, int(5e3))
        _pk = ccl.nonlin_matter_power(self.cosmo, k=_k, a=self.scale_factor)
        _y = _k**2. * _pk * self.window(_k, 8.0 / self.cosmo['h'])
        _y = np.nan_to_num(_y)
        s8_th_win = np.sqrt(scipy.integrate.simps(_y, _k) / (2. * np.pi**2.))

        # Calc. full sigma8 (in window that is wide enough)
        _k2 = np.logspace(-5, 2, int(5e4))
        _pk2 = ccl.nonlin_matter_power(self.cosmo, k=_k2, a=self.scale_factor)
        _y2 = _k2**2. * _pk2 * self.window(_k2, 8.0 / self.cosmo['h'])
        _y2 = np.nan_to_num(_y2)
        s8_th_full = np.sqrt(
            scipy.integrate.simps(_y2, _k2) / (2. * np.pi**2.))

        # Calculate sigma8 in real space
        dk = np.reshape(self.delta_k, np.shape(self.k))
        dk = dk * self.window1(self.k, 8.0 / self.cosmo['h'])
        dk = np.nan_to_num(dk)
        dx = fft.ifftn(dk)
        s8_realspace = np.std(dx)

        # sigma20
        dk = np.reshape(self.delta_k, np.shape(self.k))
        dk = dk * self.window1(self.k, 20.0 / self.cosmo['h'])
        dk = np.nan_to_num(dk)
        dx = fft.ifftn(dk)
        s20_realspace = np.std(dx)

        s20_real = self.sigmaR(20.)

        # Print report
        print("")
        print("sigma8 (real.): \t", s8_real)
        print("sigma8 (th.win.):\t", s8_th_win)
        print("sigma8 (th.full):\t", s8_th_full)
        print("sigma8 (realsp.):\t", s8_realspace)
        print("ratio =", 1. / (s8_real / s8_realspace))
        print("")
        print("sigma20 (real.): \t", s20_real)
        print("sigma20 (realsp.):\t", s20_realspace)
        print("ratio =", 1. / (s20_real / s20_realspace))
        print("var(delta) =", np.std(self.delta_x))
Ejemplo n.º 3
0
def test_transfer_matter_power_nu_raises(tf, pk, m_nu):
    cosmo = ccl.Cosmology(
        Omega_c=0.27, Omega_b=0.045, h=0.67, sigma8=0.8, n_s=0.96,
        transfer_function=tf, matter_power_spectrum=pk, m_nu=m_nu)

    if tf is not None:
        with pytest.warns(CCLWarning):
            ccl.linear_matter_power(cosmo, 1, 1)

    with pytest.raises(CCLError):
        ccl.nonlin_matter_power(cosmo, 1, 1)
Ejemplo n.º 4
0
def test_mu_sigma_matter_power_err(mp):
    with pytest.raises(ccl.CCLError):
        cosmo = ccl.Cosmology(Omega_c=0.25,
                              Omega_b=0.05,
                              h=0.7,
                              A_s=2.1e-9,
                              n_s=0.96,
                              mu_0=0.1,
                              sigma_0=0.2,
                              transfer_function=None,
                              matter_power_spectrum=mp)
        ccl.nonlin_matter_power(cosmo, 1, 1)
Ejemplo n.º 5
0
def test_halofit_highz(cosmo):
    vals = [(25, 75)] + list(zip(range(0, 98), range(1, 99)))
    for zl, zh in vals:
        al = 1.0 / (1 + zl)
        ah = 1.0 / (1 + zh)

        k = np.logspace(0, 2, 10)
        pkratl = (ccl.nonlin_matter_power(cosmo, k, al) /
                  ccl.linear_matter_power(cosmo, k, al))
        pkrath = (ccl.nonlin_matter_power(cosmo, k, ah) /
                  ccl.linear_matter_power(cosmo, k, ah))

        assert np.all(pkratl >= pkrath), (zl, zh, pkratl, pkrath)
Ejemplo n.º 6
0
def check_power(cosmo):
    """
    Check that power spectrum and sigma functions can be run.
    """
    # Types of scale factor
    a = 0.9
    a_arr = np.linspace(0.2, 1., 5)

    # Types of wavenumber input (scalar, list, array)
    k_scl = 1e-1
    k_lst = [1e-4, 1e-3, 1e-2, 1e-1, 1e0]
    k_arr = np.logspace(-4., 0., 5)

    # Types of smoothing scale, R
    R_scl = 8.
    R_lst = [1., 5., 10., 20., 50., 100.]
    R_arr = np.array([1., 5., 10., 20., 50., 100.])

    # linear_matter_power
    assert_(all_finite(ccl.linear_matter_power(cosmo, k_scl, a)))
    assert_(all_finite(ccl.linear_matter_power(cosmo, k_lst, a)))
    assert_(all_finite(ccl.linear_matter_power(cosmo, k_arr, a)))

    assert_raises(TypeError, ccl.linear_matter_power, cosmo, k_scl, a_arr)
    assert_raises(TypeError, ccl.linear_matter_power, cosmo, k_lst, a_arr)
    assert_raises(TypeError, ccl.linear_matter_power, cosmo, k_arr, a_arr)

    # nonlin_matter_power
    assert_(all_finite(ccl.nonlin_matter_power(cosmo, k_scl, a)))
    assert_(all_finite(ccl.nonlin_matter_power(cosmo, k_lst, a)))
    assert_(all_finite(ccl.nonlin_matter_power(cosmo, k_arr, a)))

    assert_raises(TypeError, ccl.nonlin_matter_power, cosmo, k_scl, a_arr)
    assert_raises(TypeError, ccl.nonlin_matter_power, cosmo, k_lst, a_arr)
    assert_raises(TypeError, ccl.nonlin_matter_power, cosmo, k_arr, a_arr)

    # sigmaR
    assert_(all_finite(ccl.sigmaR(cosmo, R_scl)))
    assert_(all_finite(ccl.sigmaR(cosmo, R_lst)))
    assert_(all_finite(ccl.sigmaR(cosmo, R_arr)))

    # sigmaV
    assert_(all_finite(ccl.sigmaV(cosmo, R_scl)))
    assert_(all_finite(ccl.sigmaV(cosmo, R_lst)))
    assert_(all_finite(ccl.sigmaV(cosmo, R_arr)))

    # sigma8
    assert_(all_finite(ccl.sigma8(cosmo)))
Ejemplo n.º 7
0
    def __init__(self,
                 cosmo,
                 hmc,
                 k_range=[0.1, 5],
                 nlk=128,
                 z_range=[0., 6.],
                 nz=16):

        k_arr = np.geomspace(*k_range, nlk)
        a_arr = 1 / (1 + np.linspace(*z_range, nz))
        a_arr = a_arr[::-1]

        cM = hmc.mass_def.concentration  # extract concentration from mass_def
        NFW = ccl.halos.profiles.HaloProfileNFW(c_m_relation=cM)
        pk_hm = ccl.halos.halomod_power_spectrum(cosmo,
                                                 hmc,
                                                 k_arr,
                                                 a_arr,
                                                 NFW,
                                                 normprof=True,
                                                 normprof2=True)

        pk_hf = np.array(
            [ccl.nonlin_matter_power(cosmo, k_arr, a) for a in a_arr])
        ratio = pk_hf / pk_hm

        self.rk_func = interp2d(np.log10(k_arr),
                                a_arr,
                                ratio,
                                bounds_error=False,
                                fill_value=1)
Ejemplo n.º 8
0
def calc_power_spectrum(Omega_v, w0, wa, transfer_fn, matter_power, linear,
                        raise_errors):
    """
    Calculate linear and nonlinear power spectrum for a given set of parameters 
    and choices of transfer function and matter power spectrum.
    """
    k = np.logspace(-5., 1., 300)
    a = np.logspace(np.log10(0.51), 0., 5)  # Emulator only works at z<2

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

    if (raise_errors == False):
        if (transfer_fn == 'eisenstein_hu' or transfer_fn == 'bbks'):
            mnu = 0.  # The bbks and E-H P(k) are not defined for massive neutrinos.
        elif (transfer_fn == 'emulator' and matter_power == 'emu'):
            mnu = mnu_list  # For the emulator, we must have 3 equal masses
        else:
            mnu = mnu_sum
    elif (raise_errors == True):
        if (transfer_fn == 'eisenstein_hu' or transfer_fn == 'bbks'):
            mnu = mnu_sum  #Use massive neutrinos to deliberately raise an error
        elif (transfer_fn == 'emulator' and matter_power == 'emu'):
            mnu = mnu_sum  #Use a sum instead of an equal list to deliberately raise an error.
        else:
            raise (
                ValueError,
                "Transfer function %s with matter power spectrum method %s has no case for which to test errors are raised."
                % (transfer_fn, matter_power))

    # Create new Parameters and Cosmology objects
    cosmo = ccl.Cosmology(Omega_c=Omega_c,
                          Omega_b=Omega_b,
                          h=h,
                          sigma8=sigma8,
                          n_s=n_s,
                          Omega_k=Omega_k,
                          w0=w0,
                          wa=wa,
                          transfer_function=transfer_fn,
                          matter_power_spectrum=matter_power,
                          Neff=Neff,
                          m_nu=mnu)

    # Calculate linear and nonlinear power spectra for each scale factor, a
    for _a in a:
        if linear:
            if raise_errors == False:
                pk_lin = ccl.linear_matter_power(cosmo, k, _a)
                assert_(all_finite(pk_lin))
            else:
                assert_raises(RuntimeError, ccl.linear_matter_power, cosmo, k,
                              _a)
        else:
            if raise_errors == False:
                pk_nl = ccl.nonlin_matter_power(cosmo, k, _a)
                assert_(all_finite(pk_nl))
            else:
                assert_raises(RuntimeError, ccl.nonlin_matter_power, cosmo, k,
                              _a)
Ejemplo n.º 9
0
def test_nonlin_matter_power_halomod(k):
    a = 0.8
    pk = ccl.nonlin_matter_power(COSMO_HM, k, a)

    # New implementation
    mdef = ccl.halos.MassDef('vir', 'matter')
    hmf = ccl.halos.MassFuncSheth99(COSMO_HM,
                                    mdef,
                                    mass_def_strict=False,
                                    use_delta_c_fit=True)
    hbf = ccl.halos.HaloBiasSheth99(COSMO_HM,
                                    mass_def=mdef,
                                    mass_def_strict=False)
    cc = ccl.halos.ConcentrationDuffy08(mdef)
    prf = ccl.halos.HaloProfileNFW(cc)
    hmc = ccl.halos.HMCalculator(COSMO_HM, hmf, hbf, mdef)
    pkb = ccl.halos.halomod_power_spectrum(COSMO_HM,
                                           hmc,
                                           k,
                                           a,
                                           prf,
                                           normprof1=True)

    assert np.allclose(pk, pkb)
    assert np.all(np.isfinite(pk))
    assert np.shape(pk) == np.shape(k)
Ejemplo n.º 10
0
def test_power_nu(model):
    mnu = [[0.04, 0., 0.], [0.05, 0.01, 0.], [0.03, 0.02, 0.04]]
    w_0 = [-1.0, -0.9, -0.9]
    w_a = [0.0, 0.0, 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,
                          Omega_k=0,
                          w0=w_0[model],
                          wa=w_a[model],
                          m_nu=mnu[model],
                          m_nu_type='list',
                          transfer_function='boltzmann_class')

    a = 1

    data_lin = np.loadtxt("./benchmarks/data/model%d_pk_nu.txt" % (model + 1))
    k_lin = data_lin[:, 0] * cosmo['h']
    pk_lin = data_lin[:, 1] / (cosmo['h']**3)
    pk_lin_ccl = ccl.linear_matter_power(cosmo, k_lin, a)
    err = np.abs(pk_lin_ccl / pk_lin - 1)
    assert np.allclose(err, 0, rtol=0, atol=POWER_NU_TOL)

    data_nl = np.loadtxt("./benchmarks/data/model%d_pk_nl_nu.txt" %
                         (model + 1))
    k_nl = data_nl[:, 0] * cosmo['h']
    pk_nl = data_nl[:, 1] / (cosmo['h']**3)
    pk_nl_ccl = ccl.nonlin_matter_power(cosmo, k_nl, a)
    err = np.abs(pk_nl_ccl / pk_nl - 1)
    assert np.allclose(err, 0, rtol=0, atol=POWER_NU_TOL)
Ejemplo n.º 11
0
def test_halomod_f2d_copy():
    mdef = ccl.halos.MassDef('vir', 'matter')
    hmf = ccl.halos.MassFuncSheth99(COSMO_HM, mdef,
                                    mass_def_strict=False,
                                    use_delta_c_fit=True)
    hbf = ccl.halos.HaloBiasSheth99(COSMO_HM, mass_def=mdef,
                                    mass_def_strict=False)
    cc = ccl.halos.ConcentrationDuffy08(mdef)
    prf = ccl.halos.HaloProfileNFW(cc)
    hmc = ccl.halos.HMCalculator(COSMO_HM, hmf, hbf, mdef)
    pk2d = ccl.halos.halomod_Pk2D(COSMO_HM, hmc, prf, normprof1=True)
    psp_new = pk2d.psp
    # This just triggers the internal calculation
    pk_old = ccl.nonlin_matter_power(COSMO_HM, 1., 0.8)
    pk_new = pk2d.eval(1., 0.8, COSMO_HM)
    psp_old = COSMO_HM.cosmo.data.p_nl
    assert psp_new.lkmin == psp_old.lkmin
    assert psp_new.lkmax == psp_old.lkmax
    assert psp_new.amin == psp_old.amin
    assert psp_new.amax == psp_old.amax
    assert psp_new.is_factorizable == psp_old.is_factorizable
    assert psp_new.is_k_constant == psp_old.is_k_constant
    assert psp_new.is_a_constant == psp_old.is_a_constant
    assert psp_new.is_log == psp_old.is_log
    assert psp_new.growth_factor_0 == psp_old.growth_factor_0
    assert psp_new.growth_exponent == psp_old.growth_exponent
    assert psp_new.extrap_order_lok == psp_old.extrap_order_lok
    assert psp_new.extrap_order_hik == psp_old.extrap_order_hik
    assert pk_old == pk_new
Ejemplo n.º 12
0
def test_emu(model):
    model_numbers = [1, 3, 5, 6, 8, 10]
    data = np.loadtxt("./benchmarks/data/emu_smooth_pk_M%d.txt" %
                      model_numbers[model])

    cosmos = np.loadtxt("./benchmarks/data/emu_cosmologies.txt")

    cosmo = ccl.Cosmology(
        Omega_c=cosmos[model, 0],
        Omega_b=cosmos[model, 1],
        h=cosmos[model, 2],
        sigma8=cosmos[model, 3],
        n_s=cosmos[model, 4],
        w0=cosmos[model, 5],
        wa=cosmos[model, 6],
        Neff=3.04,
        Omega_g=0,
        Omega_k=0,
        transfer_function='bbks',
        matter_power_spectrum='emu',
    )

    a = 1
    k = data[:, 0]
    pk = ccl.nonlin_matter_power(cosmo, k, a)
    err = np.abs(pk / data[:, 1] - 1)
    assert np.allclose(err, 0, rtol=0, atol=EMU_TOLERANCE)
Ejemplo n.º 13
0
def test_emu_nu(model):
    model_numbers = [38, 39, 40, 42]
    data = np.loadtxt("./benchmarks/data/emu_nu_smooth_pk_M%d.txt" %
                      model_numbers[model])

    cosmos = np.loadtxt("./benchmarks/data/emu_nu_cosmologies.txt")

    mnu = ccl.nu_masses(cosmos[model, 7] * cosmos[model, 2]**2,
                        'equal',
                        T_CMB=2.725)

    cosmo = ccl.Cosmology(
        Omega_c=cosmos[model, 0],
        Omega_b=cosmos[model, 1],
        h=cosmos[model, 2],
        sigma8=cosmos[model, 3],
        n_s=cosmos[model, 4],
        w0=cosmos[model, 5],
        wa=cosmos[model, 6],
        m_nu=mnu,
        m_nu_type='list',
        Neff=3.04,
        Omega_g=0,
        Omega_k=0,
        transfer_function='boltzmann_class',
        matter_power_spectrum='emu',
    )

    a = 1
    k = data[:, 0]
    pk = ccl.nonlin_matter_power(cosmo, k, a)
    err = np.abs(pk / data[:, 1] - 1)
    assert np.allclose(err, 0, rtol=0, atol=EMU_TOLERANCE)
Ejemplo n.º 14
0
def test_nonlin_camb_power_with_sigma8():
    Omega_c = 0.25
    Omega_b = 0.05
    n_s = 0.97
    h = 0.7

    ccl_cosmo = ccl.Cosmology(Omega_c=Omega_c, Omega_b=Omega_b, h=h, m_nu=0.0,
                              sigma8=0.8, n_s=n_s,
                              transfer_function="boltzmann_camb",
                              matter_power_spectrum="camb")

    k = np.logspace(-3, 1, 10)

    # Check that non-linear power spectrum isn't being used with sigma8
    with assert_raises(ccl.errors.CCLError):
        ccl.nonlin_matter_power(ccl_cosmo, k, 1.0)
Ejemplo n.º 15
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
Ejemplo n.º 16
0
def compute_covmat_cv(cosmo, zm, dndz):
    # Area COSMOS
    area_deg2 = 1.7
    area_rad2 = area_deg2 * (np.pi / 180)**2
    theta_rad = np.sqrt(area_rad2 / np.pi)
    # TODO: Where do we get the area

    # Bin widths
    dz = np.mean(zm[1:] - zm[:-1])
    # Number of galaxies in each bin
    dn = dndz * dz
    # z bin edges
    zb = np.append((zm - dz / 2.), zm[-1] + dz / 2.)

    # Comoving distance to bin edges
    chis = ccl.comoving_radial_distance(cosmo, 1. / (1 + zb))
    # Mean comoving distance in each bin
    chi_m = 0.5 * (chis[1:] + chis[:-1])
    # Comoving distance width
    dchi = chis[1:] - chis[:-1]
    # Disc radii
    R_m = theta_rad * chi_m
    # Galaxy bias
    b_m = 0.95 / ccl.growth_factor(cosmo, 1. / (1 + zm))
    # Growth rate (for RSDs)
    f_m = ccl.growth_rate(cosmo, 1. / (1 + zm))
    # Transverse k bins
    n_kt = 512
    # Parallel k bins
    n_kp = 512

    plt.plot(zm, dn, 'b-')
    plt.savefig('N_z.png')
    plt.close()

    # Transverse modes
    kt_arr = np.geomspace(0.00005, 10., n_kt)
    # Parallel modes
    kp_arr = np.geomspace(0.00005, 10., n_kp)
    # Total wavenumber
    k_arr = np.sqrt(kt_arr[None, :]**2 + kp_arr[:, None]**2)
    # B.H. changed a to float(a)
    pk_arr = np.array([(b+f*kp_arr[:,None]**2/k_arr**2)**2*
                     ccl.nonlin_matter_power(cosmo,k_arr.flatten(),float(a)).reshape([n_kp,n_kt])\
                     for a,b,f in zip(1./(1+zm),b_m,f_m)])


    window = np.array([2*jv(1,kt_arr[None,:]*R)/(kt_arr[None,:]*R)*np.sin(0.5*kp_arr[:,None]*dc)/\
                     (0.5*kp_arr[:,None]*dc) for R,dc in zip(R_m,dchi)])

    # Estimating covariance matrix
    # avoiding getting 0s in covariance
    eps = 0.0
    # Changed from dn to dndz B.H. and A.S. TODO: Check
    print("covmat_cv...")
    covmat_cv  =  np.array([[(ni+eps)*(nj+eps)*covar(i,j,window,pk_arr,chi_m,kp_arr,kt_arr) \
                             for i,ni in enumerate(dndz)] \
                            for j,nj in enumerate(dndz)])
    return covmat_cv
Ejemplo n.º 17
0
def test_bcm():
    cosmo = ccl.Cosmology(Omega_c=0.25,
                          Omega_b=0.05,
                          h=0.7,
                          A_s=2.2e-9,
                          n_s=0.96,
                          Neff=3.046,
                          m_nu_type='normal',
                          m_nu=0.0,
                          Omega_g=0,
                          Omega_k=0,
                          w0=-1,
                          wa=0,
                          bcm_log10Mc=14.0,
                          baryons_power_spectrum='bcm')

    cosmo_nobar = ccl.Cosmology(Omega_c=0.25,
                                Omega_b=0.05,
                                h=0.7,
                                A_s=2.2e-9,
                                n_s=0.96,
                                Neff=3.046,
                                m_nu_type='normal',
                                m_nu=0.0,
                                Omega_g=0,
                                Omega_k=0,
                                w0=-1,
                                wa=0)

    data = np.loadtxt("./benchmarks/data/w_baryonspk_nl.dat")
    data_nobar = np.loadtxt("./benchmarks/data/wo_baryonspk_nl.dat")

    k = data[:, 0] * cosmo['h']
    a = 1

    fbcm = ccl.bcm_model_fka(cosmo, k, a)
    err = np.abs(data[:, 1] / data_nobar[:, 1] / fbcm - 1)
    assert np.allclose(err, 0, atol=BCM_TOLERANCE, rtol=0)

    ratio = (ccl.nonlin_matter_power(cosmo, k, a) /
             ccl.nonlin_matter_power(cosmo_nobar, k, a))
    err = np.abs(data[:, 1] / data_nobar[:, 1] / ratio - 1)
    assert np.allclose(err, 0, atol=BCM_TOLERANCE, rtol=0)
Ejemplo n.º 18
0
    def __init__(self, cosmo, hmc, pM, k_range=[1E-1, 5], nlk=20, z_range=[0., 1.], nz=16):

        lkarr = np.linspace(np.log10(k_range[0]), np.log10(k_range[1]), nlk)
        karr = 10.**lkarr
        zarr = np.linspace(z_range[0], z_range[1], nz)
        aarr = 1./(1. + zarr)

        pk_hm = ccl.halos.halomod_power_spectrum(cosmo, hmc, karr, aarr, pM, normprof1=True)
        pk_hf = np.array([ccl.nonlin_matter_power(cosmo, karr, a) for a in aarr])
        ratio = pk_hf / pk_hm

        self.rk_func = interpolate.interp2d(lkarr, zarr, ratio, bounds_error=False, fill_value=1)
Ejemplo n.º 19
0
 def theoretical_power_spectrum(self):
     """
     Calculate the theoretical nonlinear power spectrum for the given 
     cosmological parameters, using CCL. Does not depend on the realisation.
     
     Returns:
         k, pk (array_like):
             Wavenumbers, from 10^-3.5 to 10^1, in Mpc^-1, and the 
             theoretical nonlinear power spectrum, in (Mpc)^3.
     """
     k = np.logspace(-3.5, 1., int(1e3))
     pk = ccl.nonlin_matter_power(self.cosmo, k=k, a=self.scale_factor)
     return k, pk
Ejemplo n.º 20
0
def test_nonlin_camb_power():
    import camb

    logT_AGN = 7.93
    Omega_c = 0.25
    Omega_b = 0.05
    A_s = 2.1e-9
    n_s = 0.97
    h = 0.7
    # Needs to be set for good agreements between CCL and CAMB
    T_CMB = 2.725

    p = camb.CAMBparams(WantTransfer=True,
                        NonLinearModel=camb.nonlinear.Halofit(
                            halofit_version="mead2020_feedback",
                            HMCode_logT_AGN=logT_AGN))
    # This affects k_min
    p.WantCls = False
    p.DoLensing = False
    p.Want_CMB = False
    p.Want_CMB_lensing = False
    p.Want_cl_2D_array = False
    p.set_cosmology(H0=h*100, omch2=Omega_c*h**2, ombh2=Omega_b*h**2,
                    mnu=0.0, TCMB=T_CMB)
    p.share_delta_neff = False
    p.InitPower.set_params(As=A_s, ns=n_s)

    z = [0.0, 0.5, 1.0, 1.5]
    p.set_matter_power(redshifts=z, kmax=10.0, nonlinear=True)
    p.set_for_lmax(5000)

    r = camb.get_results(p)

    k, z, pk_nonlin_camb = r.get_nonlinear_matter_power_spectrum(
        hubble_units=False, k_hunit=False)

    ccl_cosmo = ccl.Cosmology(
        Omega_c=Omega_c, Omega_b=Omega_b, h=h, m_nu=0.0,
        A_s=A_s, n_s=n_s,
        transfer_function="boltzmann_camb",
        matter_power_spectrum="camb",
        extra_parameters={"camb": {"halofit_version": "mead2020_feedback",
                                   "HMCode_logT_AGN": logT_AGN}})

    for z_, pk_camb in zip(z, pk_nonlin_camb):
        pk_nonlin_ccl = ccl.nonlin_matter_power(ccl_cosmo, k, 1/(1+z_))

        assert np.allclose(pk_camb, pk_nonlin_ccl, rtol=3e-5)
Ejemplo n.º 21
0
def test_iswcl():
    # Cosmology
    Ob = 0.05
    Oc = 0.25
    h = 0.7
    COSMO = ccl.Cosmology(Omega_b=Ob,
                          Omega_c=Oc,
                          h=h,
                          n_s=0.96,
                          sigma8=0.8,
                          transfer_function='bbks')

    # CCL calculation
    ls = np.arange(2, 100)
    zs = np.linspace(0, 0.6, 256)
    nz = np.exp(-0.5 * ((zs - 0.3) / 0.05)**2)
    bz = np.ones_like(zs)
    tr_n = ccl.NumberCountsTracer(COSMO,
                                  has_rsd=False,
                                  dndz=(zs, nz),
                                  bias=(zs, bz))
    tr_i = ccl.ISWTracer(COSMO)
    cl = ccl.angular_cl(COSMO, tr_n, tr_i, ls)

    # Benchmark from Eq. 6 in 1710.03238
    pz = nz / simps(nz, x=zs)
    H0 = h / ccl.physical_constants.CLIGHT_HMPC
    # Prefactor
    prefac = 3 * COSMO['T_CMB'] * (Oc + Ob) * H0**3 / (ls + 0.5)**2
    # H(z)/H0
    ez = ccl.h_over_h0(COSMO, 1. / (1 + zs))
    # Linear growth and derivative
    dz = ccl.growth_factor(COSMO, 1. / (1 + zs))
    gz = np.gradient(dz * (1 + zs), zs[1] - zs[0]) / dz
    # Comoving distance
    chi = ccl.comoving_radial_distance(COSMO, 1 / (1 + zs))
    # P(k)
    pks = np.array([
        ccl.nonlin_matter_power(COSMO, (ls + 0.5) / (c + 1E-6), 1. / (1 + z))
        for c, z in zip(chi, zs)
    ]).T
    # Limber integral
    cl_int = pks[:, :] * (pz * ez * gz)[None, :]
    clbb = simps(cl_int, x=zs)
    clbb *= prefac

    assert np.all(np.fabs(cl / clbb - 1) < 1E-3)
Ejemplo n.º 22
0
    def __init__(self,
                 cosmo,
                 k_range=[1E-1, 5],
                 nlk=128,
                 z_range=[0., 1.],
                 nz=32):
        lkarr = np.linspace(np.log10(k_range[0]), np.log10(k_range[1]), nlk)
        karr = 10.**lkarr
        zarr = np.linspace(z_range[0], z_range[1], nz)
        a_arr = 1 / (1 + zarr)

        hmd = ccl.halos.MassDef(500, "critical")
        cM = ccl.halos.ConcentrationDuffy08(mass_def=hmd)
        NFW = ccl.halos.profiles.HaloProfileNFW(c_m_relation=cM)

        kwargs = {
            "mass_function": ccl.halos.mass_function_from_name("Tinker08"),
            "halo_bias": ccl.halos.halo_bias_from_name("Tinker10")
        }
        nM = kwargs["mass_function"](cosmo, mass_def=hmd)
        bM = kwargs["halo_bias"](cosmo, mass_def=hmd)
        hmc = ccl.halos.HMCalculator(mass_function=nM,
                                     halo_bias=bM,
                                     mass_def=hmd)

        pk_hm = ccl.halos.halomod_power_spectrum(cosmo,
                                                 hmc,
                                                 karr,
                                                 a_arr,
                                                 NFW,
                                                 normprof=True,
                                                 normprof2=True)

        pk_hf = np.array(
            [ccl.nonlin_matter_power(cosmo, karr, a) for a in a_arr])

        ratio = pk_hf / pk_hm

        self.rk_func = interp2d(lkarr,
                                1 / (1 + zarr),
                                ratio,
                                bounds_error=False,
                                fill_value=1)
Ejemplo n.º 23
0
def test_power_nu(model):
    mnu = [[0.04, 0., 0.], [0.05, 0.01, 0.], [0.03, 0.02, 0.04]]
    w_0 = [-1.0, -0.9, -0.9]
    w_a = [0.0, 0.0, 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,
                          Omega_k=0,
                          w0=w_0[model],
                          wa=w_a[model],
                          m_nu=mnu[model],
                          m_nu_type='list',
                          transfer_function='boltzmann_class')

    a = 1

    data_lin = np.loadtxt("./benchmarks/data/model%d_pk_nu.txt" % (model + 1))
    k_lin = data_lin[:, 0] * cosmo['h']
    pk_lin = data_lin[:, 1] / (cosmo['h']**3)

    with warnings.catch_warnings():
        # Linear power with massive neutrinos raises a warning.
        # Ignore it.
        # XXX: Do you really want to be raising a warning for this?
        #      This seems spurious to me.  (MJ)
        warnings.simplefilter("ignore")
        pk_lin_ccl = ccl.linear_matter_power(cosmo, k_lin, a)

    err = np.abs(pk_lin_ccl / pk_lin - 1)
    assert np.allclose(err, 0, rtol=0, atol=POWER_NU_TOL)

    data_nl = np.loadtxt("./benchmarks/data/model%d_pk_nl_nu.txt" %
                         (model + 1))
    k_nl = data_nl[:, 0] * cosmo['h']
    pk_nl = data_nl[:, 1] / (cosmo['h']**3)
    pk_nl_ccl = ccl.nonlin_matter_power(cosmo, k_nl, a)
    err = np.abs(pk_nl_ccl / pk_nl - 1)
    assert np.allclose(err, 0, rtol=0, atol=POWER_NU_TOL)
Ejemplo n.º 24
0
def test_emu_lin(model):
    cosmos = np.loadtxt("./benchmarks/data/emu_input_cosmologies.txt")

    mnu = ccl.nu_masses(cosmos[model, 7] * cosmos[model, 2]**2,
                        'equal',
                        T_CMB=2.725)

    cosmo = ccl.Cosmology(
        Omega_c=cosmos[model, 0],
        Omega_b=cosmos[model, 1],
        h=cosmos[model, 2],
        sigma8=cosmos[model, 3],
        n_s=cosmos[model, 4],
        w0=cosmos[model, 5],
        wa=cosmos[model, 6],
        m_nu=mnu,
        m_nu_type='list',
        Neff=3.04,
        Omega_g=0,
        Omega_k=0,
        transfer_function='boltzmann_camb',
        matter_power_spectrum='emu',
    )

    a = 1
    k = np.logspace(-3, -2, 50)

    # Catch warning about neutrino linear growth
    if (np.sum(mnu) > 0):
        pk = ccl.pyutils.assert_warns(ccl.CCLWarning, ccl.nonlin_matter_power,
                                      cosmo, k, a)
    else:
        pk = ccl.nonlin_matter_power(cosmo, k, a)

    # Catch warning about linear matter power
    pk_lin = ccl.pyutils.assert_warns(ccl.CCLWarning, ccl.linear_matter_power,
                                      cosmo, k, a)

    err = np.abs(pk / pk_lin - 1)
    assert np.allclose(err, 0, rtol=0, atol=EMU_TOLERANCE)
Ejemplo n.º 25
0
def test_nonlin_camb_power():
    import camb

    logT_AGN = 7.93
    Omega_c = 0.25
    Omega_b = 0.05
    A_s = 2.1e-9
    n_s = 0.97
    h = 0.7

    p = camb.CAMBparams(WantTransfer=True,
                        NonLinearModel=camb.nonlinear.Halofit(
                            halofit_version="mead2020",
                            HMCode_logT_AGN=logT_AGN))
    p.set_cosmology(H0=h*100, omch2=Omega_c*h**2, ombh2=Omega_b*h**2, mnu=0.0)
    p.share_delta_neff = False
    p.InitPower.set_params(As=A_s, ns=n_s)

    z = [0.0, 0.5, 1.0]
    p.set_matter_power(redshifts=z, kmax=10.0, nonlinear=True)
    p.set_for_lmax(5000)

    r = camb.get_results(p)

    k, z, pk_nonlin_camb = r.get_nonlinear_matter_power_spectrum(
        hubble_units=False, k_hunit=False)

    ccl_cosmo = ccl.Cosmology(Omega_c=Omega_c, Omega_b=Omega_b, h=h, m_nu=0.0,
                              A_s=A_s, n_s=n_s,
                              transfer_function="boltzmann_camb",
                              matter_power_spectrum="camb",
                              extra_parameters={"camb":
                                                {"halofit_version": "mead2020",
                                                 "HMCode_logT_AGN": logT_AGN}})

    for z_, pk_camb in zip(z, pk_nonlin_camb):
        pk_nonlin_ccl = ccl.nonlin_matter_power(ccl_cosmo, k, 1/(1+z_))

        assert np.allclose(pk_camb, pk_nonlin_ccl, rtol=3e-3)
Ejemplo n.º 26
0
def test_halofit():
    # We first define equivalent CCL and jax_cosmo cosmologies
    cosmo_ccl = ccl.Cosmology(
        Omega_c=0.3,
        Omega_b=0.05,
        h=0.7,
        sigma8=0.8,
        n_s=0.96,
        Neff=0,
        transfer_function="eisenstein_hu",
        matter_power_spectrum="halofit",
    )

    cosmo_jax = Cosmology(
        Omega_c=0.3,
        Omega_b=0.05,
        h=0.7,
        sigma8=0.8,
        n_s=0.96,
        Omega_k=0.0,
        w0=-1.0,
        wa=0.0,
    )

    # Test array of scales
    k = np.logspace(-4, 2, 512)

    # Computing matter power spectrum
    pk_ccl = ccl.nonlin_matter_power(cosmo_ccl, k, 1.0)
    pk_jax = (power.nonlinear_matter_power(
        cosmo_jax,
        k / cosmo_jax.h,
        a=1.0,
        transfer_fn=tklib.Eisenstein_Hu,
        nonlinear_fn=power.halofit,
    ) / cosmo_jax.h**3)

    assert_allclose(pk_ccl, pk_jax, rtol=0.5e-2)
Ejemplo n.º 27
0
    def __init__(self,
                 cosmo,
                 k_range=[1E-1, 5],
                 nlk=20,
                 z_range=[0., 1.],
                 nz=16):

        lkarr = np.linspace(np.log10(k_range[0]), np.log10(k_range[1]), nlk)
        karr = 10.**lkarr
        zarr = np.linspace(z_range[0], z_range[1], nz)

        pk_hm = np.array([
            ccl.halomodel_matter_power(cosmo, karr, a) for a in 1. / (1 + zarr)
        ])
        pk_hf = np.array(
            [ccl.nonlin_matter_power(cosmo, karr, a) for a in 1. / (1 + zarr)])
        ratio = pk_hf / pk_hm

        self.rk_func = interpolate.interp2d(lkarr,
                                            zarr,
                                            ratio,
                                            bounds_error=False,
                                            fill_value=1)
Ejemplo n.º 28
0
# for a given redshift
for combo in template_comb_names:
    Pk_a = np.zeros((len(z_templates), len(ks)))
    for i in range(len(z_templates)):
        z_str = 'ztmp%d' % i
        a_arr[i] = 1. / (1 + z_templates[z_str])
        key = z_str + '_' + combo
        Pk = fid_dPk_Pk_templates[key] + \
            fid_dPk_Pk_templates[key+'_'+'omega_b'] * (omega_b - fid_deriv_params['omega_b']) + \
            fid_dPk_Pk_templates[key+'_'+'omega_cdm'] * (omega_cdm - fid_deriv_params['omega_cdm']) + \
            fid_dPk_Pk_templates[key+'_'+'n_s'] * (n_s - fid_deriv_params['n_s']) + \
            fid_dPk_Pk_templates[key+'_'+'sigma8_cb'] * (sigma8_cb - fid_deriv_params['sigma8_cb'])

        # tuks
        pk_a[i, :] = ccl.nonlin_matter_power(cosmo_ccl,
                                             ks * h,
                                             a=1. / (1 + z_templates[z_str]))

        if want_rat:
            Pk *= ccl.nonlin_matter_power(
                cosmo_ccl, ks * h, a=1. / (1 + z_templates[z_str])) * h**3
        # convert to Mpc^3 rather than [Mpc/h]^3
        Pk_a[i, :] = Pk / h**3.
    Pk_a_ij[combo] = Pk_a
# convert to Mpc^-1 rather than h/Mpc
Pk_a_ij['lk_arr'] = np.log(ks * h)

# tuks
pk_a *= 1.41
pk_tmp = ccl.Pk2D(a_arr=a_arr,
                  lk_arr=np.log(ks * h),
Ejemplo n.º 29
0
def test_no_sys_pipeline(plot=True):
    param_dict = {
        "cosmological_parameters": {
            "omch2": 0.1,
            "ombh2": 0.022,
            "h0": 0.7,
            "n_s": 0.96,
            "ln_1e10_A_s": 3.0,
            "omega_k": 0.0,
            "w": -1.0,
            "mnu": 0.06
        },
        "halo_model_parameters": {
            "A": 2.0,
        }
    }

    pipeline_ini = cosmosis.runtime.config.Inifile(PIPELINE_FILE)
    values_ini = cosmosis.runtime.config.Inifile(None)
    values_ini.read_dict(param_dict)

    pipeline = cosmosis.runtime.pipeline.LikelihoodPipeline(pipeline_ini,
                                                            values=values_ini)

    data = pipeline.run_parameters([])

    ccl_cosmo = ccl.Cosmology(
        Omega_c=data["cosmological_parameters", "omega_c"],
        Omega_b=data["cosmological_parameters", "omega_b"],
        Omega_k=data["cosmological_parameters", "omega_k"],
        h=data["cosmological_parameters", "h0"],
        n_s=data["cosmological_parameters", "n_s"],
        A_s=data["cosmological_parameters", "a_s"],
        Neff=data["cosmological_parameters", "n_eff"],
        m_nu=data["cosmological_parameters", "mnu"],
        w0=data["cosmological_parameters", "w"],
    )

    print("Loading n(z) and creating CCL tracers.")
    nofz_files = pipeline_ini.get("load_nz", "filepath").split(" ")
    tracers = []
    for nofz_file in nofz_files:
        z, nofz = np.loadtxt(nofz_file, unpack=True)
        z += (z[1] - z[0]) / 2
        tracers.append(ccl.WeakLensingTracer(cosmo=ccl_cosmo, dndz=(z, nofz)))
    n_tomo_bin = len(tracers)

    print("Comparing P(k) at z=0")
    h = data["cosmological_parameters", "h0"]
    k_lin = data["matter_power_lin", "k_h"]
    k_nl = data["matter_power_nl", "k_h"]
    pk_lin_ccl = ccl.linear_matter_power(ccl_cosmo, k_lin * h, 1.0) * h**3
    pk_nl_ccl = ccl.nonlin_matter_power(ccl_cosmo, k_nl * h, 1.0) * h**3

    frac_diff_pk_lin = data["matter_power_lin", "p_k"][0] / pk_lin_ccl - 1
    frac_diff_pk_nl = data["matter_power_nl", "p_k"][0] / pk_nl_ccl - 1
    print(
        f"Maximum fractional difference in linear P(k) at z=0 for k<5 h/Mpc: {max(np.abs(frac_diff_pk_lin[k_lin < 5.0]))}"
    )
    print(
        f"Maximum fractional difference in non-linear P(k) at z=0 for k<5 h/Mpc: {max(np.abs(frac_diff_pk_nl[k_nl < 5.0]))}"
    )

    ell = data["shear_cl", "ell"]
    print(ell.min(), ell.max(), len(ell))

    print("Setting up MontePython now.")

    import subprocess

    statistics_mp = {}
    for idx, likelihood in enumerate(["K1K_COSEBIs", "K1K_BandPowers"]):

        set_up_MontePython(likelihood)

        # we need to set some paths...
        path_to_param_file = os.path.join(
            "montepython/",
            "{:}/INPUT/{:}_Benchmark.param".format(likelihood, likelihood[4:]))

        path_to_mp_output = os.path.join(PATH_TO_MP_OUTPUT, likelihood)
        # TODO: unfortunately, MP saves out theory vectors and Cls to folder
        # from which it reads in its data and NOT to the MCMC output folder...
        path_to_mp_input = os.path.join(PATH_TO_MP_DATA[likelihood])

        # the call to MontePython:
        cmd = "python {:} run -p {:} -o {:} --conf {:} -N 1".format(
            os.path.join(PATH_TO_MONTEPYTHON, "montepython/MontePython.py"),
            path_to_param_file, path_to_mp_output,
            os.path.join(PATH_TO_MONTEPYTHON, "default.conf"))
        subprocess.call(cmd, shell=True)

        # we only need the Cls from one MP likelihood:
        if idx == 0:
            print("Loading and re-ordering Cls from MP.")

            fname = os.path.join(path_to_mp_input, 'Cls_tot.txt')
            data_mp = np.loadtxt(fname)
            mp_cl_raw = data_mp[:, 1:]
            # bring raw Cls from MP into same sorting order:
            mp_cl_my_sorting = {}
            idx_unique = 0
            for i in range(n_tomo_bin):
                mp_cl_my_sorting[i] = {}
                for j in range(i, n_tomo_bin):
                    #print(f"Bin {i+1}-{j+1}")
                    mp_cl_my_sorting[i][j] = mp_cl_raw[:, idx_unique]
                    idx_unique += 1

            mp_cl = {}
            for i in range(n_tomo_bin):
                mp_cl[i] = {}
                for j in range(i + 1):
                    print(f"Bin {i+1}-{j+1} = Bin {j+1}-{i+1}")
                    try:
                        mp_cl[i][j] = mp_cl_my_sorting[j][i]
                    except:
                        mp_cl[i][j] = mp_cl_my_sorting[i][j]

        fname = os.path.join(path_to_mp_input,
                             "{:}_theory.ascii".format(likelihood[4:]))
        print("Loaded theory vector from MontePython' {:} from: \n {:} \n".
              format(likelihood, fname))
        statistics_mp[likelihood] = np.loadtxt(fname)
        print(statistics_mp)
        print(statistics_mp["K1K_COSEBIs"])

    theta = data["shear_xi_plus", "theta"] * 180 / pi
    print("Running CCL for Cls and xis.")
    ccl_cl = {}
    ccl_xi = {}
    for i in range(n_tomo_bin):
        ccl_cl[i] = {}
        ccl_xi[i] = {}
        for j in range(i + 1):
            print(f"Bin {i+1}-{j+1}")
            ccl_cl[i][j] = ccl.angular_cl(cosmo=ccl_cosmo,
                                          cltracer1=tracers[i],
                                          cltracer2=tracers[j],
                                          ell=ell)

            ell_for_xi = np.concatenate(
                (np.arange(2, 100,
                           dtype=float), np.logspace(2, np.log10(ell[-1]),
                                                     300)))
            cl_for_xi = ccl.angular_cl(cosmo=ccl_cosmo,
                                       cltracer1=tracers[i],
                                       cltracer2=tracers[j],
                                       ell=ell_for_xi)
            cl_for_xi /= ((ell_for_xi - 1) * ell_for_xi * (ell_for_xi + 1) *
                          (ell_for_xi + 2) / (ell_for_xi + 1 / 2)**4)
            xip = ccl.correlation(cosmo=ccl_cosmo,
                                  ell=ell_for_xi,
                                  C_ell=cl_for_xi,
                                  theta=theta,
                                  corr_type="L+")
            xim = ccl.correlation(cosmo=ccl_cosmo,
                                  ell=ell_for_xi,
                                  C_ell=cl_for_xi,
                                  theta=theta,
                                  corr_type="L-")
            ccl_xi[i][j] = xip, xim

    ell_range = 10, 10000
    theta_range = 0.05, 10.0
    ell_mask = (ell_range[0] < ell) & (ell < ell_range[1])
    theta_mask = (theta_range[0] < theta) & (theta < theta_range[1])
    for i in range(n_tomo_bin):
        for j in range(i + 1):
            frac_diff_cl_KCAP_CCL = data["shear_cl",
                                         f"bin_{i+1}_{j+1}"] / ccl_cl[i][j] - 1
            frac_diff_cl_KCAP_MP = data["shear_cl",
                                        f"bin_{i+1}_{j+1}"] / mp_cl[i][j] - 1
            print(
                f"Maximum fractional difference between KCAP and CCL in Cl (ell>10) for bin {i+1}-{j+1}: {max(np.abs(frac_diff_cl_KCAP_CCL[ell_mask]))}"
            )
            print(
                f"Maximum fractional difference between KCAP and MP in Cl (ell>10) for bin {i+1}-{j+1}: {max(np.abs(frac_diff_cl_KCAP_MP[ell_mask]))}"
            )

            frac_diff_xi_plus = data["shear_xi_plus",
                                     f"bin_{i+1}_{j+1}"] / ccl_xi[i][j][0] - 1
            print(
                f"Maximum fractional difference in xi_p (theta<10 deg) for bin {i+1}-{j+1}: {max(np.abs(frac_diff_xi_plus[theta_mask]))}"
            )

            frac_diff_xi_minus = data["shear_xi_minus",
                                      f"bin_{i+1}_{j+1}"] / ccl_xi[i][j][1] - 1
            print(
                f"Maximum fractional difference in xi_m (theta>0.05 deg) for bin {i+1}-{j+1}: {max(np.abs(frac_diff_xi_minus[theta_mask]))}"
            )

    if plot:
        import matplotlib.pyplot as plt

        print("Plotting P(k)")

        fig, ax = plt.subplots(2, 1, sharex=True, sharey=False, figsize=(5, 5))
        fig.subplots_adjust(hspace=0, wspace=0)

        ax[0].loglog(k_lin, pk_lin_ccl, ls="--", label=f"CCL linear P(k)")
        ax[0].loglog(k_lin,
                     data["matter_power_lin", "p_k"][0],
                     ls="--",
                     label=f"CosmoSIS linear P(k)")
        ax[0].loglog(k_nl, pk_nl_ccl, label=f"CCL non-linear P(k)")
        ax[0].loglog(k_nl,
                     data["matter_power_nl", "p_k"][0],
                     label=f"CosmoSIS non-linear P(k)")

        ax[1].semilogx(k_lin,
                       data["matter_power_lin", "p_k"][0] / pk_lin_ccl - 1,
                       ls="--")
        ax[1].semilogx(k_nl, data["matter_power_nl", "p_k"][0] / pk_nl_ccl - 1)

        ax[0].legend(frameon=False)
        ax[0].set_ylabel("$P(k)$ [$h^{-3}$ Mpc$^{3}$]")
        ax[1].set_ylim(-0.05, 0.05)
        ax[1].set_xlabel("$k$ [$h$ Mpc$^{-1}$]")
        ax[1].set_ylabel("$\Delta P(k)/P(k)$ [$h$ Mpc$^{-1}$]")

        fig.suptitle("KCAP vs. CCL, P(k)")
        fig.savefig("KV450_pofk_kcap_vs_ccl.pdf")

        ell_plot_lim = ell_range

        print("Plotting Cls")

        fig, ax = plt.subplots(n_tomo_bin,
                               n_tomo_bin,
                               sharex=True,
                               sharey=True,
                               figsize=(2 * n_tomo_bin, 1.5 * n_tomo_bin))
        fig.subplots_adjust(hspace=0, wspace=0)

        u = ell**2
        for i in range(n_tomo_bin):
            for j in range(n_tomo_bin):
                if j > i:
                    ax[i][j].axis("off")
                else:
                    ax[i][j].loglog(ell,
                                    u * ccl_cl[i][j],
                                    label=f"CCL bin {i+1}-{j+1}")
                    ax[i][j].loglog(ell,
                                    u * data["shear_cl", f"bin_{i+1}_{j+1}"],
                                    label=f"CosmoSIS")
                    ax[i][j].loglog(ell, u * mp_cl[i][j], label=f"MP")

                    ax[i][j].legend(fontsize="small", frameon=False)
                    ax[i][j].set_xlim(*ell_plot_lim)

        for p in ax[-1]:
            p.set_xlabel(r"$\ell$")
        for p in ax:
            p[0].set_ylabel(r"$\ell^2\ C_\ell$")

        fig.suptitle("KCAP vs. CCL vs. MP, Cls")
        fig.savefig("KV450_Cl_kcap_vs_ccl_vs_mp.pdf")

        print("Plotting Cl fractional differences.")
        fig, ax = plt.subplots(n_tomo_bin,
                               n_tomo_bin,
                               sharex=True,
                               sharey=True,
                               figsize=(2 * n_tomo_bin, 1.5 * n_tomo_bin))
        fig.subplots_adjust(hspace=0, wspace=0)
        for i in range(n_tomo_bin):
            for j in range(n_tomo_bin):
                if j > i:
                    ax[i][j].axis("off")
                else:
                    label = f"bin {i+1}-{j+1}"
                    ax[i][j].text(0.75,
                                  0.80,
                                  label,
                                  horizontalalignment='center',
                                  transform=ax[i][j].transAxes)
                    ax[i][j].semilogx(
                        ell,
                        data["shear_cl", f"bin_{i+1}_{j+1}"] / ccl_cl[i][j] -
                        1,
                        label=f"KCAP vs. CCL")
                    ax[i][j].semilogx(
                        ell,
                        data["shear_cl", f"bin_{i+1}_{j+1}"] / mp_cl[i][j] - 1,
                        label="KCAP vs. MP")
                    #ax[i][j].legend(fontsize="small", frameon=False)

                    ax[i][j].axhline(0., ls='-', color='gray')
                    for val in [0.01, 0.05]:
                        ax[i][j].axhline(val, ls=':', color='gray')
                        ax[i][j].axhline(-val, ls=':', color='gray')

                ax[i][j].set_xlim(*ell_plot_lim)
                ax[i][j].set_ylim(-0.1, 0.1)

        ax[1][1].legend(fontsize="small",
                        frameon=False,
                        bbox_to_anchor=(.95, 1.05))

        for p in ax[-1]:
            p.set_xlabel(r"$\ell$")
        for p in ax:
            p[0].set_ylabel(r"$|\Delta C_\ell|/C_\ell$")

        fig.suptitle("KCAP vs. CCL vs. MP, Cls")
        fig.savefig("KV450_Cl_kcap_vs_ccl_vs_mp_frac_diff.pdf")

        print("Plotting xi fractional differences.")
        theta_plot_lim = theta_range
        fig, ax = plt.subplots(n_tomo_bin,
                               n_tomo_bin,
                               sharex=True,
                               sharey=True,
                               figsize=(2 * n_tomo_bin, 1.5 * n_tomo_bin))
        fig.subplots_adjust(hspace=0, wspace=0)
        for i in range(n_tomo_bin):
            for j in range(n_tomo_bin):
                if j > i:
                    ax[i][j].axis("off")
                else:
                    ax[i][j].semilogx(
                        theta,
                        data["shear_xi_plus", f"bin_{i+1}_{j+1}"] /
                        ccl_xi[i][j][0] - 1,
                        label=f"xip bin {i+1}-{j+1}")
                    ax[i][j].semilogx(
                        theta,
                        data["shear_xi_minus", f"bin_{i+1}_{j+1}"] /
                        ccl_xi[i][j][1] - 1,
                        label=f"xim bin {i+1}-{j+1}")
                    ax[i][j].legend(fontsize="small", frameon=False)

                ax[i][j].set_xlim(*theta_plot_lim)
                ax[i][j].set_ylim(-0.1, 0.1)

        for p in ax[-1]:
            p.set_xlabel(r"$\theta$ [deg]")
        for p in ax:
            p[0].set_ylabel(r"$|\Delta \xi|/\xi$")

        fig.suptitle("KCAP vs. CCL, xis")
        fig.savefig("KV450_xi_kcap_vs_ccl_frac_diff.pdf")

        print("Plotting COSEBIs fractional differences.")
        # TODO: this range should be taken from CosmoSIS keywords!!!
        n_modes = 5
        n_tomo_corrs = n_tomo_bin * (n_tomo_bin + 1) // 2
        modes = np.arange(1, n_modes + 1)
        cosebis_mp = statistics_mp["K1K_COSEBIs"].reshape(
            n_tomo_corrs, n_modes)
        fig, ax = plt.subplots(n_tomo_bin,
                               n_tomo_bin,
                               sharex=True,
                               sharey=True,
                               figsize=(2 * n_tomo_bin, 1.5 * n_tomo_bin))
        fig.subplots_adjust(hspace=0, wspace=0)
        idx_corr = 0
        for i in range(n_tomo_bin):
            for j in range(n_tomo_bin):
                if j > i:
                    ax[i][j].axis("off")
                else:
                    # TODO: add also output from CosmoSIS!
                    #ax[i][j].semilogx(modes, data["cosebis", f"bin_{i+1}_{j+1}"] / cosebis_mp[idx_corr, :] -1, label=f"COSEBIs bin {i+1}-{j+1}")
                    ax[i][j].plot(
                        modes,
                        cosebis_mp[idx_corr, :] / cosebis_mp[idx_corr, :] - 1,
                        label=f"COSEBIs bin {i+1}-{j+1}")
                    ax[i][j].legend(fontsize="small", frameon=False)
                    idx_corr += 1

                ax[i][j].set_xlim([0., 6.])
                ax[i][j].set_ylim([-0.1, 0.1])

        for p in ax[-1]:
            p.set_xlabel(r"$n$")
        for p in ax:
            p[0].set_ylabel(r"$|\Delta E_n|/E_n$")

        fig.suptitle("KCAP vs. MP, COSEBIs")
        fig.savefig("KV450_cosebis_kcap_vs_mp_frac_diff.pdf")

        print("Plotting BandPowers fractional differences.")
        # TODO: this range should be taken from CosmoSIS keywords!!!
        n_ell_bins = 8
        n_tomo_corrs = n_tomo_bin * (n_tomo_bin + 1) // 2
        plot_ell = np.logspace(np.log10(100.), np.log10(1500.), n_ell_bins)
        bandpowers_mp = statistics_mp["K1K_BandPowers"].reshape(
            n_tomo_corrs, n_ell_bins)
        fig, ax = plt.subplots(n_tomo_bin,
                               n_tomo_bin,
                               sharex=True,
                               sharey=True,
                               figsize=(2 * n_tomo_bin, 1.5 * n_tomo_bin))
        fig.subplots_adjust(hspace=0, wspace=0)
        idx_corr = 0
        for i in range(n_tomo_bin):
            for j in range(n_tomo_bin):
                if j > i:
                    ax[i][j].axis("off")
                else:
                    # TODO: add also output from CosmoSIS!
                    #ax[i][j].semilogx(modes, data["bandpower", f"bin_{i+1}_{j+1}"] / bandpowers_mp[idx_corr, :] -1, label=f"BandPowers bin {i+1}-{j+1}")
                    ax[i][j].semilogx(plot_ell,
                                      bandpowers_mp[idx_corr, :] /
                                      bandpowers_mp[idx_corr, :] - 1,
                                      label=f"BandPowers bin {i+1}-{j+1}")
                    ax[i][j].legend(fontsize="small", frameon=False)
                    idx_corr += 1

                ax[i][j].set_xlim([100., 1500.])
                ax[i][j].set_ylim([-0.1, 0.1])

        for p in ax[-1]:
            p.set_xlabel(r"$\ell$")
        for p in ax:
            p[0].set_ylabel(r"$|\Delta PeeE|/PeeE $")

        fig.suptitle("KCAP vs. MP, BandPowers")
        fig.savefig("MOCK_bandpowers_kcap_vs_mp_frac_diff.pdf")

        plt.show()
lkmin=-5.
lkmax=2.

h0=0.69 #Hubble rate

#Parameters for N(z) \propto z^\alpha \exp[-(z/z0)^\beta]
alpha_nz=2.
beta_nz=1.0
z0_nz=0.3
#Number density in arcmin^-2
ndens_amin2=40.

cosmo=ccl.Cosmology(Omega_c=0.266,Omega_b=0.049,h=h0,sigma8=0.8,n_s=0.96)
karr=10.**(lkmin+(lkmax-lkmin)*np.arange(nk)/(nk-1.))
pklinarr=ccl.linear_matter_power(cosmo,1.,karr*h0)*h0**3
pknlinarr=ccl.nonlin_matter_power(cosmo,1.,karr*h0)*h0**3

zarr=zmax*np.arange(nz)/(nz-1.)
gzarr=ccl.growth_factor(cosmo,1./(1+zarr))
bzarr=0.95/gzarr
nzarr=zarr**alpha_nz*np.exp(-(zarr/z0_nz)**beta_nz)
nzf=interp1d(zarr,nzarr)
#Normalize nz
ntot=quad(nzf,0,zmax)[0]
nzarr*=ndens_amin2*60.**2/ntot
nzf=interp1d(zarr,nzarr)

print "#Gals : %lE"%(0.4*4*np.pi*(180/np.pi)**2*quad(nzf,0,zmax)[0])

np.savetxt("pk_planck.txt",np.transpose([karr,pklinarr]))
np.savetxt("pk_nlin_planck.txt",np.transpose([karr,pknlinarr]))
Ejemplo n.º 31
0
def test_no_sys_pipeline(plot=True):
    param_dict = {"cosmological_parameters" : {"omch2"   : 0.1,
                                               "ombh2"   : 0.022,
                                               "h0"      : 0.7,
                                               "n_s"     : 0.96,
                                               "ln_1e10_A_s" : 3.0,
                                               "omega_k" : 0.0,
                                               "w"       : -1.0,
                                               "mnu"     : 0.06},
                  "halo_model_parameters"   : {"A"       : 2.0,}}


    pipeline_ini = cosmosis.runtime.config.Inifile(PIPELINE_FILE)
    values_ini = cosmosis.runtime.config.Inifile(None)
    values_ini.read_dict(param_dict)

    pipeline = cosmosis.runtime.pipeline.LikelihoodPipeline(pipeline_ini, values=values_ini)

    data = pipeline.run_parameters([])

    ccl_cosmo = ccl.Cosmology(Omega_c=data["cosmological_parameters", "omega_c"], 
                              Omega_b=data["cosmological_parameters", "omega_b"],
                              Omega_k=data["cosmological_parameters", "omega_k"],
                              h=data["cosmological_parameters", "h0"], 
                              n_s=data["cosmological_parameters", "n_s"], 
                              A_s=data["cosmological_parameters", "a_s"],
                              Neff=data["cosmological_parameters", "n_eff"], 
                              m_nu=data["cosmological_parameters", "mnu"],
                              w0=data["cosmological_parameters", "w"],
                             )

    

    print("Loading n(z) and creating CCL tracers.")
    nofz_files = pipeline_ini.get("load_nz", "filepath").split(" ")
    tracers = []
    for nofz_file in nofz_files:
        z, nofz = np.loadtxt(nofz_file, unpack=True)
        z += (z[1]-z[0])/2
        tracers.append(ccl.WeakLensingTracer(cosmo=ccl_cosmo, dndz=(z, nofz)))
    n_tomo_bin = len(tracers)

    print("Comparing P(k) at z=0")
    h = data["cosmological_parameters", "h0"]
    k_lin = data["matter_power_lin", "k_h"]
    k_nl = data["matter_power_nl", "k_h"]
    pk_lin_ccl = ccl.linear_matter_power(ccl_cosmo, k_lin*h, 1.0)*h**3
    pk_nl_ccl = ccl.nonlin_matter_power(ccl_cosmo, k_nl*h, 1.0)*h**3

    frac_diff_pk_lin = data["matter_power_lin", "p_k"][0]/pk_lin_ccl - 1
    frac_diff_pk_nl = data["matter_power_nl", "p_k"][0]/pk_nl_ccl - 1
    print(f"Maximum fractional difference in linear P(k) at z=0 for k<5 h/Mpc: {max(np.abs(frac_diff_pk_lin[k_lin < 5.0]))}")
    print(f"Maximum fractional difference in non-linear P(k) at z=0 for k<5 h/Mpc: {max(np.abs(frac_diff_pk_nl[k_nl < 5.0]))}")

    ell = data["shear_cl", "ell"]
    theta =  data["shear_xi_plus", "theta"]*180/pi
    print("Running CCL for Cls and xis.")
    ccl_cl = {}
    ccl_xi = {}
    for i in range(n_tomo_bin):
        ccl_cl[i] = {}
        ccl_xi[i] = {}
        for j in range(i+1):
            print(f"Bin {i+1}-{j+1}")
            ccl_cl[i][j] = ccl.angular_cl(cosmo=ccl_cosmo, cltracer1=tracers[i], cltracer2=tracers[j], ell=ell)
            
            ell_for_xi = np.concatenate((np.arange(2,100, dtype=float), np.logspace(2,np.log10(ell[-1]), 300)))
            cl_for_xi = ccl.angular_cl(cosmo=ccl_cosmo, cltracer1=tracers[i], cltracer2=tracers[j], ell=ell_for_xi)
            cl_for_xi /= ((ell_for_xi-1)*ell_for_xi*(ell_for_xi+1)*(ell_for_xi+2)/(ell_for_xi+1/2)**4)
            xip = ccl.correlation(cosmo=ccl_cosmo, ell=ell_for_xi, C_ell=cl_for_xi, theta=theta, corr_type="L+")
            xim = ccl.correlation(cosmo=ccl_cosmo, ell=ell_for_xi, C_ell=cl_for_xi, theta=theta, corr_type="L-")
            ccl_xi[i][j] = xip, xim

    ell_range = 10, 10000
    theta_range = 0.05, 10.0
    ell_mask = (ell_range[0] < ell) & (ell < ell_range[1])
    theta_mask = (theta_range[0] < theta) & (theta < theta_range[1])
    for i in range(n_tomo_bin):
        for j in range(i+1):
            frac_diff_cl = data["shear_cl", f"bin_{i+1}_{j+1}"]/ccl_cl[i][j] - 1
            print(f"Maximum fractional difference in Cl (ell>10) for bin {i+1}-{j+1}: {max(np.abs(frac_diff_cl[ell_mask]))}")

            frac_diff_xi_plus = data["shear_xi_plus", f"bin_{i+1}_{j+1}"]/ccl_xi[i][j][0] - 1
            print(f"Maximum fractional difference in xi_p (theta<10 deg) for bin {i+1}-{j+1}: {max(np.abs(frac_diff_xi_plus[theta_mask]))}")

            frac_diff_xi_minus = data["shear_xi_minus", f"bin_{i+1}_{j+1}"]/ccl_xi[i][j][1] - 1
            print(f"Maximum fractional difference in xi_m (theta>0.05 deg) for bin {i+1}-{j+1}: {max(np.abs(frac_diff_xi_plus[theta_mask]))}")


    if plot:
        import matplotlib.pyplot as plt
        print("Plotting P(k)")

        fig, ax = plt.subplots(2, 1, sharex=True, sharey=False,
                            figsize=(5, 5))
        fig.subplots_adjust(hspace=0, wspace=0)

        ax[0].loglog(k_lin, pk_lin_ccl, ls="--", label=f"CCL linear P(k)")
        ax[0].loglog(k_lin, data["matter_power_lin", "p_k"][0], ls="--", label=f"CosmoSIS linear P(k)")
        ax[0].loglog(k_nl, pk_nl_ccl, label=f"CCL non-linear P(k)")
        ax[0].loglog(k_nl, data["matter_power_nl", "p_k"][0], label=f"CosmoSIS non-linear P(k)")

        ax[1].semilogx(k_lin, data["matter_power_lin", "p_k"][0]/pk_lin_ccl-1, ls="--")
        ax[1].semilogx(k_nl, data["matter_power_nl", "p_k"][0]/pk_nl_ccl-1)

        ax[0].legend(frameon=False)
        ax[0].set_ylabel("$P(k)$ [$h^{-3}$ Mpc$^{3}$]")
        ax[1].set_ylim(-0.05, 0.05)
        ax[1].set_xlabel("$k$ [$h$ Mpc$^{-1}$]")
        ax[1].set_ylabel("$\Delta P(k)/P(k)$ [$h$ Mpc$^{-1}$]")
        
        fig.suptitle("KCAP vs CCL, P(k)")
        # fig.savefig("KV450_pofk_kcap_vs_ccl.pdf") 


        print("Plotting Cls")
        ell_plot_lim = ell_range

        fig, ax = plt.subplots(n_tomo_bin, n_tomo_bin, sharex=True, sharey=True,
                                figsize=(2*n_tomo_bin, 1.5*n_tomo_bin))
        fig.subplots_adjust(hspace=0, wspace=0)

        u = ell**2
        for i in range(n_tomo_bin):
            for j in range(n_tomo_bin):
                if j > i:
                    ax[i][j].axis("off")
                else:
                    ax[i][j].loglog(ell, u*ccl_cl[i][j], label=f"CCL bin {i+1}-{j+1}")
                    ax[i][j].loglog(ell, u*data["shear_cl", f"bin_{i+1}_{j+1}"], label=f"CosmoSIS")

                    ax[i][j].legend(fontsize="small", frameon=False)
                    ax[i][j].set_xlim(*ell_plot_lim)

        for p in ax[-1]:
            p.set_xlabel(r"$\ell$")
        for p in ax:
            p[0].set_ylabel(r"$\ell^2\ C_\ell$")

        fig.suptitle("KCAP vs CCL, Cls")
        #fig.savefig("KV450_Cl_kcap_vs_ccl.pdf")

        print("Plotting Cl fractional differences.")
        fig, ax = plt.subplots(n_tomo_bin, n_tomo_bin, sharex=True, sharey=True,
                            figsize=(2*n_tomo_bin, 1.5*n_tomo_bin))
        fig.subplots_adjust(hspace=0, wspace=0)
        for i in range(n_tomo_bin):
            for j in range(n_tomo_bin):
                if j > i:
                    ax[i][j].axis("off")
                else:
                    ax[i][j].semilogx(ell, data["shear_cl", f"bin_{i+1}_{j+1}"]/ccl_cl[i][j]-1, label=f"bin {i+1}-{j+1}")
                    ax[i][j].legend(fontsize="small", frameon=False)
        
                ax[i][j].set_xlim(*ell_plot_lim)
                ax[i][j].set_ylim(-0.1, 0.1)

        for p in ax[-1]:
            p.set_xlabel(r"$\ell$")
        for p in ax:
            p[0].set_ylabel(r"$|\Delta C_\ell|/C_\ell$")

        fig.suptitle("KCAP vs CCL, Cls")
        #fig.savefig("KV450_Cl_kcap_vs_ccl_frac_diff.pdf") 

        print("Plotting xi fractional differences.")
        theta_plot_lim = theta_range
        fig, ax = plt.subplots(n_tomo_bin, n_tomo_bin, sharex=True, sharey=True,
                                figsize=(2*n_tomo_bin, 1.5*n_tomo_bin))
        fig.subplots_adjust(hspace=0, wspace=0)
        for i in range(n_tomo_bin):
            for j in range(n_tomo_bin):
                if j > i:
                    ax[i][j].axis("off")
                else:
                    ax[i][j].semilogx(theta, data["shear_xi_plus", f"bin_{i+1}_{j+1}"]/ccl_xi[i][j][0]-1, label=f"xip bin {i+1}-{j+1}")
                    ax[i][j].semilogx(theta, data["shear_xi_minus", f"bin_{i+1}_{j+1}"]/ccl_xi[i][j][1]-1, label=f"xim bin {i+1}-{j+1}")
                    ax[i][j].legend(fontsize="small", frameon=False)
        
                ax[i][j].set_xlim(*theta_plot_lim)
                ax[i][j].set_ylim(-0.1, 0.1)

        for p in ax[-1]:
            p.set_xlabel(r"$\theta$ [deg]")
        for p in ax:
            p[0].set_ylabel(r"$|\Delta \xi|/\xi$")

        fig.suptitle("KCAP vs CCL, xis")
        #fig.savefig("KV450_xi_kcap_vs_ccl_frac_diff.pdf") 
        
        plt.show()