Ejemplo n.º 1
0
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)
Ejemplo n.º 2
0
def test_pk2d_cls():
    """
    Test interplay between Pk2D and the Limber integrator
    """

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

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

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

    # Check that passing a correct power spectrum runs as expected
    psp = ccl.Pk2D(pkfunc=lpk2d, cosmo=cosmo)
    cells = ccl.angular_cl(cosmo, lens1, lens1, ells, p_of_k_a=psp)
    assert all_finite(cells)
Ejemplo n.º 3
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
Ejemplo n.º 4
0
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)

    # Check invalid dndz
    with assert_raises(ValueError):
        ccl.NumberCountsTracer(COSMO, False, dndz=z, bias=(z, b))
    with assert_raises(ValueError):
        ccl.NumberCountsTracer(COSMO, False, dndz=(z, n, n), bias=(z, b))
    with assert_raises(ValueError):
        ccl.NumberCountsTracer(COSMO, False, dndz=(z, ), bias=(z, b))
    with assert_raises(ValueError):
        ccl.NumberCountsTracer(COSMO, False, dndz=(1, 2), bias=(z, b))
    with assert_raises(ValueError):
        ccl.WeakLensingTracer(COSMO, dndz=z)
    with assert_raises(ValueError):
        ccl.WeakLensingTracer(COSMO, dndz=(z, n, n))
    with assert_raises(ValueError):
        ccl.WeakLensingTracer(COSMO, dndz=(z, ))
    with assert_raises(ValueError):
        ccl.WeakLensingTracer(COSMO, dndz=(1, 2))
Ejemplo n.º 5
0
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)
Ejemplo n.º 6
0
def test_cls_raise_integ_method():
    ells = [10, 11]
    with pytest.raises(ValueError):
        ccl.angular_cl(COSMO,
                       LENS,
                       LENS,
                       ells,
                       limber_integration_method='guad')
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
Ejemplo n.º 8
0
def test_two_point_some(kind, tmpdir):

    cosmo = ccl.Cosmology(Omega_c=0.27,
                          Omega_b=0.045,
                          Omega_k=0.0,
                          w0=-1.0,
                          wa=0.0,
                          sigma8=0.8,
                          n_s=0.96,
                          h=0.67)

    sources = {}
    for i, mn in enumerate([0.25, 0.75]):
        sources['src%d' % i] = DummySource()
        z = np.linspace(0, 2, 50)
        nz = np.exp(-0.5 * (z - mn)**2 / 0.25 / 0.25)

        if ('g' in kind and i == 0) or kind == 'gg':
            sources['src%d' % i].tracer_ = ccl.ClTracerNumberCounts(
                cosmo,
                has_rsd=False,
                has_magnification=False,
                z=z,
                n=nz,
                bias=np.ones_like(z) * 2.0)
        else:
            sources['src%d' % i].tracer_ = ccl.ClTracerLensing(
                cosmo, has_intrinsic_alignment=False, z=z, n=nz)

        sources['src%d' % i].scale_ = i / 2.0 + 1.0

    # compute the statistic
    tracers = [v.tracer_ for k, v in sources.items()]
    scale = np.prod([v.scale_ for k, v in sources.items()])
    data = os.path.join(tmpdir, 'stat.csv')
    if kind == 'cl':
        ell = np.logspace(1, 3, 10)
        cell = ccl.angular_cl(cosmo, *tracers, ell) * scale
        pd.DataFrame({'l': ell, 'cl': cell}).to_csv(data, index=False)
    else:
        theta = np.logspace(1, 2, 100)
        ell = _ell_for_xi()
        cell = ccl.angular_cl(cosmo, *tracers, ell)
        xi = ccl.correlation(cosmo, ell, cell, theta / 60.0,
                             corr_type=kind) * scale
        pd.DataFrame({'t': theta, 'xi': xi}).to_csv(data, index=False)

    stat = TwoPointStatistic(data=data, kind=kind, sources=['src0', 'src1'])
    stat.compute(cosmo, {}, sources, systematics=None)

    if kind == 'cl':
        assert np.allclose(stat.measured_statistic_, cell)
    else:
        assert np.allclose(stat.measured_statistic_, xi)

    assert np.allclose(stat.measured_statistic_, stat.predicted_statistic_)
