コード例 #1
0
ファイル: amplitude_model.py プロジェクト: damonge/NzCV
 def get_power_spectrum(self, cosmo, nz1, nz2):
     """
     Compute power spectrum between two redshift distributions
     """
     t1 = ccl.WeakLensingTracer(cosmo, nz1)
     t2 = ccl.WeakLensingTracer(cosmo, nz2)
     return ccl.angular_cl(cosmo, t1, t2, self.ells)
コード例 #2
0
def test_tracer_lensing_kernel_spline_vs_gsl_intergation(
        z_min, z_max, n_z_samples):
    # Create a new Cosmology object so that we're not messing with the other
    # tests
    cosmo = ccl.Cosmology(Omega_c=0.27,
                          Omega_b=0.045,
                          h=0.67,
                          sigma8=0.8,
                          n_s=0.96,
                          transfer_function='bbks',
                          matter_power_spectrum='linear')
    z = np.linspace(z_min, z_max, n_z_samples)
    n = dndz(z)

    # Make sure case where z[0] > 0 and n[0] > 0 is tested for
    if z_min > 0:
        assert n[0] > 0

    cosmo.cosmo.gsl_params.LENSING_KERNEL_SPLINE_INTEGRATION = True
    tr_wl = ccl.WeakLensingTracer(cosmo, dndz=(z, n))
    w_wl_spline, _ = tr_wl.get_kernel(chi=None)

    cosmo.cosmo.gsl_params.LENSING_KERNEL_SPLINE_INTEGRATION = False
    tr_wl = ccl.WeakLensingTracer(cosmo, dndz=(z, n))
    w_wl_gsl, chi = tr_wl.get_kernel(chi=None)

    # Peak of kernel is ~1e-5
    if n_z_samples >= 1000:
        assert np.allclose(w_wl_spline[0], w_wl_gsl[0], atol=1e-10, rtol=1e-9)
    else:
        assert np.allclose(w_wl_spline[0], w_wl_gsl[0], atol=5e-9, rtol=1e-5)
コード例 #3
0
ファイル: test_ccl.py プロジェクト: boryanah/GrandConjuration
 def test_method(self, cosmo):
     z_n = np.linspace(0., 1., 200)
     n = np.ones(z_n.shape)
     tracer1 = ccl.WeakLensingTracer(cosmo, dndz=(z_n, n))
     tracer2 = ccl.WeakLensingTracer(cosmo, dndz=(z_n, n))
     ell = np.logspace(np.log10(3), 3)
     cls = ccl.cls.angular_cl(cosmo, tracer1, tracer2, ell)
     return cls
コード例 #4
0
def get_cl_ccl(pars, ell_bp):

    cosmo = get_cosmo_ccl(pars)
    clust = ccl.NumberCountsTracer(cosmo,
                                   has_rsd=False,
                                   dndz=(z, pz),
                                   bias=(z, bz))
    lens = ccl.WeakLensingTracer(cosmo, dndz=(z, pz))

    ell = np.arange(nell)
    cl0 = np.zeros(nell) * 0.

    cls = np.zeros([3, 3, nell])
    cls[0, 0, :] = ccl.angular_cl(cosmo, clust, clust, ell)
    cls[0, 1, :] = ccl.angular_cl(cosmo, clust, lens, ell)
    cls[0, 2, :] = cl0
    cls[1, 0, :] = cls[0, 1, :]
    cls[1, 1, :] = ccl.angular_cl(cosmo, lens, lens, ell)
    cls[1, 2, :] = cl0
    cls[2, 0, :] = cls[0, 2, :]
    cls[2, 1, :] = cls[1, 2, :]
    cls[2, 2, :] = cl0

    cl_flat = np.concatenate(
        [cls[0, 0, ell_bp], cls[0, 1, ell_bp], cls[1, 1, ell_bp]])

    return cl_flat
コード例 #5
0
def get_cl(dtype):
    config = get_config(dtype)
    cosmo_pars = config['cosmo']
    cosmo = ccl.Cosmology(**cosmo_pars)

    if config['dtype'] == 'generic':
        return np.ones(3 * config['nside'])

    if config['dtype'] == 'galaxy_density':
        z, nz = np.loadtxt('xcell/tests/data/DESY1gc_dndz_bin0.txt',
                           usecols=(1, 3),
                           unpack=True)
        b = np.ones_like(z)
        tracer = ccl.NumberCountsTracer(cosmo,
                                        dndz=(z, nz),
                                        bias=(z, b),
                                        has_rsd=None)
    elif config['dtype'] == 'galaxy_shear':
        z, nz = np.loadtxt('xcell/tests/data/Nz_DIR_z0.1t0.3.asc',
                           usecols=(0, 1),
                           unpack=True)
        tracer = ccl.WeakLensingTracer(cosmo, dndz=(z, nz))
    elif config['dtype'] == 'cmb_convergence':
        tracer = ccl.CMBLensingTracer(cosmo, z_source=1100)
    elif config['dtype'] == 'cmb_tSZ':
        tracer = ccl.tSZTracer(cosmo, z_max=3.)

    cl = ccl.angular_cl(cosmo, tracer, tracer, np.arange(3 * config['nside']))
    return cl
コード例 #6
0
ファイル: shear_test.py プロジェクト: fjaviersanchez/descqa
    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]
