Beispiel #1
0
def check_cls(cosmo):
    """
    Check that cls functions can be run.
    """
    # Number density input
    z = np.linspace(0., 1., 200)
    n = np.ones(z.shape)
    
    # Bias input
    b = np.sqrt(1. + z)
    
    # ell range input
    ell_scl = 4
    ell_lst = [2, 3, 4, 5, 6, 7, 8, 9]
    ell_arr = np.arange(2, 10)
    
    # 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))
    nc1 = ccl.ClTracerNumberCounts(cosmo, False, False, n=(z,n), bias=(z,b))
    nc2 = ccl.ClTracerNumberCounts(cosmo, True, False, n=(z,n), bias=(z,b))
    nc3 = ccl.ClTracerNumberCounts(cosmo, True, True, n=(z,n), bias=(z,b),
                                   mag_bias=(z,b))
    cmbl=ccl.ClTracerCMBLensing(cosmo,1100.)
    
    # Check valid ell input is accepted
    assert_( all_finite(ccl.angular_cl(cosmo, lens1, lens1, ell_scl)) )
    assert_( all_finite(ccl.angular_cl(cosmo, lens1, lens1, ell_lst)) )
    assert_( all_finite(ccl.angular_cl(cosmo, lens1, lens1, ell_arr)) )
    
    assert_( all_finite(ccl.angular_cl(cosmo, nc1, nc1, ell_scl)) )
    assert_( all_finite(ccl.angular_cl(cosmo, nc1, nc1, ell_lst)) )
    assert_( all_finite(ccl.angular_cl(cosmo, nc1, nc1, ell_arr)) )

    assert_( all_finite(ccl.angular_cl(cosmo, cmbl, cmbl, ell_arr)) )
    
    # Check various cross-correlation combinations
    assert_( all_finite(ccl.angular_cl(cosmo, lens1, lens2, ell_arr)) )
    assert_( all_finite(ccl.angular_cl(cosmo, lens1, nc1, ell_arr)) )
    assert_( all_finite(ccl.angular_cl(cosmo, lens1, nc2, ell_arr)) )
    assert_( all_finite(ccl.angular_cl(cosmo, lens1, nc3, ell_arr)) )
    assert_( all_finite(ccl.angular_cl(cosmo, lens1, cmbl, ell_arr)) )
    assert_( all_finite(ccl.angular_cl(cosmo, lens2, nc1, ell_arr)) )
    assert_( all_finite(ccl.angular_cl(cosmo, lens2, nc2, ell_arr)) )
    assert_( all_finite(ccl.angular_cl(cosmo, lens2, nc3, ell_arr)) )
    assert_( all_finite(ccl.angular_cl(cosmo, lens2, cmbl, ell_arr)) )
    assert_( all_finite(ccl.angular_cl(cosmo, nc1, nc2, ell_arr)) )
    assert_( all_finite(ccl.angular_cl(cosmo, nc1, nc3, ell_arr)) )
    assert_( all_finite(ccl.angular_cl(cosmo, nc1, cmbl, ell_arr)) )
    assert_( all_finite(ccl.angular_cl(cosmo, nc2, nc3, ell_arr)) )
    assert_( all_finite(ccl.angular_cl(cosmo, nc2, cmbl, ell_arr)) )
    assert_( all_finite(ccl.angular_cl(cosmo, nc3, cmbl, ell_arr)) )
    
    # Check that reversing order of ClTracer inputs works
    assert_( all_finite(ccl.angular_cl(cosmo, nc1, lens1, ell_arr)) )
    assert_( all_finite(ccl.angular_cl(cosmo, nc1, lens2, ell_arr)) )