Ejemplo n.º 9
0
    def get_log_prob(self, theta):
        # Check the priors
        log_prior = self.get_log_prior(theta)
        if not np.isfinite(log_prior):
            return -np.inf

        # Update default cosmological parameters with new sampled parameters
        params = self.cosmology_params.copy()
        for param_name in self.arg_names:
            if param_name in params:
                params[param_name] = theta[self.arg_names.index(param_name)]
        cosmo = ccl.Cosmology(**params)

        # Update data parameters
        z_tail = theta[self.arg_names.index(
            'z_tail')] if 'z_tail' in self.arg_names else self.z_tail
        bias = theta[self.arg_names.index(
            'bias')] if 'bias' in self.arg_names else self.bias

        # Get redshift distribution
        z_arr, n_arr = get_lotss_redshift_distribution(z_tail=z_tail)
        bias_arr = bias * np.ones(len(z_arr))
        bias_arr = bias_arr / ccl.growth_factor(cosmo, 1. / (1 + z_arr))

        # Get correlations
        number_counts_tracer = ccl.NumberCountsTracer(cosmo,
                                                      has_rsd=False,
                                                      dndz=(z_arr, n_arr),
                                                      bias=(z_arr, bias_arr))
        cmb_lensing_tracer = ccl.CMBLensingTracer(cosmo, 1091)
        correlations = {}
        if 'gg' in self.correlation_symbols:
            correlations['gg'] = ccl.angular_cl(cosmo, number_counts_tracer,
                                                number_counts_tracer,
                                                self.l_arr)
        if 'gk' in self.correlation_symbols:
            correlations['gk'] = ccl.angular_cl(cosmo, number_counts_tracer,
                                                cmb_lensing_tracer, self.l_arr)

        # Bin spectra using coupling matrices in workspaces
        for correlation_symbol in self.correlation_symbols:
            correlations[correlation_symbol] = decouple_correlation(
                self.workspaces[correlation_symbol],
                correlations[correlation_symbol])

        # Calculate log prob
        model = np.concatenate([
            correlations[correlation_symbol][:self.n_ells[correlation_symbol]]
            for correlation_symbol in self.correlation_symbols
        ])
        diff = self.data_vector - model
        log_prob = log_prior - np.dot(
            diff, np.dot(self.inverted_covariance, diff)) / 2.0

        return log_prob
def getLensingCRmatrix(lenses, ell, cosmo):
    """This function calculats auto- and cross-power spectra for given lensing objects in tomographic bins. Input the lensing objects and ls' to integrate over. It returns a matrix that stores the cross power spectra between different bins"""
    n = len(lenses)
    lensCL = np.zeros([n, n, len(ell)])
    #create an empty n-by-n array that stores the lensing cross power spectrum between the ith and jth bin
    for i in range(n):
        lensCL[i, i, :] = ccl.angular_cl(cosmo, lenses[i], lenses[i], ell)
    for j in range(n - 1):
        for k in range(j + 1, n):
            lensCL[j, k, :] = ccl.angular_cl(cosmo, lenses[j], lenses[k], ell)
            lensCL[k, j, :] = lensCL[j, k, :]
    return lensCL
def getTheories(ccl_cosmo,s,ctracers) :
    theo={}
    for t1i,t2i,ells,_ in s.sortTracers():
        cls=ccl.angular_cl(ccl_cosmo,ctracers[t1i],ctracers[t2i],ells)
        theo[(t1i,t2i)]=cls
        theo[(t2i,t1i)]=cls
    return theo