コード例 #7
0
def test_tracer_nz_support():
    z_max = 1.0
    a = np.linspace(1 / (1 + z_max), 1.0, 100)

    background_def = {
        "a": a,
        "chi": ccl.comoving_radial_distance(COSMO, a),
        "h_over_h0": ccl.h_over_h0(COSMO, a)
    }

    calculator_cosmo = ccl.CosmologyCalculator(Omega_c=0.27,
                                               Omega_b=0.045,
                                               h=0.67,
                                               sigma8=0.8,
                                               n_s=0.96,
                                               background=background_def)

    z = np.linspace(0., 2., 2000)
    n = dndz(z)

    with pytest.raises(ValueError):
        _ = ccl.WeakLensingTracer(calculator_cosmo, (z, n))

    with pytest.raises(ValueError):
        _ = ccl.NumberCountsTracer(calculator_cosmo,
                                   has_rsd=False,
                                   dndz=(z, n),
                                   bias=(z, np.ones_like(z)))

    with pytest.raises(ValueError):
        _ = ccl.CMBLensingTracer(calculator_cosmo, z_source=2.0)
コード例 #8
0
def get_tomo_xi_ccl(sigma8, Omega_cm0, Omega_bm0, h, zpts, zhist, theta_deg, ell):
    ns = 0.965

    ell_num = len(ell)

    # tomo panel num
    tomo_bin_num, zpts_num = zhist.shape
    tomo_panel_num = int((tomo_bin_num * tomo_bin_num + tomo_bin_num) / 2)

    cosmo = pyccl.Cosmology(Omega_c=Omega_cm0, Omega_b=Omega_bm0, h=h, n_s=ns, sigma8=sigma8,
                          transfer_function="boltzmann_camb")

    ccl_lens_trs = []
    ccl_PL = numpy.zeros((tomo_panel_num, ell_num))
    ccl_xip = numpy.zeros_like(theta_deg)
    ccl_xim = numpy.zeros_like(theta_deg)

    for i in range(tomo_bin_num):
        lens_tr = pyccl.WeakLensingTracer(cosmo, dndz=(zpts, zhist[i]))
        ccl_lens_trs.append(lens_tr)

    tag = 0
    for i in range(tomo_bin_num):
        for j in range(i, tomo_bin_num):
            ccl_PL[tag] = pyccl.angular_cl(cosmo, ccl_lens_trs[i], ccl_lens_trs[j], ell)
            ccl_xip[tag] = pyccl.correlation(cosmo, ell, ccl_PL[tag], theta_deg[tag], type='GG+', method='FFTLog')
            ccl_xim[tag] = pyccl.correlation(cosmo, ell, ccl_PL[tag], theta_deg[tag], type='GG-', method='FFTLog')
            tag += 1
    return ccl_xip, ccl_xim, ccl_PL
コード例 #9
0
def get_tracer(tracer_type, cosmo=None, **tracer_kwargs):
    if cosmo is None:
        cosmo = COSMO
    z = np.linspace(0., 1., 2000)
    n = dndz(z)
    b = np.sqrt(1. + z)

    if tracer_type == 'nc':
        ntr = 3
        tr = ccl.NumberCountsTracer(cosmo,
                                    True,
                                    dndz=(z, n),
                                    bias=(z, b),
                                    mag_bias=(z, b),
                                    **tracer_kwargs)
    elif tracer_type == 'wl':
        ntr = 2
        tr = ccl.WeakLensingTracer(cosmo,
                                   dndz=(z, n),
                                   ia_bias=(z, b),
                                   **tracer_kwargs)
    elif tracer_type == 'cl':
        ntr = 1
        tr = ccl.CMBLensingTracer(cosmo, 1100., **tracer_kwargs)
    else:
        ntr = 0
        tr = ccl.Tracer(**tracer_kwargs)
    return tr, ntr
コード例 #10
0
ファイル: test_pk2d.py プロジェクト: borisbolliet/CCL
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)
コード例 #11
0
ファイル: test_cls.py プロジェクト: yingzhac/CCL
def test_cls_raise_ell_reversed(ells):
    z = np.linspace(0., 1., 200)
    n = np.exp(-((z - 0.5) / 0.1)**2)
    lens = ccl.WeakLensingTracer(COSMO, (z, n))

    with pytest.raises(ValueError):
        ccl.angular_cl(COSMO, lens, lens, ells)