Beispiel #2
0
    def get_tracers(self, cosmo, dic_par):
        tr_out = []
        has_rsd = dic_par.get('has_rds', False)
        has_magnification = dic_par.get('has_magnification', False)
        for (tr_index, thistracer) in enumerate(self.s.tracers):
            if thistracer.type.__contains__('point'):
                try:
                    z_b_arr = dic_par[thistracer.exp_sample + '_z_b']
                    b_b_arr = dic_par[thistracer.exp_sample + '_b_b']
                except:
                    raise ValueError("bias needed for each tracer")

                if 'zshift_bin' + str(tr_index) in dic_par:
                    zbins = thistracer.z + dic_par['zshift_bin' +
                                                   str(tr_index)]
                else:
                    zbins = thistracer.z
                bf = interp1d(
                    z_b_arr, b_b_arr, kind='nearest'
                )  #Assuming linear interpolation. Decide on extrapolation.
                b_arr = bf(
                    thistracer.z)  #Assuming that tracers have this attribute
                tr_out.append(
                    ccl.ClTracerNumberCounts(cosmo,
                                             dic_par['has_rsd'],
                                             dic_par['has_magnification'],
                                             z=thistracer.z,
                                             n=(zbins, thistracer.Nz),
                                             bias=(z_b_arr, b_b_arr)))
            else:
                raise ValueError("Only \"point\" tracers supported")
        return tr_out
Beispiel #3
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_)
Beispiel #4
0
    def render(self, cosmo, params, systematics=None):
        """
        Render a source by applying systematics.

        Parameters
        ----------
        cosmo : pyccl.Cosmology
            A pyccl.Cosmology object.
        params : dict
            A dictionary mapping parameter names to their current values.
        systematics : dict
            A dictionary mapping systematic names to their objects. The
            default of `None` corresponds to no systematics.
        """
        systematics = systematics or {}

        self.z_ = self._z_orig.copy()
        self.nz_ = self._nz_orig.copy()
        self.scale_ = self.scale
        self.bias_ = np.ones_like(self.z_) * params[self.bias]

        if self.has_magnification:
            self.mag_bias_ = np.ones_like(self.z_) * params[self.mag_bias]

        for systematic in self.systematics:
            systematics[systematic].apply(cosmo, params, self)

        if self.has_magnification:
            tracer = ccl.ClTracerNumberCounts(cosmo,
                                              has_rsd=self.has_rsd,
                                              has_magnification=True,
                                              n=(self.z_, self.nz_),
                                              bias=(self.z_, self.bias_),
                                              mag_bias=(self.z_,
                                                        self.mag_bias_))
        else:
            tracer = ccl.ClTracerNumberCounts(cosmo,
                                              has_rsd=self.has_rsd,
                                              has_magnification=False,
                                              n=(self.z_, self.nz_),
                                              bias=(self.z_, self.bias_))
        self.tracer_ = tracer
Beispiel #5
0
def sacc2ccl_tracer(t):
    if len(t.z) != 1:
        toret = ccl.ClTracerNumberCounts(ccl_cosmo,
                                         has_rsd=False,
                                         has_magnification=False,
                                         n=(t.z, t.Nz),
                                         bias=(t.z, t.extraColumn('b')),
                                         mag_bias=(t.z, np.zeros(len(t.z))))
    else:
        toret = None
    return toret
Beispiel #6
0
    def get_tracers(self, cosmo, dic_par):
        tr_out = []
        for tr in self.s.tracers:
            if tr.type == 'point':
                try:
                    z_b_arr = dic_par[tr.exp_sample + '_z_b']
                    b_b_arr = dic_par[tr.exp_sample + '_b_b']
                except:
                    raise ValueError("bias needed for each tracer")

                bf = interp1d(
                    z_b_arr, b_b_arr, kind='nearest'
                )  #Assuming linear interpolation. Decide on extrapolation.
                b_arr = bf(tr.z)  #Assuming that tracers have this attribute
                tr_out.append(
                    ccl.ClTracerNumberCounts(cosmo, False, False, tr.z, tr.Nz,
                                             tr.z, b_arr))
            else:
                raise ValueError("Only \"point\" tracers supported")

        return tr_out
Beispiel #7
0
def getTracers(cosmo, dic_par):
    #Create SACC tracers and corresponding CCL tracers
    tracers = []
    cltracers = []
    for i, z in enumerate(zbins):
        zar = np.arange(z - 3 * zbin_size, z + 3 * zbin_size, 0.001)
        Nz = np.exp(-(z - zar)**2 / (2 * zbin_size**2))
        T = sacc.Tracer("des_gals_" + str(i),
                        "point",
                        zar,
                        Nz,
                        exp_sample="gals",
                        Nz_sigma_logmean=0.01,
                        Nz_sigma_logwidth=0.1)
        bias = np.ones_like(zar)
        T.addColumns({'b': bias})
        tracers.append(T)
        cltracers.append(
            ccl.ClTracerNumberCounts(cosmo, dic_par['has_rsd'],
                                     dic_par['has_magnification'], zar, Nz,
                                     zar, bias))
    return tracers, cltracers