Ejemplo n.º 12
0
    def theory_corr(self, n_z2, xvals, lmax2, chi_max, zlo2, zhi2, cosmo_cat):
        '''compute the correlation function from limber integration over the CAMB power spectrum'''
        nz_int = self.compute_nz(n_z2)
        z_vals = np.linspace(zlo2, zhi2, 1000)
        n_vals = nz_int(z_vals)

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

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

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

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

        pp3_2 = np.zeros((lmax2, 4))
        pp3_2[:, 1] = pp[:] * (ll * (ll + 1.)) / (2. * np.pi)
        cxvals = np.cos(xvals / (60.) / (180. / np.pi))
        vals = camb.correlations.cl2corr(pp3_2, cxvals)
        return xvals, vals[:, 1], vals[:, 2]
Ejemplo n.º 13
0
def get_cl(trs, b1, b2):
    nl = np.zeros(3*o.nside)
    if (b1 == b2) and (not o.full_noise):
        fname_nl = predir + "maps_metacal_bin%d_ns%d_nells.npz" % (b1, o.nside)
        d = np.load(fname_nl)
        nl[2:] = d['nl_cov']

    sl = ccl.angular_cl(cosmo, trs[b1], trs[b2], ls)
    if o.old_nka:
        return np.array([sl + nl, cl0, cl0, nl])
    else:
        w = nmt.NmtWorkspace()
        predir_mcm = predir + 'cls_metacal_mcm_bins_'
        fname_mcm = predir_mcm + '%d%d_ns%d.fits' % (b1, b2, o.nside)
        if os.path.isfile(fname_mcm):
            w.read_from(fname_mcm)
        else:
            fname_mcm = predir_mcm + '%d%d_ns%d.fits' % (b2, b1, o.nside)
            if os.path.isfile(fname_mcm):
                w.read_from(fname_mcm)
            else:
                raise ValueError("Can't find MCM " + fname_mcm)
        mskprod = get_field(b1, return_mask=True)
        if b1 == b2:
            mskprod *= mskprod
        else:
            mskprod *= get_field(b2, return_mask=True)
        fsky = np.mean(mskprod)
        return w.couple_cell([sl, cl0, cl0, cl0])/fsky + np.array([nl, cl0, cl0, nl])
Ejemplo n.º 14
0
def test_xi(set_up, corr_method, t1, t2, bm, er, kind, pref):
    cosmo, trcs, bms, ers, fls = set_up
    method, errfac = corr_method

    # Debugging - define the  same cosmology but in GR

    cl = ccl.angular_cl(cosmo, trcs[t1], trcs[t2], fls['ells'])

    ell = np.arange(fls['lmax'])
    cli = interp1d(fls['ells'], cl, kind='cubic')(ell)
    # Our benchmarks have theta in arcmin
    # but CCL requires it in degrees:
    theta_deg = bms['theta'] / 60.
    # We cut the largest theta value for xi+ because of issues with the
    # benchmarks.
    if kind == 'GG+':
        xi = ccl.correlation(cosmo,
                             ell,
                             cli,
                             theta_deg[0:14],
                             type=kind,
                             method=method)
    else:
        xi = ccl.correlation(cosmo,
                             ell,
                             cli,
                             theta_deg,
                             type=kind,
                             method=method)
    xi *= pref

    assert np.all(np.fabs(xi - bms[bm]) < ers[er] * errfac)
Ejemplo n.º 15
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
Ejemplo n.º 16
0
Archivo: cl.py Proyecto: damonge/S8z
    def get_cl_file(self):
        nside = self.data['healpy']['nside']
        if self.read_symm:
            tr1 = self.tr2
            tr2 = self.tr1
        else:
            tr1 = self.tr1
            tr2 = self.tr2
        fname = os.path.join(self.outdir, 'cl_{}_{}.npz'.format(tr1, tr2))
        ell = np.arange(3 * nside)
        if not os.path.isfile(fname):
            ccl_tr1, ccl_tr2 = self.get_tracers_ccl()
            cl = ccl.angular_cl(self.cosmo, ccl_tr1, ccl_tr2, ell)
            tracers = self.data['tracers']
            fiducial = self.data['cov']['fiducial']
            for tr in [self.tr1, self.tr2]:
                if (tracers[tr]['type'] == 'wl') and fiducial['wl_m']:
                    cl = (1 + tracers[tr]['m']) * cl

            s1, s2 = self.get_spins()
            size = s1 + s2
            if size == 0:
                size = 1
            cl_vector = np.zeros((size, cl.size))
            cl_vector[0] = cl

            np.savez_compressed(fname, cl=cl_vector, ell=ell)

        cl_file = np.load(fname)
        if np.any(cl_file['ell'] != ell):
            raise ValueError(
                'The ell in {} does not match the ell from nside={}'.format(
                    fname, nside))
        return cl_file