コード例 #12
0
def test_clfid_halomod(tr1, tr2):
    data = get_config(dtype0=tr1, dtype1=tr2, inc_hm=True)

    cosmo = ccl.Cosmology(**data['cov']['fiducial']['cosmo'])
    md = ccl.halos.MassDef200m()
    mf = ccl.halos.MassFuncTinker10(cosmo, mass_def=md)
    hb = ccl.halos.HaloBiasTinker10(cosmo, mass_def=md)
    cm = ccl.halos.ConcentrationDuffy08(mdef=md)
    hmc = ccl.halos.HMCalculator(cosmo, mf, hb, md)
    pNFW = ccl.halos.HaloProfileNFW(cm)
    profs = {}
    ccltr = {}
    normed = {}
    for tr, lab in [(tr1, 'Dummy__0'), (tr2, 'Dummy__1')]:
        if tr == 'galaxy_density':
            data['tracers'][lab]['hod_params'] = {'lMmin_0': 12.1,
                                                  'lM1_p': 0.1,
                                                  'bg_0': 1.2}
            profs[tr] = ccl.halos.HaloProfileHOD(cm, lMmin_0=12.1,
                                                 lM1_p=0.1, bg_0=1.2)
            z, nz = np.loadtxt('xcell/tests/data/DESY1gc_dndz_bin0.txt',
                               usecols=(1, 3), unpack=True)
            ccltr[tr] = ccl.NumberCountsTracer(cosmo, False, dndz=(z, nz),
                                               bias=(z, np.ones_like(z)))
            normed[tr] = True
        elif tr == 'cmb_tSZ':
            data['tracers'][lab]['gnfw_params'] = {'mass_bias': 0.9}
            profs[tr] = ccl.halos.HaloProfilePressureGNFW(mass_bias=0.9)
            ccltr[tr] = ccl.tSZTracer(cosmo, z_max=3.)
            normed[tr] = False
        elif tr == 'galaxy_shear':
            profs[tr] = pNFW
            z, nz = np.loadtxt('xcell/tests/data/Nz_DIR_z0.1t0.3.asc',
                               usecols=(0, 1), unpack=True)
            ccltr[tr] = ccl.WeakLensingTracer(cosmo, dndz=(z, nz))
            normed[tr] = True
        elif tr == 'cmb_convergence':
            profs[tr] = pNFW
            ccltr[tr] = ccl.CMBLensingTracer(cosmo, z_source=1100.)
            normed[tr] = True

    clf = ClFid(data, 'Dummy__0', 'Dummy__1')
    d = clf.get_cl_file()
    shutil.rmtree(tmpdir1)

    k_arr = np.geomspace(1E-4, 1E2, 512)
    a_arr = 1./(1+np.linspace(0, 3, 15)[::-1])
    pk = ccl.halos.halomod_Pk2D(cosmo, hmc, profs[tr1],
                                prof2=profs[tr2],
                                normprof1=normed[tr1],
                                normprof2=normed[tr2],
                                lk_arr=np.log(k_arr),
                                a_arr=a_arr)
    # Commented out until these features are pushed to the pip release of CCL
    # smooth_transition=(lambda a: 0.7),
    # supress_1h=(lambda a: 0.01))
    clb = ccl.angular_cl(cosmo, ccltr[tr1], ccltr[tr2], d['ell'], p_of_k_a=pk)

    assert np.all(np.fabs(clb[2:]/d['cl'][0][2:]-1) < 1E-4)
コード例 #13
0
ファイル: test_cls.py プロジェクト: yingzhac/CCL
def test_cls_raise_weird_pk():
    z = np.linspace(0., 1., 200)
    n = np.exp(-((z - 0.5) / 0.1)**2)
    lens = ccl.WeakLensingTracer(COSMO, (z, n))
    ells = [10, 11]

    with pytest.raises(ValueError):
        ccl.angular_cl(COSMO, lens, lens, ells, p_of_k_a=lambda k, a: 10)
コード例 #14
0
def get_tomo_xi_ccl_2(sigma8, Omega_cm0, Omega_bm0, h, zpts, zhist, theta_deg, theta_num_per_bin, ell, used_zbins, xi_pm="xi_p"):
    """
    for the MCMC
    :param sigma8:
    :param Omega_cm0:
    :param Omega_bm0:
    :param h:
    :param zpts: the center of the Z bins
    :param zhist: Z histogram, (n,m), n is the tomographic bin num,
                  includes the histograms of all bins, the used_zbins will determine which bins are used
    :param theta_deg: where the signals are measured, (n,)
    :param ell: \ell of C(\ell), the angular power spectrum
    :param uesd_zbins: numpy array,(n,), labels, 1 for used, 0 for not used
    :return:
    """
    # tomo panel num
    tomo_bin_num, zbin_num = used_zbins.shape[0],used_zbins.sum()

    cosmo = pyccl.Cosmology(Omega_c=Omega_cm0, Omega_b=Omega_bm0, h=h, n_s=0.965, sigma8=sigma8,
                            transfer_function="boltzmann_camb")

    ccl_lens_trs = []

    for i in range(tomo_bin_num):
        if used_zbins[i] == 1:
            lens_tr = pyccl.WeakLensingTracer(cosmo, dndz=(zpts, zhist[i]))
            ccl_lens_trs.append(lens_tr)

    if xi_pm == "all":
        pts_num = int(2*theta_deg.shape[0])
        ccl_xipm = numpy.zeros((pts_num,))
        tag = 0
        for i in range(zbin_num):
            for j in range(i, zbin_num):
                st, ed = int(tag * theta_num_per_bin), int((tag + 1) * theta_num_per_bin)
                ccl_cls = pyccl.angular_cl(cosmo, ccl_lens_trs[i], ccl_lens_trs[j], ell)
                ccl_xipm[st:ed] = pyccl.correlation(cosmo, ell, ccl_cls, theta_deg[st:ed], type='GG+', method='FFTLog')
                ccl_xipm[pts_num+st:pts_num+ed] = pyccl.correlation(cosmo, ell, ccl_cls, theta_deg[st:ed], type='GG-', method='FFTLog')
                tag += 1
        return ccl_xipm

    if xi_pm == "xi_p":
        corr_type = "GG+"
    elif xi_pm == "xi_m":
        corr_type = "GG-"
    else:
        print("xi_pm must be one of [\"xi_p\", \"xi_m\",\"all\"]")
        return None

    ccl_xi = numpy.zeros_like(theta_deg)
    tag = 0
    for i in range(zbin_num):
        for j in range(i, zbin_num):
            st, ed = int(tag*theta_num_per_bin), int((tag+1)*theta_num_per_bin)
            ccl_cls = pyccl.angular_cl(cosmo, ccl_lens_trs[i], ccl_lens_trs[j], ell)
            ccl_xi[st:ed] = pyccl.correlation(cosmo, ell, ccl_cls, theta_deg[st:ed], type=corr_type, method='FFTLog')
            tag += 1
    return ccl_xi