Beispiel #8
0
    plt.plot(zarr_dlo_n12, nzarr_dlo_n12, 'r-')
    plt.plot(zarr_dlo_n12b, nzarr_dlo_n12b, 'r--')
    plt.plot(zarr_dlo_g16, nzarr_dlo_g16, 'r-.')
    plt.plot(zarr_qso_n12, nzarr_qso_n12, 'b-')
    plt.plot(zarr_qso_n12b, nzarr_qso_n12b, 'b--')
    plt.plot(zarr_qso_g16, nzarr_qso_g16, 'b-.')
    plt.plot(zarr_qsu, nzarr_qsu, 'g-')

if not os.path.isfile(outdir + "cls_th.txt"):
    cosmo = ccl.Cosmology(Omega_c=0.27,
                          Omega_b=0.045,
                          h=0.69,
                          sigma8=0.83,
                          n_s=0.96)
    clt_dlo_n12 = ccl.ClTracerNumberCounts(cosmo, False, False,
                                           (zarr_dlo_n12, nzarr_dlo_n12),
                                           (zarr_dlo_n12, bzarr_dlo_n12))
    clt_qso_n12 = ccl.ClTracerNumberCounts(cosmo, False, False,
                                           (zarr_qso_n12, nzarr_qso_n12),
                                           (zarr_qso_n12, bzarr_qso_n12))
    clt_dlo_n12b = ccl.ClTracerNumberCounts(cosmo, False, False,
                                            (zarr_dlo_n12b, nzarr_dlo_n12b),
                                            (zarr_dlo_n12b, bzarr_dlo_n12b))
    clt_qso_n12b = ccl.ClTracerNumberCounts(cosmo, False, False,
                                            (zarr_qso_n12b, nzarr_qso_n12b),
                                            (zarr_qso_n12b, bzarr_qso_n12b))
    clt_dlo_g16 = ccl.ClTracerNumberCounts(cosmo, False, False,
                                           (zarr_dlo_g16, nzarr_dlo_g16),
                                           (zarr_dlo_g16, bzarr_dlo_g16))
    clt_qso_g16 = ccl.ClTracerNumberCounts(cosmo, False, False,
                                           (zarr_qso_g16, nzarr_qso_g16),
Beispiel #9
0
def calc_sn(z_phot, z_bins, hsc_z_phot, hsc_ids, matched_pdf_ids, matched_pdfs, n_z, ell, area_in_sr,
            plot_cls=True, hsc_z_mc=None, nz_mc=False,
            save_plots=False, dont_show_plots=False, filetag=None, outDir=None):
    print('-----------------------------------------\nRunning calc_sn for %s bins ... '%(len(z_phot)-1))
    if nz_mc:
        if hsc_z_mc is None:
            raise ValueError('Need either the N(z) or z_mc to estimate dn/dz.')

    # set up the bins
    z_edges_all = [min(z_bins)] + list(z_phot) + [max(z_bins)]   # cover the entire range, even outside the target bins

    target_bins, target_bin_ends = get_bins_ends(z_bin_array=z_phot)
    all_bins, all_bin_ends = get_bins_ends(z_bin_array=z_edges_all)

    print('Target bins: %s'%(target_bins))
    print('All bins: %s\n'%(all_bins))

    # get dn/dz
    dn_dz, num_gals = get_dn_dz(z_edges=z_edges_all, hsc_z_phot=hsc_z_phot,
                                hsc_ids=hsc_ids, matched_pdf_ids=matched_pdf_ids, matched_pdfs=matched_pdfs,
                                nz_mc=nz_mc, hsc_z_mc=hsc_z_mc, z_bins=z_bins)
    # plot the dn/dz for the different bins
    fontsize = 20
    plt.clf()
    for key in dn_dz:
        if key in target_bin_ends:
            plt.plot(z_bins, dn_dz[key], lw=4, label=r'** dn_dz: $%s$: %s galaxies'%(key, num_gals[key]))
        else:
            plt.plot(z_bins, dn_dz[key], lw=4, label=r'   dn_dz: $%s$: %s galaxies'%(key, num_gals[key]))
    # plot n(z) for reference
    plt.plot(z_bins, n_z, 'k-.', label='   n_z', alpha=0.7)
    # plot bin edges
    ymin, ymax = plt.gca().get_ylim()
    for key in target_bin_ends:
        for z_edge in target_bin_ends[key]:
            plt.plot([z_edge, z_edge], [0, ymax], 'k:', alpha=0.7)
    plt.title(filetag, fontsize=fontsize)
    plt.gca().tick_params(axis='both', labelsize=fontsize-2)
    plt.xlabel('z', fontsize=fontsize)
    plt.gcf().set_size_inches(10, 6)
    plt.legend(bbox_to_anchor=(1,1), fontsize=fontsize-5)
    if save_plots:
        filename = '%s_dndz_%sbins.png'%(filetag, len(z_phot)-1)
        plt.savefig('%s/%s'%(outDir, filename), format='png', bbox_inches='tight')
        print('\n## Saved plot: %s\n'%filename)
    if dont_show_plots:
        plt.close('all')
    else:
        plt.show()

    # set up ccl
    cosmo_fid= ccl.Cosmology(Omega_c=0.25, Omega_b=0.05, h=0.7, sigma8=0.8, n_s=0.96)
    bias = 1 + 0.84*z_bins

    # calculate the signal matrix
    print('Calculating the signal matrix ... ')
    S = np.zeros(shape=(len(ell), len(all_bins), len(all_bins)))
    for i, bin1_key in enumerate(all_bins):
        nc_bin1 = ccl.ClTracerNumberCounts(cosmo_fid, has_rsd=False, has_magnification=False,
                                            n=dn_dz[bin1_key], bias=bias, z=z_bins)
        for j, bin2_key in enumerate(all_bins):
            nc_bin2= ccl.ClTracerNumberCounts(cosmo_fid, has_rsd=False, has_magnification=False,
                                                  n=dn_dz[bin2_key], bias=bias, z=z_bins)
            S[:, i, j] = ccl.angular_cl(cosmo_fid, nc_bin1, nc_bin2, ell)

    # calculate the noise matrix
    print('Calculating the noise matrix ... ')
    N = np.zeros(shape=(len(ell), len(all_bins), len(all_bins)))
    for i, bin_key in enumerate(all_bins):
        zmin, zmax = all_bin_ends[bin_key]
        n_obj = len(np.where((hsc_z_phot > zmin) & (hsc_z_phot < zmax))[0])
        print('%s objects in %s'%(n_obj, bin_key))
        num_density = get_surface_number_density(n_objs=n_obj, area_in_sr=area_in_sr)
        N[:, i, i] = 1./num_density

    ###############################################################################################
    # plot all cls
    if plot_cls:
        plt.clf()
        nrow, ncol = 2, 2
        fig, axes = plt.subplots(nrow, ncol)
        # plot cross spectra
        for i, bin1_key in enumerate(all_bins):
            # plot auto spectrum and noise
            p = axes[0, 0].plot(ell, S[:, i, i], 'o-', label=r'$%s$'%(bin1_key))
            axes[1, 0].plot(ell, N[:, i, i], 'o:', color= p[0].get_color(), label='$%s$'%(bin1_key))
            # plot cross spectrum
            for j, bin2_key in enumerate(all_bins):
                if i!=j: # cross spectrum
                    if j>i:
                        p = axes[0, 1].plot(ell, S[:, i, j], 'o-', label=r'$%s$ - $%s$'%(bin1_key, bin2_key))
                        axes[1, 1].plot(ell, N[:, i, j], 'o:', color=p[0].get_color(), label='$%s$ - $%s$'%(bin1_key, bin2_key))
                    else:
                        # check to ensure that we really dont need to plot j, i entry.
                        if (abs(S[:, i, j]-S[:, j, i])>1e-5).any():
                            print('Somethings wrong. Signal matrix isnt symmetric: S[:, i, j]-S[:, j, i]:\n%s'%(S[:, i, j]-S[:, j, i]))
                        if (abs(N[:, i, j]-N[:, j, i])>1e-5).any():
                            print('Somethings wrong. Noise matrix isnt symmetric: N[:, i, j]-N[:, j, i]:\n%s'%(N[:, i, j]-N[:, j, i]))
        for row in range(nrow):
            for col in range(ncol):
                axes[1, col].set_xlabel('$\ell$', fontsize=fontsize)
                axes[row, col].ticklabel_format(style='sci',scilimits=(-3,4),axis='y')
                axes[row, col].set_xscale('log')
                axes[0, col].set_yscale('log')
                axes[row, col].tick_params(axis='x', labelsize=fontsize-2)
                axes[row, col].tick_params(axis='y', labelsize=fontsize-2)
        axes[0, 0].set_ylabel('Auto C$_\ell$', fontsize=fontsize)
        axes[1, 0].set_ylabel('Auto Noise', fontsize=fontsize)
        axes[0, 1].set_ylabel('Cross C$_\ell$', fontsize=fontsize)
        axes[1, 1].set_ylabel('Cross Noise', fontsize=fontsize)
        axes[0, 0].legend(bbox_to_anchor=(-0.15,1), fontsize=fontsize-4)
        axes[0, 1].legend(bbox_to_anchor=(1,1), fontsize=fontsize-4)
        plt.suptitle(filetag, fontsize=fontsize)
        plt.gcf().set_size_inches(20, 10)
        if save_plots:
            filename = '%s_%sbins_spectra.png'%(filetag, len(z_phot)-1)
            plt.savefig('%s/%s'%(outDir, filename), format='png', bbox_inches='tight')
            print('\n## Saved plot: %s\n'%filename)
        if dont_show_plots:
            plt.close('all')
        else:
            plt.show()

    ###############################################################################################
    # (2*ell+1) Tr(S_ell . C_ell^-1 . S_ell . C_ell^-1)
    C = S+N
    sn_sq = 0
    for j in range(len(ell)):
        inv = np.linalg.inv(C[j, :, :])
        mat = np.dot(S[j, :, :], inv)
        mat = np.dot(inv, mat)
        mat = np.dot(S[j, :, :], mat)
        sn_sq += (2*ell[j]+1)*np.trace(mat)

    fsky = area_in_sr/(4*np.pi)  # total sky area: 4pi Sr
    print('\n## fsky: %.2e\n'%fsky)
    return np.sqrt((fsky/2.)*sn_sq)
Beispiel #10
0
#This just generates the theory power spectra
if not os.path.isfile('cls_flat.txt'):
    import pyccl as ccl
    z = np.linspace(0.2, 1.2, 256)
    pz = np.exp(-((z - 0.7) / 0.1)**2)
    bz = np.ones_like(z)
    plt.figure()
    plt.plot(z, pz)
    plt.xlabel('$z$', fontsize=16)
    plt.ylabel('$p(z)$', fontsize=16)
    cosmo = ccl.Cosmology(Omega_c=0.27,
                          Omega_b=0.045,
                          h=0.67,
                          A_s=2.1e-9,
                          n_s=0.96)
    clust = ccl.ClTracerNumberCounts(cosmo, False, False, z=z, n=pz, bias=bz)
    lens = ccl.ClTracerLensing(cosmo, False, z=z, n=pz)
    ell = np.arange(20000)
    cltt = ccl.angular_cl(cosmo, clust, clust, ell)
    clte = ccl.angular_cl(cosmo, clust, lens, ell)
    clee = ccl.angular_cl(cosmo, lens, lens, ell)
    clbb = np.zeros_like(clee)

    np.savetxt("cls_flat.txt", np.transpose([ell, cltt, clee, clbb, clte]))
ell, cltt, clee, clbb, clte = np.loadtxt("cls_flat.txt", unpack=True)
cltt[0] = 0
clee[0] = 0
clbb[0] = 0
clte[0] = 0
if plotres:
    plt.figure()
def check_cls_nu(cosmo):
    """
    Check that cls functions can be run.
    """
    # Number density input
    z = np.linspace(0., 1., 200)
    n = np.exp(-((z-0.5)/0.1)**2)
    
    # Bias input
    b = np.sqrt(1. + z)
    
    # ell range input
    ell_scl = 4
    ell_lst = [2, 3, 4, 5, 6, 7, 8, 9]
    ell_arr = np.arange(2, 10)
    
    # Check if power spectrum type is valid for CMB
    cmb_ok = True
    if cosmo.configuration.matter_power_spectrum_method \
        == ccl.core.matter_power_spectrum_types['emu']: cmb_ok = False
    
    # 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))
    nc1 = ccl.ClTracerNumberCounts(cosmo, False, False, n=(z,n), bias=(z,b))
    
    # Check that for massive neutrinos including rsd raises an error (not yet implemented)
    assert_raises(RuntimeError, ccl.ClTracerNumberCounts, cosmo, True, False, n=(z,n), bias=(z,b))

    cmbl=ccl.ClTracerCMBLensing(cosmo,1100.)
    
    # Check valid ell input is accepted
    assert_( all_finite(ccl.angular_cl(cosmo, lens1, lens1, ell_scl)) )
    assert_( all_finite(ccl.angular_cl(cosmo, lens1, lens1, ell_lst)) )
    assert_( all_finite(ccl.angular_cl(cosmo, lens1, lens1, ell_arr)) )
    
    assert_( all_finite(ccl.angular_cl(cosmo, nc1, nc1, ell_scl)) )
    assert_( all_finite(ccl.angular_cl(cosmo, nc1, nc1, ell_lst)) )
    assert_( all_finite(ccl.angular_cl(cosmo, nc1, nc1, ell_arr)) )

    if cmb_ok: assert_( all_finite(ccl.angular_cl(cosmo, cmbl, cmbl, ell_arr)) )
    
    # Check various cross-correlation combinations
    assert_( all_finite(ccl.angular_cl(cosmo, lens1, lens2, ell_arr)) )
    assert_( all_finite(ccl.angular_cl(cosmo, lens1, nc1, ell_arr)) )
    if cmb_ok: assert_( all_finite(ccl.angular_cl(cosmo, lens1, cmbl, ell_arr)) )
    assert_( all_finite(ccl.angular_cl(cosmo, lens2, nc1, ell_arr)) )
    if cmb_ok: assert_( all_finite(ccl.angular_cl(cosmo, lens2, cmbl, ell_arr)) )
    if cmb_ok: assert_( all_finite(ccl.angular_cl(cosmo, nc1, cmbl, ell_arr)) )
    
    # Check that reversing order of ClTracer inputs works
    assert_( all_finite(ccl.angular_cl(cosmo, nc1, lens1, ell_arr)) )
    assert_( all_finite(ccl.angular_cl(cosmo, nc1, lens2, ell_arr)) )
    
    # Check get_internal_function()
    a_scl = 0.5
    a_lst = [0.2, 0.4, 0.6, 0.8, 1.]
    a_arr = np.linspace(0.2, 1., 5)
    assert_( all_finite(nc1.get_internal_function(cosmo, 'dndz', a_scl)) )
    assert_( all_finite(nc1.get_internal_function(cosmo, 'dndz', a_lst)) )
    assert_( all_finite(nc1.get_internal_function(cosmo, 'dndz', a_arr)) )
    
    # Check that invalid options raise errors
    assert_raises(KeyError, nc1.get_internal_function, cosmo, 'x', a_arr)
    assert_raises(ValueError, ccl.ClTracerNumberCounts, cosmo, True, True, 
                  n=(z,n), bias=(z,b))
    assert_raises(KeyError, ccl.ClTracer, cosmo, 'x', True, True, 
                  n=(z,n), bias=(z,b))
    assert_raises(ValueError, ccl.ClTracerLensing, cosmo, 
                  has_intrinsic_alignment=True, n=(z,n), bias_ia=(z,n))
    assert_no_warnings(ccl.cls._cltracer_obj, nc1)
    assert_no_warnings(ccl.cls._cltracer_obj, nc1.cltracer)
    assert_raises(TypeError, ccl.cls._cltracer_obj, None)
def check_cls(cosmo):
    """
    Check that cls functions can be run.
    """
    # Number density input
    z = np.linspace(0., 1., 200)
    n = np.exp(-((z-0.5)/0.1)**2)
    
    # Bias input
    b = np.sqrt(1. + z)
    
    # ell range input
    ell_scl = 4
    ell_lst = [2, 3, 4, 5, 6, 7, 8, 9]
    ell_arr = np.arange(2, 10)
    
    # Check if power spectrum type is valid for CMB
    cmb_ok = True
    if cosmo.configuration.matter_power_spectrum_method \
        == ccl.core.matter_power_spectrum_types['emu']: cmb_ok = False
    
    # 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))
    nc1 = ccl.ClTracerNumberCounts(cosmo, False, False, n=(z,n), bias=(z,b))
    nc2 = ccl.ClTracerNumberCounts(cosmo, True, False, n=(z,n), bias=(z,b))
    nc3 = ccl.ClTracerNumberCounts(cosmo, True, True, n=(z,n), bias=(z,b),
                                   mag_bias=(z,b))
    cmbl=ccl.ClTracerCMBLensing(cosmo,1100.)
    
    # Check valid ell input is accepted
    assert_( all_finite(ccl.angular_cl(cosmo, lens1, lens1, ell_scl)) )
    assert_( all_finite(ccl.angular_cl(cosmo, lens1, lens1, ell_lst)) )
    assert_( all_finite(ccl.angular_cl(cosmo, lens1, lens1, ell_arr)) )
    
    assert_( all_finite(ccl.angular_cl(cosmo, nc1, nc1, ell_scl)) )
    assert_( all_finite(ccl.angular_cl(cosmo, nc1, nc1, ell_lst)) )
    assert_( all_finite(ccl.angular_cl(cosmo, nc1, nc1, ell_arr)) )

    if cmb_ok: assert_( all_finite(ccl.angular_cl(cosmo, cmbl, cmbl, ell_arr)) )

    # Check non-limber calculations
    assert_( all_finite(ccl.angular_cl(cosmo, nc1, nc1, ell_arr, l_limber=20, non_limber_method="native")))
    assert_( all_finite(ccl.angular_cl(cosmo, nc1, nc1, ell_arr, l_limber=20, non_limber_method="angpow")))
    
    # Check various cross-correlation combinations
    assert_( all_finite(ccl.angular_cl(cosmo, lens1, lens2, ell_arr)) )
    assert_( all_finite(ccl.angular_cl(cosmo, lens1, nc1, ell_arr)) )
    assert_( all_finite(ccl.angular_cl(cosmo, lens1, nc2, ell_arr)) )
    assert_( all_finite(ccl.angular_cl(cosmo, lens1, nc3, ell_arr)) )
    if cmb_ok: assert_( all_finite(ccl.angular_cl(cosmo, lens1, cmbl, ell_arr)) )
    assert_( all_finite(ccl.angular_cl(cosmo, lens2, nc1, ell_arr)) )
    assert_( all_finite(ccl.angular_cl(cosmo, lens2, nc2, ell_arr)) )
    assert_( all_finite(ccl.angular_cl(cosmo, lens2, nc3, ell_arr)) )
    if cmb_ok: assert_( all_finite(ccl.angular_cl(cosmo, lens2, cmbl, ell_arr)) )
    assert_( all_finite(ccl.angular_cl(cosmo, nc1, nc2, ell_arr)) )
    assert_( all_finite(ccl.angular_cl(cosmo, nc1, nc3, ell_arr)) )
    if cmb_ok: assert_( all_finite(ccl.angular_cl(cosmo, nc1, cmbl, ell_arr)) )
    assert_( all_finite(ccl.angular_cl(cosmo, nc2, nc3, ell_arr)) )
    if cmb_ok: assert_( all_finite(ccl.angular_cl(cosmo, nc2, cmbl, ell_arr)) )
    if cmb_ok: assert_( all_finite(ccl.angular_cl(cosmo, nc3, cmbl, ell_arr)) )
    
    # Check that reversing order of ClTracer inputs works
    assert_( all_finite(ccl.angular_cl(cosmo, nc1, lens1, ell_arr)) )
    assert_( all_finite(ccl.angular_cl(cosmo, nc1, lens2, ell_arr)) )

    # Wrong non limber method
    assert_raises(KeyError, ccl.angular_cl, cosmo, lens1, lens1, ell_scl, non_limber_method='xx')
Beispiel #13
0
    return zarr, pzarr


nz, bn = np.histogram(data_dla['z_abs'], range=[0, 7], bins=50)
zarr_dlo, nzarr_dlo = get_nz_oversample(bn, nz, 256)
bzarr_dlo = bdla * np.ones_like(zarr_dlo)
nz, bins = np.histogram(data_dla['zqso'], range=[0, 7], bins=50)
zarr_qso, nzarr_qso = get_nz_oversample(bn, nz, 256)
bzarr_qso = bqso * np.ones_like(zarr_qso)

cosmo = ccl.Cosmology(Omega_c=0.27,
                      Omega_b=0.045,
                      h=0.69,
                      sigma8=0.83,
                      n_s=0.96)
clt_dlo = ccl.ClTracerNumberCounts(cosmo, False, False, (zarr_dlo, nzarr_dlo),
                                   (zarr_dlo, bzarr_dlo))
clt_qso = ccl.ClTracerNumberCounts(cosmo, False, False, (zarr_qso, nzarr_qso),
                                   (zarr_qso, bzarr_qso))
clt_cmbl = ccl.ClTracerCMBLensing(cosmo, z_source=1100.)


def get_fisher(xp):
    ll = np.arange(xp.lmin, xp.lmax)
    cl_dd = ccl.angular_cl(cosmo, clt_dlo, clt_dlo, ll)  #,l_limber=-1)
    cl_dq = ccl.angular_cl(cosmo, clt_dlo, clt_qso, ll)  #,l_limber=-1)
    cl_dc = ccl.angular_cl(cosmo, clt_dlo, clt_cmbl, ll)  #,l_limber=-1)
    cl_qq = ccl.angular_cl(cosmo, clt_qso, clt_qso, ll)  #,l_limber=-1)
    cl_qc = ccl.angular_cl(cosmo, clt_qso, clt_cmbl, ll)  #,l_limber=-1)
    cl_cc = ccl.angular_cl(cosmo, clt_cmbl, clt_cmbl, ll)  #,l_limber=-1)
    cl_aa = cl_dd + 2 * cl_dq + cl_qq
    cl_aq = cl_dq + cl_qq
Beispiel #14
0
                            h=0.69,
                            sigma8=0.83,
                            n_s=0.96)