Ejemplo n.º 17
0
def check_corr(cosmo):

    # Number density input
    z = np.linspace(0., 1., 200)
    n = np.ones(z.shape)

    # ClTracer test objects
    lens1 = ccl.ClTracerLensing(cosmo, False, n=n, z=z)
    lens2 = ccl.ClTracerLensing(cosmo,
                                True,
                                n=(z, n),
                                bias_ia=(z, n),
                                f_red=(z, n))

    ells = np.arange(3000)
    cls = ccl.angular_cl(cosmo, lens1, lens2, ells)

    t = np.logspace(-2, np.log10(5.), 20)  #degrees
    corrfunc = ccl.correlation(cosmo,
                               ells,
                               cls,
                               t,
                               corr_type='L+',
                               method='FFTLog')
    assert_(all_finite(corrfunc))
Ejemplo n.º 18
0
def compute_cls(oc,ob,h,s8,ns,w,fname_out=False) :
    #Fiducial cosmological parameters
    cosmo=ccl.Cosmology(Omega_c=oc,Omega_b=ob,h=h,sigma8=s8,n_s=ns,w0=w,
                        transfer_function='eisenstein_hu')
    print ccl.sigma8(cosmo)

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

    #Power spectra
    c_ij=np.zeros([LMAX+1,nbins,nbins])
    for i1 in np.arange(nbins) :
        for i2 in np.arange(i1,nbins) :
            print i1,i2
            if xcorr[i1,i2]<-1:#1E-6 :
                c_ij[:,i1,i2]=0
            else :
                c_ij[:,i1,i2]=ccl.angular_cl(cosmo,tracers[i1],tracers[i2],np.arange(LMAX+1))#,l_limber=100)
            if i1!=i2 :
                c_ij[:,i2,i1]=c_ij[:,i1,i2]
    if fname_out!=False :
        np.save(fname_out,c_ij)
    return c_ij
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
Ejemplo n.º 20
0
def test_cls(set_up, t1, t2, bm,
             a1b1, a1b2, a2b1, a2b2, fl):
    cosmo, trcs, lfc, bmk = set_up
    cl = ccl.angular_cl(cosmo, trcs[t1], trcs[t2], lfc['ells']) * lfc[fl]
    el = np.sqrt((bmk[a1b1] * bmk[a2b2] + bmk[a1b2] * bmk[a2b1]) /
                 (2 * lfc['ells'] + 1.))
    assert np.all(np.fabs(cl - bmk[bm]) < 0.1 * el)
Ejemplo n.º 21
0
def getcorrCCL(theta, data, centers):

    Nz, be = np.histogram(data['z'], bins=8, range=(0.05, 0.15))
    z = 0.5 * (be[1:] + be[:-1])

    h = 0.675  # Planck value for h (Hubble parameter)
    Ob = 0.044  # Planck value for Omega_b (Baryon energy density)
    Om = theta[1]  # Planck value for Omega_m (Matter energy density)
    Oc = Om - Ob  # Value for Omega_c (Cold dark matter energy density)
    ns = 0.965  # Scalar index

    cosmo = ccl.Cosmology(Omega_c=Oc,
                          Omega_b=Ob,
                          h=h,
                          sigma8=0.8,
                          n_s=ns,
                          matter_power_spectrum='linear')

    tracer = ccl.NumberCountsTracer(cosmo,
                                    has_rsd=False,
                                    dndz=(z, Nz),
                                    bias=(z, np.ones_like(z)))

    ell = np.arange(1, 7500)  # is this the same as lmax?
    angular_power_spectrum = ccl.angular_cl(cosmo, tracer, tracer, ell)

    th = centers  #np.linspace(0,0.2, num = 15)

    ang_corr_func = ccl.correlation(cosmo, ell, angular_power_spectrum, th)

    return ang_corr_func