コード例 #15
0
ファイル: utils.py プロジェクト: damonge/S8z
 def get_ccl_tracer(self, cosmo):
     _, z, _, nz = np.loadtxt(self.get_path(self.config_h['dndz']),
                              unpack=True)
     if self.type == 'gc':
         bz = np.ones_like(z) * self.config_h['bias']
         tr = ccl.NumberCountsTracer(cosmo, False, (z, nz), (z, bz))
     elif self.type == 'sh':
         tr = ccl.WeakLensingTracer(cosmo, (z, nz))
     return tr
コード例 #16
0
ファイル: cl.py プロジェクト: damonge/S8z
 def compute_tracer_ccl(self, tr):
     tracer = self.data['tracers'][tr]
     fiducial = self.data['cov']['fiducial']
     # Get Tracers
     if tracer['type'] == 'gc':
         # Import z, pz
         z, pz = np.loadtxt(tracer['dndz'],
                            usecols=tracer['dndz_cols'],
                            unpack=True)
         # Calculate z bias
         dz = 0
         z_dz = z - dz
         # Set to 0 points where z_dz < 0:
         sel = z_dz >= 0
         z_dz = z_dz[sel]
         pz = pz[sel]
         # Calculate bias
         bias = None
         if fiducial['gc_bias'] is True:
             bias = (z, tracer['bias'] * np.ones_like(z))
         # Get tracer
         return ccl.NumberCountsTracer(self.cosmo,
                                       has_rsd=False,
                                       dndz=(z_dz, pz),
                                       bias=bias)
     elif tracer['type'] == 'wl':
         # Import z, pz
         z, pz = np.loadtxt(tracer['dndz'],
                            usecols=tracer['dndz_cols'],
                            unpack=True)
         # Calculate z bias
         dz = 0
         z_dz = z - dz
         # Set to 0 points where z_dz < 0:
         sel = z_dz >= 0
         z_dz = z_dz[sel]
         pz = pz[sel]
         # # Calculate bias IA
         ia_bias = None
         if fiducial['wl_ia']:
             A, eta, z0 = fiducial[
                 'wl_ia']  # TODO: Improve this in yml file
             bz = A * (
                 (1. + z) / (1. + z0)
             )**eta * 0.0139 / 0.013872474  # pyccl2 -> has already the factor inside. Only needed bz
             ia_bias = (z, bz)
         # Get tracer
         return ccl.WeakLensingTracer(self.cosmo,
                                      dndz=(z_dz, pz),
                                      ia_bias=ia_bias)
     elif tracer['type'] == 'cv':
         return ccl.CMBLensingTracer(self.cosmo,
                                     z_source=1100)  #TODO: correct z_source
     else:
         raise ValueError(
             'Type of tracer not recognized. It can be gc, wl or cv!')
コード例 #17
0
    def compute_theory_c_ell(self, cosmo, nz, sacc_data):
        # Turn the nz into CCL Tracer objects
        # Use the cosmology object to calculate C_ell values
        import pyccl as ccl
        import sacc

        CEE = sacc.standard_types.galaxy_shear_cl_ee
        CEd = sacc.standard_types.galaxy_shearDensity_cl_e
        Cdd = sacc.standard_types.galaxy_density_cl
        theory = {}

        for data_type in [CEE, CEd, Cdd]:
            for t1, t2 in sacc_data.get_tracer_combinations(data_type):
                ell = sacc_data.get_tag('ell', data_type, (t1, t2))
                tracer1 = sacc_data.get_tracer(t1)
                tracer2 = sacc_data.get_tracer(t2)
                dndz1 = (tracer1.z, tracer1.nz)
                dndz2 = (tracer2.z, tracer2.nz)

                if data_type in [CEE, CEd]:
                    cTracer1 = ccl.WeakLensingTracer(cosmo, dndz=dndz1)
                else:
                    bias = (tracer1.z, np.ones_like(tracer1.z))
                    cTracer1 = ccl.NumberCountsTracer(cosmo,
                                                      has_rsd=False,
                                                      bias=bias,
                                                      dndz=dndz1)
                    warnings.warn("Not including bias in fiducial cosmology")

                if data_type == CEE:
                    cTracer2 = ccl.WeakLensingTracer(cosmo, dndz=dndz1)
                else:
                    bias = (tracer2.z, np.ones_like(tracer2.z))
                    cTracer2 = ccl.NumberCountsTracer(cosmo,
                                                      has_rsd=False,
                                                      bias=bias,
                                                      dndz=dndz2)

                print(" - Calculating fiducial C_ell for ", data_type, t1, t2)
                theory[(data_type, t1,
                        t2)] = ccl.angular_cl(cosmo, cTracer1, cTracer2, ell)

        return theory