cosmo = ccl.Cosmology(parameters)
lens = ccl.ClTracerCMBLensing(cosmo)

#use ccl to predict cls
bias_qso = np.ones(rdshift.size)
bias_dla = np.ones(rdshift.size)

b = nmt.NmtBin(2048, nlb=bsize)
ell_arr = b.get_effective_ells()

source_dla = ccl.ClTracerNumberCounts(cosmo,
                                      False,
                                      False,
                                      z=rdshift,
                                      n=n_dla,
                                      bias=bias_dla)
theory_dla = ccl.angular_cl(cosmo, lens, source_dla, ell_arr, l_limber=-1)

source_qso = ccl.ClTracerNumberCounts(cosmo,
                                      False,
                                      False,
                                      z=rdshift,
                                      n=n_qso,
                                      bias=bias_qso)
theory_qso = ccl.angular_cl(cosmo, lens, source_qso, ell_arr, l_limber=-1)

#import precalculated power spectra

if args.nsim == None:
Beispiel #15
0
    return theo

def getTheoryVec(s, cls_theory):
    vec=np.zeros((s.size(),))
    for t1i,t2i,ells,ndx in s.sortTracers():
        vec[ndx]=cls_theory[(t1i,t2i)]
    return sacc.MeanVec(vec)
print 'Setting up cosmology'
cosmo = ccl.Cosmology(ccl.Parameters(Omega_c=0.266,Omega_b=0.049,h=hhub,sigma8=0.8,n_s=0.96,),matter_power_spectrum='linear',transfer_function='eisenstein_hu')

#Compute grid scale
zmax=2.5
ngrid=3072
a_grid=2*ccl.comoving_radial_distance(cosmo,1./(1+zmax))*(1+2./ngrid)/ngrid*hhub
print "Grid smoothing : %.3lf Mpc/h"%a_grid

print 'Reading SACC file'
#SACC File with the N(z) to analyze
binning_sacc = sacc.SACC.loadFromHDF('../test/catalog0.sacc')
#Bias file (it can also be included in the SACC file in the line before)
bias_tab = astropy.table.Table.read('../test/bz_lsst.txt',format='ascii')
tracers = binning_sacc.tracers
print 'Got ',len(tracers),' tracers'
cltracers=[ccl.ClTracerNumberCounts(cosmo,False,False,n=(t.z,t.Nz),bias=(bias_tab['col1'],bias_tab['col2']),r_smooth=0.5*a_grid) for t in tracers]
print 'Cl tracers ready'
theories = getTheories(cosmo,binning_sacc,cltracers)
mean=getTheoryVec(binning_sacc,theories)
csacc=sacc.SACC(tracers,binning_sacc.binning,mean)
csacc.printInfo()
csacc.saveToHDF('theory.sacc',save_precision=False)