Ejemplo n.º 22
0
def test_xi(set_up, corr_method, t1, t2, bm, er, kind, pref):
    cosmo, trcs, bms, ers, fls = set_up
    method, errfac = corr_method

    global T0_CLS
    t0 = time.time()
    cl = ccl.angular_cl(cosmo, trcs[t1], trcs[t2], fls['ells'])
    T0_CLS += (time.time() - t0)

    ell = np.arange(fls['lmax'])
    cli = interp1d(fls['ells'], cl, kind='cubic')(ell)

    global T0
    t0 = time.time()
    xi = ccl.correlation(cosmo,
                         ell,
                         cli,
                         bms['theta'],
                         corr_type=kind,
                         method=method)
    T0 += (time.time() - t0)

    xi *= pref
    assert np.all(np.fabs(xi - bms[bm]) < ers[er] * errfac)

    print("time:", T0)
    print("time cls:", T0_CLS)
Ejemplo n.º 23
0
def getTheories(ccl_cosmo,s,ctracers) :
    theo={}
    for t1i,t2i,ells,_ in s.sortTracers(): 
        cls=ccl.angular_cl(ccl_cosmo,ctracers[t1i],ctracers[t2i],ells)
        theo[(t1i,t2i)]=cls
        theo[(t2i,t1i)]=cls
    return theo
Ejemplo n.º 24
0
 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)
Ejemplo n.º 25
0
def compute_cls(cosmo, tracers_info, ells, outdir):
    # Get the Tracer instaces
    print('Get tracer instances')
    get_tracers_ccl(cosmo, tracers_info)

    cls_ar = np.zeros((len(tracers_info['data_vectors']), ells.size))
    # Get theory Cls
    print('Computing theory Cls')
    for i, dv in enumerate(tracers_info['data_vectors']):
        tracer1 = next(x['tracer'] for x in tracers_info['maps']
                       if x['name'] == dv['tracers'][0])
        tracer2 = next(x['tracer'] for x in tracers_info['maps']
                       if x['name'] == dv['tracers'][1])
        cls = ccl.angular_cl(cosmo, tracer1, tracer2, ells)
        # # Add multiplicative bias to WL
        # type1 = next(x['type'] for x in tracers_info['maps'] if x['name']==dv['tracers'][0])
        # type2 = next(x['type'] for x in tracers_info['maps'] if x['name']==dv['tracers'][1])
        # if type1 == 'wl':
        #     bin = next(x['bin'] for x in tracers_info['maps'] if x['name']==dv['tracers'][0])
        #     m =
        #     cls = (1.+m)*cls
        # if type2 == 'wl':
        #     bin = next(x['bin'] for x in tracers_info['maps'] if x['name']==dv['tracers'][1])
        #     m =
        #     cls = (1.+m)*cls

        fname = os.path.join(outdir, 'cls_{}_{}.npz'.format(*dv['tracers']))
        print('Saving {}'.format(fname))
        np.savez_compressed(fname, cls=cls, ells=ells)
        cls_ar[i] = cls
    return cls_ar
Ejemplo n.º 26
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)
Ejemplo n.º 27
0
 def _get_cl(self, t1, t2, ls, dchi, lnl):
     return ccl.angular_cl(self.cosmo,
                           t1,
                           t2,
                           ls,
                           l_limber=lnl,
                           limber_integration_method='spline',
                           dchi_nonlimber=dchi)