コード例 #18
0
def test_tracer_n_sample_wl():
    z = np.linspace(0., 1., 2000)
    n = dndz(z)

    n_samples = 50
    tr_wl = ccl.WeakLensingTracer(COSMO, dndz=(z, n), n_samples=n_samples)
    w, chi = tr_wl.get_kernel(chi=None)

    assert w[0].shape[-1] == n_samples
    assert chi[0].shape[-1] == n_samples
コード例 #19
0
    def get_tracer_info(self, two_point_data={}):
        """
        Creates CCL tracer objects and computes the noise for all the tracers
        Check usage: Can we call all the tracer at once?

        Parameters:
        -----------
            two_point_data (sacc obj):

        Returns:
        --------
            ccl_tracers: dict, ccl obj
                ccl.WeakLensingTracer or ccl.NumberCountsTracer
            tracer_Noise ({dict: float}): 
                shot (shape) noise for lens (sources)
        """
        ccl_tracers = {}
        tracer_Noise = {}
        # b = { l:bi*np.ones(len(z)) for l, bi in self.lens_bias.items()}

        for tracer in two_point_data.tracers:
            tracer_dat = two_point_data.get_tracer(tracer)
            z = tracer_dat.z

            # FIXME: Following should be read from sacc dataset.--------------
            #Ngal = 26.  # arc_min^2
            #sigma_e = .26
            #b = 1.5*np.ones(len(z))  # Galaxy bias (constant with scale and z)
            # AI = .5*np.ones(len(z))  # Galaxy bias (constant with scale and z)
            #Ngal = Ngal*3600/d2r**2
            # ---------------------------------------------------------------

            dNdz = tracer_dat.nz
            dNdz /= (dNdz * np.gradient(z)).sum()
            dNdz *= self.Ngal[tracer]
            #FAO  this should be called by tomographic bin
            if 'source' in tracer or 'src' in tracer:
                IA_bin = self.IA * np.ones(len(z))  # fao: refactor this
                ccl_tracers[tracer] = ccl.WeakLensingTracer(self.cosmo,
                                                            dndz=(z, dNdz),
                                                            ia_bias=(z,
                                                                     IA_bin))
                # CCL automatically normalizes dNdz
                tracer_Noise[
                    tracer] = self.sigma_e[tracer]**2 / self.Ngal[tracer]

            elif 'lens' in tracer:
                # import pdb; pdb.set_trace()
                b = self.bias_lens[tracer] * np.ones(len(z))
                tracer_Noise[tracer] = 1. / self.Ngal[tracer]
                ccl_tracers[tracer] = ccl.NumberCountsTracer(self.cosmo,
                                                             has_rsd=False,
                                                             dndz=(z, dNdz),
                                                             bias=(z, b))
        return ccl_tracers, tracer_Noise
コード例 #20
0
ファイル: test_cls.py プロジェクト: chrgeorgiou/CCL
def test_cls_smoke(p_of_k_a):
    # make a set of tracers to test with
    z = np.linspace(0., 1., 200)
    n = np.exp(-((z - 0.5) / 0.1)**2)
    b = np.sqrt(1. + z)
    lens1 = ccl.WeakLensingTracer(COSMO, (z, n))
    lens2 = ccl.WeakLensingTracer(COSMO, dndz=(z, n), ia_bias=(z, n))
    nc1 = ccl.NumberCountsTracer(COSMO, False, dndz=(z, n), bias=(z, b))
    nc2 = ccl.NumberCountsTracer(COSMO, True, dndz=(z, n), bias=(z, b))
    nc3 = ccl.NumberCountsTracer(COSMO,
                                 True,
                                 dndz=(z, n),
                                 bias=(z, b),
                                 mag_bias=(z, b))
    cmbl = ccl.CMBLensingTracer(COSMO, 1100.)
    tracers = [lens1, lens2, nc1, nc2, nc3, cmbl]

    ell_scl = 4.
    ell_int = 4
    ell_lst = [2, 3, 4, 5]
    ell_arr = np.arange(2, 5)
    ells = [ell_int, ell_scl, ell_lst, ell_arr]

    for i in range(len(tracers)):
        for j in range(i, len(tracers)):
            for ell in ells:
                corr = ccl.angular_cl(COSMO,
                                      tracers[i],
                                      tracers[j],
                                      ell,
                                      p_of_k_a=p_of_k_a)
                assert np.all(np.isfinite(corr))
                assert np.shape(corr) == np.shape(ell)

                # reversing should be fine
                corr_rev = ccl.angular_cl(COSMO,
                                          tracers[j],
                                          tracers[i],
                                          ell,
                                          p_of_k_a=p_of_k_a)
                assert np.allclose(corr, corr_rev)
コード例 #21
0
def get_tracers_ccl(cosmo, z, pz, bz):
    n_bins = pz.shape[0]
    # Tracers
    tracers = []
    for i in range(n_bins):
        tracers.append(
            ccl.NumberCountsTracer(cosmo,
                                   has_rsd=False,
                                   dndz=(z[i], pz[i]),
                                   bias=(z[i], bz[i])))
        tracers.append(ccl.WeakLensingTracer(cosmo, dndz=(z[i], pz[i])))
    return np.array(tracers)
コード例 #22
0
def euclid_ccl(Omega_c, sigma8=0.83):
    """
    Generate C_ell as function of ell for a given Omega_c and Sigma8

    Inputs
        Omega_c -- float: CDM density 
        Sigma_8 -- float: sigma_8

    Assumed global variables
        z -- np.array: samples of z
        ells -- np.array: samples of ell
        dNdz_true -- ccl.dNdzSmail: dNdz distribution
        pz -- ccl.PhotoZGaussian: PhotoZ error
        nbins -- the amount of tomographic redshift bins

    Outputs
        Cls -- np.array, shape (nbins*(nbins-1)/2 + nbins, len(ell)): 
                Cross/Auto correlation shear spectra for the tomographic bins
        dNdzs -- np.array, shape (nbins,len(z):
                dNdz per redshift bin, for all redshifts

    """

    cosmo_fid = ccl.Cosmology(Omega_c=Omega_c,
                              Omega_b=0.045,
                              h=0.71,
                              sigma8=sigma8,
                              n_s=0.963)

    dNdzs = np.zeros((nbins, z.size))
    shears = []

    for i in range(nbins):
        # edges of 1 equal width redshift bins, between 0 and 2
        zmin, zmax = i * (2. / nbins), (i + 1) * (2. / nbins)
        # generate dNdz per bin
        dNdzs[i, :] = ccl.dNdz_tomog(z=z,
                                     zmin=zmin,
                                     zmax=zmax,
                                     pz_func=pz,
                                     dNdz_func=dNdz_true)
        # calculate the shear per bin
        gal_shapes = ccl.WeakLensingTracer(cosmo_fid, dndz=(z, dNdzs[i, :]))
        shears.append(gal_shapes)

    print('Shears calculated, calculating power spectra now...')
    # calculate nbin*(nbin+1)/2 = 1 spectra from the shears
    Cls = []
    for i in range(nbins):
        for j in range(0, i + 1):
            Cls.append(ccl.angular_cl(cosmo_fid, shears[i], shears[j], ells))

    return np.array(Cls), dNdzs
コード例 #23
0
    def setup(self):
        # Initialize cosmology
        par = self.get_cosmological_parameters()
        dpk = self.get_pk()
        a = 1./(1+dpk['z'][::-1])
        self.cosmo = ccl.CosmologyCalculator(Omega_c=par['Omega_m']-par['Omega_b'],
                                             Omega_b=par['Omega_b'],
                                             h=par['h'], n_s=par['n_s'],
                                             A_s=par['A_s'], w0=par['w0'],
                                             pk_linear={'a': a,
                                                        'k': dpk['k'],
                                                        'delta_matter:delta_matter': dpk['pk_lin'][::-1][:]},
                                             pk_nonlin={'a': a,
                                                        'k': dpk['k'],
                                                        'delta_matter:delta_matter': dpk['pk_nl'][::-1][:]})

        # Initialize tracers
        if self.config.get('tracers_from_kernels', False):
            tpar = self.get_tracer_parameters()
            ker = self.get_tracer_kernels()
            a_g = 1./(1+ker['z_cl'][::-1])
            self.t_g = []
            for k in ker['kernels_cl']:
                t = ccl.Tracer()
                barr = np.ones_like(a_g)
                t.add_tracer(self.cosmo,
                             (ker['chi_cl'], k),
                             transfer_a=(a_g, barr))
                self.t_g.append(t)
            self.t_s = []
            for k in ker['kernels_sh']:
                t = ccl.Tracer()
                t.add_tracer(self.cosmo,
                             kernel=(ker['chi_sh'], k),
                             der_bessel=-1, der_angles=2)
                self.t_s.append(t)
        else:
            nzs = self.get_tracer_dndzs()
            tpar = self.get_tracer_parameters()
            z_g = nzs['z_cl']
            z_s = nzs['z_sh']
            self.t_g = [ccl.NumberCountsTracer(self.cosmo, True,
                                               (z_g, nzs['dNdz_cl'][:, ni]),
                                               bias=(z_g,
                                                     np.full(len(z_g), b)))
                        for ni, b in zip(range(0, 10),
                                         tpar['b_g'])]
            self.t_s = [ccl.WeakLensingTracer(self.cosmo,
                                              (z_s, nzs['dNdz_sh'][:, ni]),
                                              True)
                        for ni in range(0, 5)]
コード例 #24
0
def getCl(cosmo, dndz_sliced, ell):
    """This function calculats auto- and cross-power spectra for given sliced galaxy-redshift distribution."""
    n = len(dndz_sliced)
    lens = [[]] * n
    for i, dndz in enumerate(dndz_sliced.values()):
        lens[i] = ccl.WeakLensingTracer(cosmo, dndz=(dndz[:, 0], dndz[:, 1]))
    #create an empty n-by-n array that stores the lensing cross power spectrum between the ith and jth bin
    cl = []
    for j in range(n):
        cl.extend(
            ccl.angular_cl(cosmo, lens[j], lens[j + i], ell)
            for i in range(n - j))
    cl_arr = np.array(cl)
    return cl_arr
コード例 #25
0
 def get_ccl_tracer(tr):
     if tr == 'galaxy_density':
         z, nz = np.loadtxt('xcell/tests/data/DESY1gc_dndz_bin0.txt',
                            usecols=(1, 3), unpack=True)
         t = ccl.NumberCountsTracer(cosmo, False, dndz=(z, nz),
                                    bias=(z, np.ones_like(z)),
                                    mag_bias=(z, np.ones_like(z)))
     elif tr == 'galaxy_shear':
         z, nz = np.loadtxt('xcell/tests/data/Nz_DIR_z0.1t0.3.asc',
                            usecols=(0, 1), unpack=True)
         t = ccl.WeakLensingTracer(cosmo, dndz=(z, nz))
     elif tr == 'cmb_convergence':
         t = ccl.CMBLensingTracer(cosmo, z_source=1100.)
     return t