Ejemplo n.º 28
0
def project_Cl(cosmo, tracer, Pk_a_s, ks, a_s, want_plot=False):
    # number of redshifts
    num_zs = Pk_a_s.shape[0]

    # hubble parameter
    h = cosmo._params_init_kwargs['h']

    # change the order cause that's what CCL prefers
    i_sort = np.argsort(a_s)
    a_s = a_s[i_sort]
    Pk_a_s = Pk_a_s[i_sort, :]
    assert num_zs == len(
        a_s), "Different number of input spectra and redshifts"

    # wave numbers
    ells = np.geomspace(2, 1000, 20)
    '''
    # simple power spectrum for testing
    lpk_array = np.log(np.array([ccl.nonlin_matter_power(cosmo, ks*h, a) for a in a_s]))
    cl_tt = ccl.angular_cl(cosmo, tracer, tracer, ells)

    # generating fake data
    Cl_err = cl_tt*np.sqrt(2./(2*ells+1.))
    cov = np.diag(Cl_err**2)
    np.save("data_power/cl_gg_z%4.3f.npy"%a2z(a_s[0]),cl_tt)
    np.save("data_power/ells.npy",ells)
    np.save("data_power/cov_cl_gg_z%4.3f.npy"%a2z(a_s[0]),cov)
    '''

    # Create a Pk2D object, giving log k in Mpc^-1 and pk_arr in Mpc^3
    #lpk_array = np.log(Pk_a_s/h**3)
    #pk_tmp = ccl.Pk2D(a_arr=a_s, lk_arr=np.log(ks*h), pk_arr=lpk_array, is_logp=True)
    pk_tmp = ccl.Pk2D(a_arr=a_s,
                      lk_arr=np.log(ks * h),
                      pk_arr=Pk_a_s / h**3,
                      is_logp=False)

    # Compute power spectra with and without cutoff
    cl_tt_tmp = ccl.angular_cl(cosmo, tracer, tracer, ells, p_of_k_a=pk_tmp)

    if want_plot:
        # plot the power spectra
        plt.plot(np.log(ks * h), lpk_array[-1, :], label="ccl")
        plt.plot(np.log(ks * h), np.log(Pk_a_s[-1, :] / h**3), label="buba")
        plt.legend()
        plt.show()

        # plot the angular power spectra
        plt.plot(ells, 1E4 * cl_tt, 'r-', label='built-in tracer')
        plt.plot(ells, 1E4 * cl_tt_tmp, 'k--', label='custom tracer')
        plt.xscale('log')
        plt.xlabel('$\\ell$', fontsize=14)
        plt.ylabel('$10^4\\times C_\\ell$', fontsize=14)
        plt.legend(loc='upper right', fontsize=12, frameon=False)
        plt.savefig("figs/Cls.png")
        plt.show()

    return ells, cl_tt_tmp
Ejemplo n.º 29
0
    def get_ccl_cl(self, ccl_tr1, ccl_tr2, ell):
        cosmo = self.get_cosmo_ccl()

        pk = self.get_ccl_pk(ccl_tr1, ccl_tr2)
        return ccl.angular_cl(cosmo,
                              ccl_tr1['ccl_tr'],
                              ccl_tr2['ccl_tr'],
                              ell,
                              p_of_k_a=pk)
Ejemplo n.º 30
0
    def get_prediction(self, dic_par):
        theory_out = np.zeros((self.s.size(), ))
        cosmo = self.get_cosmo(dic_par)
        tr = self.get_tracers(cosmo, dic_par)
        for i1, i2, ells, ndx in self.s.sortTracers():
            cls = ccl.angular_cl(cosmo, tr[i1], tr[i2], ells)
            theory_out[ndx] = cls

        return theory_out
Ejemplo n.º 31
0
def test_cls_spline(set_up, t1, t2, bm, a1b1, a1b2, a2b1, a2b2, fl):
    cosmo, trcs, lfc, bmk = set_up
    cl = ccl.angular_cl(cosmo,
                        trcs[t1],
                        trcs[t2],
                        lfc['ells'],
                        limber_integration_method='spline') * lfc[fl]
    el = np.sqrt((bmk[a1b1] * bmk[a2b2] + bmk[a1b2] * bmk[a2b1]) /
                 (2 * lfc['ells'] + 1.))
    assert np.all(np.fabs(cl - bmk[bm]) < 0.2 * el)