コード例 #26
0
ファイル: cls_scale_cuts.py プロジェクト: damonge/S8z
def get_tracers_ccl(cosmo, tracers_info):
    # Get Tracers
    for tr in tracers_info['maps']:
        if tr['type'] == 'gc':
            # Import z, pz
            fname = os.path.join(files_root, tr['dndz_file'])
            z, pz = np.loadtxt(fname, usecols=(1, 3), unpack=True)
            # Calculate z bias
            dz = 0
            z_dz = z - dz
            # Set to 0 points where z_dz < 0:
            sel = z_dz >= 0
            z_dz = z_dz[sel]
            pz = pz[sel]
            # Calculate bias
            bias = tr['bias']
            bz = bias * np.ones(z.shape)
            # Get tracer
            tr['tracer'] = ccl.NumberCountsTracer(cosmo,
                                                  has_rsd=False,
                                                  dndz=(z_dz, pz),
                                                  bias=(z, bz))
        elif tr['type'] == 'wl':
            # Import z, pz
            fname = os.path.join(files_root, tr['dndz_file'])
            z, pz = np.loadtxt(fname, usecols=(1, 3), unpack=True)
            # Calculate z bias
            dz = 0
            z_dz = z - dz
            # Set to 0 points where z_dz < 0:
            sel = z_dz >= 0
            z_dz = z_dz[sel]
            pz = pz[sel]
            # # Calculate bias IA
            # A =
            # eta =
            # z0 =
            # bz = A*((1.+z)/(1.+z0))**eta*0.0139/0.013872474  # pyccl2 -> has already the factor inside. Only needed bz
            # Get tracer
            tr['tracer'] = ccl.WeakLensingTracer(cosmo,
                                                 dndz=(z_dz,
                                                       pz))  # ,ia_bias=(z,bz))
        elif tr['type'] == 'cv':
            tr['tracer'] = ccl.CMBLensingTracer(
                cosmo, z_source=1100)  #TODO: correct z_source
        else:
            raise ValueError(
                'Type of tracer not recognized. It can be gc, wl or cv!')
コード例 #27
0
ファイル: test_pk2d.py プロジェクト: borisbolliet/CCL
def test_pk2d_parsing():
    a_arr = np.linspace(0.1, 1, 100)
    k_arr = np.geomspace(1E-4, 1E3, 1000)
    pk_arr = a_arr[:, None] * ((k_arr / 0.01) / (1 +
                                                 (k_arr / 0.01)**3))[None, :]

    psp = ccl.Pk2D(a_arr=a_arr, lk_arr=np.log(k_arr), pk_arr=np.log(pk_arr))

    cosmo = ccl.CosmologyCalculator(Omega_c=0.27,
                                    Omega_b=0.045,
                                    h=0.67,
                                    sigma8=0.8,
                                    n_s=0.96,
                                    pk_nonlin={
                                        'a': a_arr,
                                        'k': k_arr,
                                        'delta_matter:delta_matter': pk_arr,
                                        'a:b': pk_arr
                                    })
    z = np.linspace(0., 1., 200)
    n = np.exp(-((z - 0.5) / 0.1)**2)
    lens1 = ccl.WeakLensingTracer(cosmo, (z, n))
    ells = np.linspace(2, 100, 10)

    cls1 = ccl.angular_cl(cosmo, lens1, lens1, ells, p_of_k_a=None)
    cls2 = ccl.angular_cl(cosmo,
                          lens1,
                          lens1,
                          ells,
                          p_of_k_a='delta_matter:delta_matter')
    cls3 = ccl.angular_cl(cosmo, lens1, lens1, ells, p_of_k_a='a:b')
    cls4 = ccl.angular_cl(cosmo, lens1, lens1, ells, p_of_k_a=psp)
    assert all_finite(cls1)
    assert all_finite(cls2)
    assert all_finite(cls3)
    assert all_finite(cls4)
    assert np.all(np.fabs(cls2 / cls1 - 1) < 1E-10)
    assert np.all(np.fabs(cls3 / cls1 - 1) < 1E-10)
    assert np.all(np.fabs(cls4 / cls1 - 1) < 1E-10)

    # Wrong name
    with pytest.raises(KeyError):
        ccl.angular_cl(cosmo, lens1, lens1, ells, p_of_k_a='a:c')

    # Wrong type
    with pytest.raises(ValueError):
        ccl.angular_cl(cosmo, lens1, lens1, ells, p_of_k_a=3)
コード例 #28
0
ファイル: cl_theory.py プロジェクト: tilmantroester/ShCl_like
    def run(self, inputs):
        cosmo = ccl.Cosmology(Omega_c=inputs["Omega_c"],
                              Omega_b=inputs["Omega_b"],
                              h=inputs["h"],
                              n_s=inputs["n_s"],
                              A_s=inputs["A_s"],
                              T_CMB=2.7255,
                              m_nu=inputs["m_nu"],
                              transfer_function=self.transfer_function,
                              matter_power_spectrum=self.matter_pk,
                              baryons_power_spectrum=self.baryons_pk)

        if not self.run_boltzmann:
            # Ingest pre-calculated distances
            cosmo._set_background_from_arrays(a_array=inputs["a_bg"],
                                              chi_array=inputs["distance"],
                                              hoh0_array=inputs["E_of_z"])

            # Ingest pre-calculated P(k)
            cosmo._set_linear_power_from_arrays(inputs["a_lin"], 
                inputs["k_lin"], inputs["Pk_lin"])
            cosmo._set_nonlin_power_from_arrays(inputs["a_nl"], 
                inputs["k_nl"], inputs["Pk_nl"])

        data_type = 'galaxy_shear_cl_ee'


        nz_info = inputs['nz']
        ia_info = inputs['ia']
        tracers = {}
        for b in self.tracer_names[data_type]:
            tracers[data_type, b] = ccl.WeakLensingTracer(
                                                cosmo, 
                                                nz_info[b],
                                                ia_bias=ia_info[b]
                                    )

        results = {}
        results[data_type] = {}
        for bin1, bin2 in self.calculations[data_type]:
            ell = self.ell[data_type][bin1, bin2]
            T1 = tracers[data_type, bin1]
            T2 = tracers[data_type, bin2]
            cl = ccl.angular_cl(cosmo, T1, T2, ell)
            results[data_type][bin1, bin2] = cl

        return results
コード例 #29
0
def euclid_ccl(Omega_c, sigma8):
    """
    Generate C_ell as function of ell for a given Omega_c and Sigma8
    Assumes a redshift distribution given by
        z^alpha * exp(z/z0)^beta
        with alpha=1.3, beta = 1.5 and z0 = 0.65

    Assumes photo-z error is Gaussian with a bias is 0.05(1+z)
    """

    cosmo_fid = ccl.Cosmology(Omega_c=Omega_c,
                              Omega_b=0.045,
                              h=0.71,
                              sigma8=sigma8,
                              n_s=0.963)

    ell = np.logspace(np.log10(100), np.log10(6000), 10)

    pz = ccl.PhotoZGaussian(sigma_z0=0.05)
    dNdz_true = ccl.dNdzSmail(alpha=1.3, beta=1.5, z0=0.65)

    dNdzs = np.zeros((nbins, z.size))
    shears = []

    for i in range(nbins):
        # edges of nbins equal width redshift bins, between 0 and 2
        zmin, zmax = i * (2. / nbins), (i + 1) * (2. / nbins)
        # generate dNdz per bin
        dNdzs[i, :] = ccl.dNdz_tomog(z=z,
                                     zmin=zmin,
                                     zmax=zmax,
                                     pz_func=pz,
                                     dNdz_func=dNdz_true)
        # calculate the shear per bin
        gal_shapes = ccl.WeakLensingTracer(cosmo_fid, dndz=(z, dNdzs[i, :]))
        shears.append(gal_shapes)

    # calculate nbin*(nbin+1)/2 spectra from the shears
    Cls = []
    bin_indices = [
    ]  # list of length nbin*(nbin+1)/2 containing tuples with the indices of the bins
    for i in range(nbins):
        for j in range(0, i + 1):
            bin_indices.append((i, j))
            Cls.append(ccl.angular_cl(cosmo_fid, shears[i], shears[j], ell))

    return ell, np.array(Cls), dNdzs, bin_indices
コード例 #30
0
def euclid_ccl(Omega_c, Omega_b=0.045, sigma8=0.83, n_s=0.963, h=0.71, mps='halofit'):
    """
    Generate C_ell as function of ell for a given Omega_c and Sigma8

    Inputs
        Omega_c -- float: CDM density 
        Sigma_8 -- float: sigma_8
        mps     -- string: model to use for matter power spectrum

    Assumed global variables
        z -- np.array: samples of z
        ells -- np.array: samples of ell
        dNdz_true -- ccl.dNdzSmail: dNdz distribution
        pz -- ccl.PhotoZGaussian: PhotoZ error
        nbins -- the amount of tomographic redshift bins

    Outputs
        Cls -- np.array, shape (nbins*(nbins-1)/2 + nbins, len(ell)): 
                Cross/Auto correlation shear spectra for the tomographic bins
        dNdzs -- np.array, shape (nbins,len(z):
                dNdz per redshift bin, for all redshifts

    """

    cosmo_fid = ccl.Cosmology(Omega_c=Omega_c, Omega_b=Omega_b, h=h, sigma8=sigma8, n_s=n_s, matter_power_spectrum=mps)

    dNdzs = np.zeros((nbins, z.size))
    shears = []
    
    for i in range(nbins):
        # edges of 2 redshift bins
        zmin_b, zmax_b = zbins[i]
        print (f'Redshift bin {i}: {zmin_b} - {zmax_b}')
        # generate dNdz per bin
        dNdzs[i,:] = ccl.dNdz_tomog(z=z, zmin=zmin_b, zmax=zmax_b, pz_func=pz, dNdz_func = dNdz_true)
        # calculate the shear per bin
        gal_shapes = ccl.WeakLensingTracer(cosmo_fid, dndz=(z, dNdzs[i,:]))
        shears.append(gal_shapes)
        
    # calculate nbin*(nbin+1)/2 = 3 spectra from the shears
    Cls = []
    for i in range(nbins):
        for j in range(0,i+1):
            Cls.append(ccl.angular_cl(cosmo_fid, shears[i], shears[j], ells))
     
    return np.array(Cls), dNdzs