def test_power_mu_sigma_sigma8norm(tf): cosmo = ccl.Cosmology( Omega_c=0.27, Omega_b=0.045, h=0.67, sigma8=0.8, n_s=0.96, transfer_function=tf) cosmo_musig = ccl.Cosmology( Omega_c=0.27, Omega_b=0.045, h=0.67, sigma8=0.8, n_s=0.96, transfer_function=tf, mu_0=0.1, sigma_0=0.2) # make sure sigma8 is correct assert np.allclose(ccl.sigma8(cosmo_musig), 0.8) if tf != 'boltzmann_isitgr': # make sure P(k) ratio is right a = 0.8 gfac = ( ccl.growth_factor(cosmo, a) / ccl.growth_factor(cosmo_musig, a))**2 pk_rat = ( ccl.linear_matter_power(cosmo, 1e-4, a) / ccl.linear_matter_power(cosmo_musig, 1e-4, a)) assert np.allclose(pk_rat, gfac) with mock.patch.dict(sys.modules, {'isitgr': None}): with assert_raises(ImportError): get_isitgr_pk_lin(cosmo) # Importing ccl without isitgr is fine. No ImportError triggered. with mock.patch.dict(sys.modules, {'isitgr': None}): reload(ccl.boltzmann)
def test_camb_class_consistent_smoke(kwargs=None, pkerr=1e-3): kwargs = kwargs or {} print('kwargs:', kwargs) c_camb = ccl.Cosmology(Omega_c=0.25, Omega_b=0.05, h=0.7, n_s=0.95, A_s=2e-9, transfer_function='boltzmann_camb', **kwargs) c_class = ccl.Cosmology(Omega_c=0.25, Omega_b=0.05, h=0.7, n_s=0.95, A_s=2e-9, transfer_function='boltzmann_class', **kwargs) rel_sigma8 = np.abs(ccl.sigma8(c_camb) / ccl.sigma8(c_class) - 1) a = 0.845 k = np.logspace(-3, 1, 100) pk_camb = ccl.linear_matter_power(c_camb, k, a) pk_class = ccl.linear_matter_power(c_class, k, a) rel_pk = np.max(np.abs(pk_camb / pk_class - 1)) print('rel err pk:', rel_pk) print('rel err sigma8:', rel_sigma8) assert rel_sigma8 < 3e-3 assert rel_pk < pkerr
def test_power_sigma8norm_norms_consistent(tf): # make a cosmo with A_s cosmo = ccl.Cosmology(Omega_c=0.27, Omega_b=0.045, h=0.67, A_s=2e-9, n_s=0.96, transfer_function=tf) sigma8 = ccl.sigma8(cosmo) # remake same but now give sigma8 cosmo_s8 = ccl.Cosmology(Omega_c=0.27, Omega_b=0.045, h=0.67, sigma8=sigma8, n_s=0.96, transfer_function=tf) # make sure they come out the same-ish assert np.allclose(ccl.sigma8(cosmo), ccl.sigma8(cosmo_s8)) # and that the power spectra look right a = 0.8 gfac = (ccl.growth_factor(cosmo, a) / ccl.growth_factor(cosmo_s8, a))**2 pk_rat = (ccl.linear_matter_power(cosmo, 1e-4, a) / ccl.linear_matter_power(cosmo_s8, 1e-4, a)) assert np.allclose(pk_rat, gfac)
def test_camb_de_model(): """Check that the dark energy model for CAMB has been properly defined.""" with pytest.raises(ValueError): cosmo = ccl.CosmologyVanillaLCDM( transfer_function='boltzmann_camb', extra_parameters={"camb": { "dark_energy_model": "pf" }}) ccl.linear_matter_power(cosmo, 1, 1) """Check that w is not less than -1, if the chosen dark energy model for CAMB is fluid.""" with pytest.raises(ValueError): cosmo = ccl.CosmologyVanillaLCDM(transfer_function='boltzmann_camb', w0=-1, wa=-1) ccl.linear_matter_power(cosmo, 1, 1) """Check that ppf is running smoothly.""" cosmo = ccl.CosmologyVanillaLCDM( transfer_function='boltzmann_camb', w0=-1, wa=-1, extra_parameters={"camb": { "dark_energy_model": "ppf" }}) assert np.isfinite(ccl.linear_matter_power(cosmo, 1, 1))
def test_transfer_matter_power_nu_raises(tf, pk, m_nu): cosmo = ccl.Cosmology( Omega_c=0.27, Omega_b=0.045, h=0.67, sigma8=0.8, n_s=0.96, transfer_function=tf, matter_power_spectrum=pk, m_nu=m_nu) if tf is not None: with pytest.warns(CCLWarning): ccl.linear_matter_power(cosmo, 1, 1) with pytest.raises(CCLError): ccl.nonlin_matter_power(cosmo, 1, 1)
def test_mu_sigma_transfer_err(tf): with pytest.raises(ccl.CCLError): cosmo = ccl.Cosmology(Omega_c=0.25, Omega_b=0.05, h=0.7, A_s=2.1e-9, n_s=0.96, mu_0=0.1, sigma_0=0.2, transfer_function=tf, matter_power_spectrum='linear') ccl.linear_matter_power(cosmo, 1, 1)
def test_halofit_highz(cosmo): vals = [(25, 75)] + list(zip(range(0, 98), range(1, 99))) for zl, zh in vals: al = 1.0 / (1 + zl) ah = 1.0 / (1 + zh) k = np.logspace(0, 2, 10) pkratl = (ccl.nonlin_matter_power(cosmo, k, al) / ccl.linear_matter_power(cosmo, k, al)) pkrath = (ccl.nonlin_matter_power(cosmo, k, ah) / ccl.linear_matter_power(cosmo, k, ah)) assert np.all(pkratl >= pkrath), (zl, zh, pkratl, pkrath)
def check_power(cosmo): """ Check that power spectrum and sigma functions can be run. """ # Types of scale factor a = 0.9 a_arr = np.linspace(0.2, 1., 5) # Types of wavenumber input (scalar, list, array) k_scl = 1e-1 k_lst = [1e-4, 1e-3, 1e-2, 1e-1, 1e0] k_arr = np.logspace(-4., 0., 5) # Types of smoothing scale, R R_scl = 8. R_lst = [1., 5., 10., 20., 50., 100.] R_arr = np.array([1., 5., 10., 20., 50., 100.]) # linear_matter_power assert_(all_finite(ccl.linear_matter_power(cosmo, k_scl, a))) assert_(all_finite(ccl.linear_matter_power(cosmo, k_lst, a))) assert_(all_finite(ccl.linear_matter_power(cosmo, k_arr, a))) assert_raises(TypeError, ccl.linear_matter_power, cosmo, k_scl, a_arr) assert_raises(TypeError, ccl.linear_matter_power, cosmo, k_lst, a_arr) assert_raises(TypeError, ccl.linear_matter_power, cosmo, k_arr, a_arr) # nonlin_matter_power assert_(all_finite(ccl.nonlin_matter_power(cosmo, k_scl, a))) assert_(all_finite(ccl.nonlin_matter_power(cosmo, k_lst, a))) assert_(all_finite(ccl.nonlin_matter_power(cosmo, k_arr, a))) assert_raises(TypeError, ccl.nonlin_matter_power, cosmo, k_scl, a_arr) assert_raises(TypeError, ccl.nonlin_matter_power, cosmo, k_lst, a_arr) assert_raises(TypeError, ccl.nonlin_matter_power, cosmo, k_arr, a_arr) # sigmaR assert_(all_finite(ccl.sigmaR(cosmo, R_scl))) assert_(all_finite(ccl.sigmaR(cosmo, R_lst))) assert_(all_finite(ccl.sigmaR(cosmo, R_arr))) # sigmaV assert_(all_finite(ccl.sigmaV(cosmo, R_scl))) assert_(all_finite(ccl.sigmaV(cosmo, R_lst))) assert_(all_finite(ccl.sigmaV(cosmo, R_arr))) # sigma8 assert_(all_finite(ccl.sigma8(cosmo)))
def calc_power_spectrum(Omega_v, w0, wa, transfer_fn, matter_power, linear, raise_errors): """ Calculate linear and nonlinear power spectrum for a given set of parameters and choices of transfer function and matter power spectrum. """ k = np.logspace(-5., 1., 300) a = np.logspace(np.log10(0.51), 0., 5) # Emulator only works at z<2 # Set Omega_K in a consistent way Omega_k = 1.0 - Omega_c - Omega_b - Omega_v if (raise_errors == False): if (transfer_fn == 'eisenstein_hu' or transfer_fn == 'bbks'): mnu = 0. # The bbks and E-H P(k) are not defined for massive neutrinos. elif (transfer_fn == 'emulator' and matter_power == 'emu'): mnu = mnu_list # For the emulator, we must have 3 equal masses else: mnu = mnu_sum elif (raise_errors == True): if (transfer_fn == 'eisenstein_hu' or transfer_fn == 'bbks'): mnu = mnu_sum #Use massive neutrinos to deliberately raise an error elif (transfer_fn == 'emulator' and matter_power == 'emu'): mnu = mnu_sum #Use a sum instead of an equal list to deliberately raise an error. else: raise ( ValueError, "Transfer function %s with matter power spectrum method %s has no case for which to test errors are raised." % (transfer_fn, matter_power)) # Create new Parameters and Cosmology objects cosmo = ccl.Cosmology(Omega_c=Omega_c, Omega_b=Omega_b, h=h, sigma8=sigma8, n_s=n_s, Omega_k=Omega_k, w0=w0, wa=wa, transfer_function=transfer_fn, matter_power_spectrum=matter_power, Neff=Neff, m_nu=mnu) # Calculate linear and nonlinear power spectra for each scale factor, a for _a in a: if linear: if raise_errors == False: pk_lin = ccl.linear_matter_power(cosmo, k, _a) assert_(all_finite(pk_lin)) else: assert_raises(RuntimeError, ccl.linear_matter_power, cosmo, k, _a) else: if raise_errors == False: pk_nl = ccl.nonlin_matter_power(cosmo, k, _a) assert_(all_finite(pk_nl)) else: assert_raises(RuntimeError, ccl.nonlin_matter_power, cosmo, k, _a)
def test_eisenstein_hu(): # We first define equivalent CCL and jax_cosmo cosmologies cosmo_ccl = ccl.Cosmology( Omega_c=0.3, Omega_b=0.05, h=0.7, sigma8=0.8, n_s=0.96, Neff=0, transfer_function="eisenstein_hu", matter_power_spectrum="linear", ) cosmo_jax = Cosmology( Omega_c=0.3, Omega_b=0.05, h=0.7, sigma8=0.8, n_s=0.96, Omega_k=0.0, w0=-1.0, wa=0.0, ) # Test array of scales k = np.logspace(-4, 2, 512) # Computing matter power spectrum pk_ccl = ccl.linear_matter_power(cosmo_ccl, k, 1.0) pk_jax = (power.linear_matter_power(cosmo_jax, k / cosmo_jax.h, a=1.0) / cosmo_jax.h**3) assert_allclose(pk_ccl, pk_jax, rtol=0.5e-2)
def ccl_pk_bbks(self,z,cosmo_params=None,pk_params=None): if not cosmo_params: cosmo_params=self.cosmo_params if not pk_params: pk_params=self.pk_params cosmo_ccl=pyccl.Cosmology(h=cosmo_params['h'],Omega_c=cosmo_params['Omc'],Omega_b=cosmo_params['Omb'], sigma8=cosmo_params['s8'],n_s=cosmo_params['ns'], transfer_function='bbks', matter_power_spectrum='linear', Omega_g=cosmo_params['Og']) #m_nu=cosmo_params['m_nu'],Neff=cosmo_params['Neff']) kh=np.logspace(np.log10(pk_params['kmin']),np.log10(pk_params['kmax']),pk_params['nk']) nz=len(z) ps=np.zeros((nz,pk_params['nk'])) ps0=[] z0=9.#PS(z0) will be rescaled using growth function when CCL fails. pyccl_pkf=pyccl.linear_matter_power if pk_params['non_linear']==1: pyccl_pkf=pyccl.nonlin_matter_power for i in np.arange(nz): try: ps[i]= pyccl_pkf(cosmo_ccl,kh,1./(1+z[i])) except Exception as err: print ('CCL err',err,z[i]) if not np.any(ps0): ps0=pyccl.linear_matter_power(cosmo_ccl,kh,1./(1.+z0)) Dz=self.DZ_int(z=[z0,z[i]]) ps[i]=ps0*(Dz[1]/Dz[0])**2 return ps*cosmo_params['h']**3,kh/cosmo_params['h'] #factors of h to get in same units as camb output
def test_eh(): model = 1 cosmo = ccl.Cosmology( Omega_c=0.25, Omega_b=0.05, h=0.7, sigma8=0.8, n_s=0.96, Neff=0, m_nu=0.0, w0=-1.0, wa=0.0, m_nu_type='normal', Omega_g=0, Omega_k=0, transfer_function='eisenstein_hu', matter_power_spectrum='linear') data = np.loadtxt('./benchmarks/data/model%d_pk_eh.txt' % model) k = data[:, 0] * cosmo['h'] for i in range(1): a = 1.0 / (1.0 + i) pk = data[:, i+1] / (cosmo['h']**3) pk_ccl = ccl.linear_matter_power(cosmo, k, a) err = np.abs(pk_ccl/pk - 1) assert np.allclose(err, 0, rtol=0, atol=EH_TOLERANCE)
def test_power_mg(model): mu_0 = [0., 0.1, -0.1, 0.1, -0.1] sigma_0 = [0., 0.1, -0.1, -0.1, 0.1] h0 = 0.7 cosmo = ccl.Cosmology(Omega_c=0.112 / h0**2, Omega_b=0.0226 / h0**2, h=h0, A_s=2.1e-9, n_s=0.96, Neff=3.046, mu_0=mu_0[model], sigma_0=sigma_0[model], Omega_k=0, m_nu=0, T_CMB=2.7255, matter_power_spectrum='linear', transfer_function='boltzmann_isitgr') data = np.loadtxt("./benchmarks/data/model%d_pk_MG_matterpower.dat" % model) a = 1 k = data[:, 0] * cosmo['h'] pk = data[:, 1] / (cosmo['h']**3) pk_ccl = ccl.linear_matter_power(cosmo, k, a) err = np.abs(pk_ccl / pk - 1) # cut two points due to cosmic variance cut = data[:, 0] > 1e-04 assert np.allclose(err[cut], 0, rtol=0, atol=POWER_MG_TOL)
def signal_power(zc, k, mu, cosmo, params): """ Return the signal auto- and cross-power spectra. """ # Scale factor at central redshift a = 1. / (1. + zc) # Get matter power spectrum pk = ccl.linear_matter_power(cosmo, k, a) # Get redshift-dep. functions b = bias(zc, params) rg = corrfac(zc, params) f = params['x_f'] * ccl.growth_rate(cosmo, a) beta = f / b H = params['x_H'] * ccl.h_over_h0(cosmo, a) * 100. * cosmo['h'] # km/s/Mpc # Redshift-space suppression factors D_g = 1. / np.sqrt(1. + 0.5 * (k * mu * sigma_g(zc, params))**2.) D_u = np.sinc(k * sigma_u(zc, params)) # galaxy-galaxy (dimensionless) pk_gg = b**2. * (1. + 2. * rg * beta * mu**2. + beta**2. * mu**4.) * D_g**2. * pk # galaxy-velocity (units: km/s) pk_gv = 1.j * a * H * f * b * mu * (rg + beta * mu**2.) * D_g * D_u / k * pk #pk_vg = -1. * pk_gv # Complex conjugate # velocity-velocity (units: [km/s]^2) pk_vv = (a * H * f * mu)**2. * (D_u / k)**2. * pk # Multiply all elements by P(k) and return return pk_gg, pk_gv, pk_vv
def get_ssc_counterterm_gc(k, a, hmc, prof1, prof2, prof12_2pt, normalize=False): P_12 = b1 = b2 = np.zeros_like(k) if prof1.is_number_counts or prof2.is_number_counts: norm1 = hmc.profile_norm(COSMO, a, prof1) norm2 = hmc.profile_norm(COSMO, a, prof2) norm12 = 1 if prof1.is_number_counts or normalize: norm12 *= norm1 if prof2.is_number_counts or normalize: norm12 *= norm2 i11_1 = hmc.I_1_1(COSMO, k, a, prof1) i11_2 = hmc.I_1_1(COSMO, k, a, prof2) i02_12 = hmc.I_0_2(COSMO, k, a, prof1, prof12_2pt, prof2) pk = ccl.linear_matter_power(COSMO, k, a) P_12 = norm12 * (pk * i11_1 * i11_2 + i02_12) if prof1.is_number_counts: b1 = halomod_bias_1pt(COSMO, hmc, k, a, prof1) * norm1 if prof2.is_number_counts: b2 = halomod_bias_1pt(COSMO, hmc, k, a, prof2) * norm2 return (b1 + b2) * P_12
def test_power_mg(model): mu_0 = [0., 0.1, -0.1, 0.1, -0.1] sigma_0 = [0., 0.1, -0.1, -0.1, 0.1] cosmo = ccl.Cosmology( Omega_c=0.25, Omega_b=0.05, h=0.7, A_s=2.1e-9, n_s=0.96, Neff=3.046, mu_0=mu_0[model], sigma_0=sigma_0[model], Omega_k=0, matter_power_spectrum='linear', transfer_function='boltzmann_class') data = np.loadtxt("./benchmarks/data/model%d_pk_MG.dat" % model) a = 1 k = data[:, 0] * cosmo['h'] pk = data[:, 1] / (cosmo['h']**3) pk_ccl = ccl.linear_matter_power(cosmo, k, a) err = np.abs(pk_ccl/pk - 1) if model == 0: assert np.allclose(err, 0, rtol=0, atol=POWER_MG_TOL) else: msk = data[:, 0] > 5e-3 assert np.allclose(err[msk], 0, rtol=0, atol=POWER_MG_TOL)
def test_bbks(model, w0, wa): cosmo = ccl.Cosmology(Omega_c=0.25, Omega_b=0.05, h=0.7, sigma8=0.8, n_s=0.96, Neff=0, m_nu=0.0, w0=w0, wa=wa, T_CMB=2.7, m_nu_type='normal', Omega_g=0, Omega_k=0, transfer_function='bbks', matter_power_spectrum='linear') data = np.loadtxt('./benchmarks/data/model%d_pk.txt' % model) k = data[:, 0] * cosmo['h'] for i in range(6): a = 1.0 / (1.0 + i) pk = data[:, i + 1] / (cosmo['h']**3) pk_ccl = ccl.linear_matter_power(cosmo, k, a) err = np.abs(pk_ccl / pk - 1) assert np.allclose(err, 0, rtol=0, atol=BBKS_TOLERANCE)
def test_power_nu(model): mnu = [[0.04, 0., 0.], [0.05, 0.01, 0.], [0.03, 0.02, 0.04]] w_0 = [-1.0, -0.9, -0.9] w_a = [0.0, 0.0, 0.1] cosmo = ccl.Cosmology(Omega_c=0.25, Omega_b=0.05, h=0.7, A_s=2.1e-9, n_s=0.96, Neff=3.046, Omega_k=0, w0=w_0[model], wa=w_a[model], m_nu=mnu[model], m_nu_type='list', transfer_function='boltzmann_class') a = 1 data_lin = np.loadtxt("./benchmarks/data/model%d_pk_nu.txt" % (model + 1)) k_lin = data_lin[:, 0] * cosmo['h'] pk_lin = data_lin[:, 1] / (cosmo['h']**3) pk_lin_ccl = ccl.linear_matter_power(cosmo, k_lin, a) err = np.abs(pk_lin_ccl / pk_lin - 1) assert np.allclose(err, 0, rtol=0, atol=POWER_NU_TOL) data_nl = np.loadtxt("./benchmarks/data/model%d_pk_nl_nu.txt" % (model + 1)) k_nl = data_nl[:, 0] * cosmo['h'] pk_nl = data_nl[:, 1] / (cosmo['h']**3) pk_nl_ccl = ccl.nonlin_matter_power(cosmo, k_nl, a) err = np.abs(pk_nl_ccl / pk_nl - 1) assert np.allclose(err, 0, rtol=0, atol=POWER_NU_TOL)
def test_pk_cutoff(): # Tests the exponential cutoff ptc1 = ccl.nl_pt.PTCalculator(with_NC=True) ptc2 = ccl.nl_pt.PTCalculator(with_NC=True, k_cutoff=10., n_exp_cutoff=2.) zs = np.array([0., 1.]) gs4 = ccl.growth_factor(COSMO, 1. / (1 + zs))**4 pk_lin_z0 = ccl.linear_matter_power(COSMO, ptc1.ks, 1.) ptc1.update_pk(pk_lin_z0) ptc2.update_pk(pk_lin_z0) Pd1d1 = np.array( [ccl.linear_matter_power(COSMO, ptc1.ks, a) for a in 1. / (1 + zs)]).T one = np.ones_like(zs) zero = np.zeros_like(zs) p1 = ptc1.get_pgg(Pd1d1, gs4, one, zero, zero, one, zero, zero, True).T p2 = ptc2.get_pgg(Pd1d1, gs4, one, zero, zero, one, zero, zero, True).T expcut = np.exp(-(ptc1.ks / 10.)**2) assert np.all(np.fabs(p1 * expcut / p2 - 1) < 1E-10)
def test_k2pk(): # Tests the k2 term scaling ptc = ccl.nl_pt.PTCalculator(with_NC=True) zs = np.array([0., 1.]) gs4 = ccl.growth_factor(COSMO, 1. / (1 + zs))**4 pk_lin_z0 = ccl.linear_matter_power(COSMO, ptc.ks, 1.) ptc.update_pk(pk_lin_z0) Pd1d1 = np.array( [ccl.linear_matter_power(COSMO, ptc.ks, a) for a in 1. / (1 + zs)]).T one = np.ones_like(zs) zero = np.zeros_like(zs) pmm = ptc.get_pgg(Pd1d1, gs4, one, zero, zero, one, zero, zero, True) pmm_b = ptc.get_pgm(Pd1d1, gs4, one, zero, zero) pmk = ptc.get_pgg(Pd1d1, gs4, one, zero, zero, one, zero, zero, True, bk21=one) pmk_b = ptc.get_pgm(Pd1d1, gs4, one, zero, zero, bk2=one) pkk = ptc.get_pgg(Pd1d1, gs4, one, zero, zero, one, zero, zero, True, bk21=one, bk22=one) ks = ptc.ks[:, None] assert np.all(np.fabs(pmm / Pd1d1 - 1) < 1E-10) assert np.all(np.fabs(pmm_b / Pd1d1 - 1) < 1E-10) assert np.all(np.fabs(pmk / (pmm * (1 + 0.5 * ks**2)) - 1) < 1E-10) assert np.all(np.fabs(pmk_b / (pmm * (1 + 0.5 * ks**2)) - 1) < 1E-10) assert np.all(np.fabs(pkk / (pmm * (1 + ks**2)) - 1) < 1E-10)
def test_power_mu_sigma_sigma8norm(tf): cosmo = ccl.Cosmology( Omega_c=0.27, Omega_b=0.045, h=0.67, sigma8=0.8, n_s=0.96, transfer_function=tf) cosmo_musig = ccl.Cosmology( Omega_c=0.27, Omega_b=0.045, h=0.67, sigma8=0.8, n_s=0.96, transfer_function=tf, mu_0=0.1, sigma_0=0.2) # make sure sigma8 is correct assert np.allclose(ccl.sigma8(cosmo_musig), 0.8) # make sure P(k) ratio is right a = 0.8 gfac = ( ccl.growth_factor(cosmo, a) / ccl.growth_factor(cosmo_musig, a))**2 pk_rat = ( ccl.linear_matter_power(cosmo, 1e-4, a) / ccl.linear_matter_power(cosmo_musig, 1e-4, a)) assert np.allclose(pk_rat, gfac)
def pk(self, k, a, lmmin=6., lmmax=17., nlm=256, return_decomposed=False): """ Returns power spectrum at redshift `z` sampled at all values of k in `k`. k : array of wavenumbers in CCL units a : scale factor lmmin, lmmax, nlm : mass edges and sampling rate for mass integral. return_decomposed : if True, returns 1-halo, 2-halo, bias, shot noise and total (see below for order). """ z = 1. / a - 1. marr = np.logspace(lmmin, lmmax, nlm) dlm = np.log10(marr[1] / marr[0]) u_s = self.u_sat(z, marr, k) hmf = ccl.massfunc(self.cosmo, marr, a) hbf = ccl.halo_bias(self.cosmo, marr, a) rhoM = ccl.rho_x(self.cosmo, a, "matter", is_comoving=True) n0_1h = (rhoM - np.sum(hmf * marr) * dlm) / marr[0] n0_2h = (rhoM - np.sum(hmf * hbf * marr) * dlm) / marr[0] #Number of galaxies fc = self.fc_f(z) ngm = self.n_tot(z, marr) ncm = self.n_cent(z, marr) nsm = self.n_sat(z, marr) #Number density ng = np.sum(hmf * ngm) * dlm + n0_1h * ngm[0] if ng <= 1E-16: #Make sure we won't divide by 0 return None #Bias b_hod = np.sum( (hmf * hbf * ncm)[None, :] * (fc + nsm[None, :] * u_s[:, :]), axis=1) * dlm + n0_2h * ncm[0] * (fc + nsm[0] * u_s[:, 0]) b_hod /= ng #1-halo #p1h=np.sum((hmf*ncm**2)[None,:]*(fc+nsm[None,:]*u_s[:,:])**2,axis=1)*dlm+n0_1h*(ncm[0]*(fc+nsm[0]*u_s[:,0]))**2 p1h = np.sum( (hmf * ncm)[None, :] * (2 * fc * nsm[None, :] * u_s[:, :] + (nsm[None, :] * u_s[:, :])**2), axis=1) * dlm + n0_1h * ncm[0] * (2 * fc * nsm[0] * u_s[:, 0] + (nsm[0] * u_s[:, 0])**2) p1h /= ng**2 #2-halo p2h = b_hod**2 * ccl.linear_matter_power(self.cosmo, k, a) if return_decomposed: return p1h + p2h, p1h, p2h, np.ones_like(k) / ng, b_hod else: return p1h + p2h
def test_camb_class_consistent_smoke(kwargs=None, pkerr=1e-3): kwargs = kwargs or {} print('kwargs:', kwargs) c_camb = ccl.Cosmology(Omega_c=0.25, Omega_b=0.05, h=0.7, n_s=0.95, A_s=2e-9, transfer_function='boltzmann_camb', **kwargs) c_class = ccl.Cosmology(Omega_c=0.25, Omega_b=0.05, h=0.7, n_s=0.95, A_s=2e-9, transfer_function='boltzmann_class', **kwargs) with warnings.catch_warnings(): # We do some tests here with massive neutrinos, which currently raises # a warning. # XXX: Do you really want to be raising a warning for this? # This seems spurious to me. (MJ) warnings.simplefilter("ignore") rel_sigma8 = np.abs(ccl.sigma8(c_camb) / ccl.sigma8(c_class) - 1) a = 0.845 k = np.logspace(-3, 1, 100) pk_camb = ccl.linear_matter_power(c_camb, k, a) pk_class = ccl.linear_matter_power(c_class, k, a) rel_pk = np.max(np.abs(pk_camb / pk_class - 1)) print('rel err pk:', rel_pk) print('rel err sigma8:', rel_sigma8) assert rel_sigma8 < 3e-3 assert rel_pk < pkerr
def test_pk2d_from_model(model): cosmo_fixed = ccl.Cosmology( Omega_c=0.27, Omega_b=0.045, h=0.67, sigma8=0.8, n_s=0.96) cosmo = ccl.Cosmology( Omega_c=0.27, Omega_b=0.045, h=0.67, sigma8=0.8, n_s=0.96, transfer_function=model) pk = ccl.Pk2D.pk_from_model(cosmo_fixed, model=model) ks = np.geomspace(1E-3, 1E1, 128) for z in [0., 0.5, 2.]: a = 1./(1+z) pk1 = pk.eval(ks, a, cosmo) pk2 = ccl.linear_matter_power(cosmo, ks, a) maxdiff = np.amax(np.fabs(pk1/pk2-1)) assert maxdiff < 1E-10
def ICpk(cosmo, z_ic): ''' Compute the linear theory P(k) at the redshift of initial conditions Input: -cosmo: cosmological parameters -z_ic: initial conditions redshift Output: -fpk: power spectrum function that takes k in units of h/Mpc ''' k = np.logspace(-5, 2.3, 1000) #CCL uses units if 1/Mpc not h/Mpc so we have to convert things pk = pyccl.linear_matter_power(cosmo, k * cosmo['h'], 1) * (cosmo['h'])**3 D = pyccl.growth_factor(cosmo, 1. / (1 + z_ic)) fpk = interp1d(k, pk * D**2) return fpk
def signal_covariance(zc, cosmo, params): """ Signal power spectrum matrix, containing (cross-)spectra for gg, gv, vv. These are simply the galaxy auto-, galaxy-velocity cross-, and velocity auto-spectra. """ # Scale factor at central redshift a = 1. / (1. + zc) # Grid of Fourier wavenumbers k = np.logspace(KMIN, KMAX, NK) mu = np.linspace(-1., 1., NMU) K, MU = np.meshgrid(k, mu) # Get matter power spectrum pk = ccl.linear_matter_power(cosmo, k, a=1.) # Get redshift-dep. functions b = bias(zc, params) rg = corrfac(zc, params) f = params['x_f'] * ccl.growth_rate(cosmo, a) beta = f / b H = params['x_H'] * ccl.h_over_h0(cosmo, a) * 100. * cosmo['h'] # km/s/Mpc # Redshift-space suppression factors D_g = 1. / np.sqrt(1. + 0.5 * (K * MU * sigma_g(zc, params))**2.) D_u = np.sinc(K * sigma_u(zc, params)) # Build 2x2 matrix of mu- and k-dependent pre-factors of P(k) fac = np.zeros((2, 2, mu.size, k.size)).astype(complex) # galaxy-galaxy (dimensionless) fac[0, 0] = b**2. * (1. + 2. * rg * beta * MU**2. + beta**2. * MU**4.) * D_g**2. # galaxy-velocity (units: km/s) fac[0, 1] = 1.j * a * H * f * b * MU * (rg + beta * MU**2.) * D_g * D_u / K fac[1, 0] = -1. * fac[0, 1] # Complex conjugate # velocity-velocity (units: [km/s]^2) fac[1, 1] = (a * H * f * MU)**2. * (D_u / K)**2. # Multiply all elements by P(k) and return return fac * pk[np.newaxis, np.newaxis, np.newaxis, :]
def test_power_nu(model): mnu = [[0.04, 0., 0.], [0.05, 0.01, 0.], [0.03, 0.02, 0.04]] w_0 = [-1.0, -0.9, -0.9] w_a = [0.0, 0.0, 0.1] cosmo = ccl.Cosmology(Omega_c=0.25, Omega_b=0.05, h=0.7, A_s=2.1e-9, n_s=0.96, Neff=3.046, Omega_k=0, w0=w_0[model], wa=w_a[model], m_nu=mnu[model], m_nu_type='list', transfer_function='boltzmann_class') a = 1 data_lin = np.loadtxt("./benchmarks/data/model%d_pk_nu.txt" % (model + 1)) k_lin = data_lin[:, 0] * cosmo['h'] pk_lin = data_lin[:, 1] / (cosmo['h']**3) with warnings.catch_warnings(): # Linear power with massive neutrinos raises a warning. # Ignore it. # XXX: Do you really want to be raising a warning for this? # This seems spurious to me. (MJ) warnings.simplefilter("ignore") pk_lin_ccl = ccl.linear_matter_power(cosmo, k_lin, a) err = np.abs(pk_lin_ccl / pk_lin - 1) assert np.allclose(err, 0, rtol=0, atol=POWER_NU_TOL) data_nl = np.loadtxt("./benchmarks/data/model%d_pk_nl_nu.txt" % (model + 1)) k_nl = data_nl[:, 0] * cosmo['h'] pk_nl = data_nl[:, 1] / (cosmo['h']**3) pk_nl_ccl = ccl.nonlin_matter_power(cosmo, k_nl, a) err = np.abs(pk_nl_ccl / pk_nl - 1) assert np.allclose(err, 0, rtol=0, atol=POWER_NU_TOL)
if len(sys.argv)!=9 : print "Usage : mkpk.py Om Ob h s8 ns pk_type tf_type fname_out" exit(1) om=float(sys.argv[1]) ob=float(sys.argv[2]) hh=float(sys.argv[3]) s8=float(sys.argv[4]) ns=float(sys.argv[5]) pkt=sys.argv[6] tft=sys.argv[7] fno=sys.argv[8] lk0=-4. lkf=2. nk=512 karr=10.**np.linspace(lk0,lkf,nk) print "Generating power spectrum for params: " print " Om=",om print " Ob=",ob print " hh=",hh print " s8=",s8 print " ns=",ns print " pk_type:",pkt print " tf_type:",tft print " " cosmo=ccl.Cosmology(ccl.Parameters(Omega_c=om-ob,Omega_b=ob,h=hh,sigma8=s8,n_s=ns,), matter_power_spectrum=pkt,transfer_function=tft) pkarr=ccl.linear_matter_power(cosmo,karr*hh,1.)*hh**3 np.savetxt(fno,np.transpose([karr,pkarr]))
def test_no_sys_pipeline(plot=True): param_dict = { "cosmological_parameters": { "omch2": 0.1, "ombh2": 0.022, "h0": 0.7, "n_s": 0.96, "ln_1e10_A_s": 3.0, "omega_k": 0.0, "w": -1.0, "mnu": 0.06 }, "halo_model_parameters": { "A": 2.0, } } pipeline_ini = cosmosis.runtime.config.Inifile(PIPELINE_FILE) values_ini = cosmosis.runtime.config.Inifile(None) values_ini.read_dict(param_dict) pipeline = cosmosis.runtime.pipeline.LikelihoodPipeline(pipeline_ini, values=values_ini) data = pipeline.run_parameters([]) ccl_cosmo = ccl.Cosmology( Omega_c=data["cosmological_parameters", "omega_c"], Omega_b=data["cosmological_parameters", "omega_b"], Omega_k=data["cosmological_parameters", "omega_k"], h=data["cosmological_parameters", "h0"], n_s=data["cosmological_parameters", "n_s"], A_s=data["cosmological_parameters", "a_s"], Neff=data["cosmological_parameters", "n_eff"], m_nu=data["cosmological_parameters", "mnu"], w0=data["cosmological_parameters", "w"], ) print("Loading n(z) and creating CCL tracers.") nofz_files = pipeline_ini.get("load_nz", "filepath").split(" ") tracers = [] for nofz_file in nofz_files: z, nofz = np.loadtxt(nofz_file, unpack=True) z += (z[1] - z[0]) / 2 tracers.append(ccl.WeakLensingTracer(cosmo=ccl_cosmo, dndz=(z, nofz))) n_tomo_bin = len(tracers) print("Comparing P(k) at z=0") h = data["cosmological_parameters", "h0"] k_lin = data["matter_power_lin", "k_h"] k_nl = data["matter_power_nl", "k_h"] pk_lin_ccl = ccl.linear_matter_power(ccl_cosmo, k_lin * h, 1.0) * h**3 pk_nl_ccl = ccl.nonlin_matter_power(ccl_cosmo, k_nl * h, 1.0) * h**3 frac_diff_pk_lin = data["matter_power_lin", "p_k"][0] / pk_lin_ccl - 1 frac_diff_pk_nl = data["matter_power_nl", "p_k"][0] / pk_nl_ccl - 1 print( f"Maximum fractional difference in linear P(k) at z=0 for k<5 h/Mpc: {max(np.abs(frac_diff_pk_lin[k_lin < 5.0]))}" ) print( f"Maximum fractional difference in non-linear P(k) at z=0 for k<5 h/Mpc: {max(np.abs(frac_diff_pk_nl[k_nl < 5.0]))}" ) ell = data["shear_cl", "ell"] print(ell.min(), ell.max(), len(ell)) print("Setting up MontePython now.") import subprocess statistics_mp = {} for idx, likelihood in enumerate(["K1K_COSEBIs", "K1K_BandPowers"]): set_up_MontePython(likelihood) # we need to set some paths... path_to_param_file = os.path.join( "montepython/", "{:}/INPUT/{:}_Benchmark.param".format(likelihood, likelihood[4:])) path_to_mp_output = os.path.join(PATH_TO_MP_OUTPUT, likelihood) # TODO: unfortunately, MP saves out theory vectors and Cls to folder # from which it reads in its data and NOT to the MCMC output folder... path_to_mp_input = os.path.join(PATH_TO_MP_DATA[likelihood]) # the call to MontePython: cmd = "python {:} run -p {:} -o {:} --conf {:} -N 1".format( os.path.join(PATH_TO_MONTEPYTHON, "montepython/MontePython.py"), path_to_param_file, path_to_mp_output, os.path.join(PATH_TO_MONTEPYTHON, "default.conf")) subprocess.call(cmd, shell=True) # we only need the Cls from one MP likelihood: if idx == 0: print("Loading and re-ordering Cls from MP.") fname = os.path.join(path_to_mp_input, 'Cls_tot.txt') data_mp = np.loadtxt(fname) mp_cl_raw = data_mp[:, 1:] # bring raw Cls from MP into same sorting order: mp_cl_my_sorting = {} idx_unique = 0 for i in range(n_tomo_bin): mp_cl_my_sorting[i] = {} for j in range(i, n_tomo_bin): #print(f"Bin {i+1}-{j+1}") mp_cl_my_sorting[i][j] = mp_cl_raw[:, idx_unique] idx_unique += 1 mp_cl = {} for i in range(n_tomo_bin): mp_cl[i] = {} for j in range(i + 1): print(f"Bin {i+1}-{j+1} = Bin {j+1}-{i+1}") try: mp_cl[i][j] = mp_cl_my_sorting[j][i] except: mp_cl[i][j] = mp_cl_my_sorting[i][j] fname = os.path.join(path_to_mp_input, "{:}_theory.ascii".format(likelihood[4:])) print("Loaded theory vector from MontePython' {:} from: \n {:} \n". format(likelihood, fname)) statistics_mp[likelihood] = np.loadtxt(fname) print(statistics_mp) print(statistics_mp["K1K_COSEBIs"]) theta = data["shear_xi_plus", "theta"] * 180 / pi print("Running CCL for Cls and xis.") ccl_cl = {} ccl_xi = {} for i in range(n_tomo_bin): ccl_cl[i] = {} ccl_xi[i] = {} for j in range(i + 1): print(f"Bin {i+1}-{j+1}") ccl_cl[i][j] = ccl.angular_cl(cosmo=ccl_cosmo, cltracer1=tracers[i], cltracer2=tracers[j], ell=ell) ell_for_xi = np.concatenate( (np.arange(2, 100, dtype=float), np.logspace(2, np.log10(ell[-1]), 300))) cl_for_xi = ccl.angular_cl(cosmo=ccl_cosmo, cltracer1=tracers[i], cltracer2=tracers[j], ell=ell_for_xi) cl_for_xi /= ((ell_for_xi - 1) * ell_for_xi * (ell_for_xi + 1) * (ell_for_xi + 2) / (ell_for_xi + 1 / 2)**4) xip = ccl.correlation(cosmo=ccl_cosmo, ell=ell_for_xi, C_ell=cl_for_xi, theta=theta, corr_type="L+") xim = ccl.correlation(cosmo=ccl_cosmo, ell=ell_for_xi, C_ell=cl_for_xi, theta=theta, corr_type="L-") ccl_xi[i][j] = xip, xim ell_range = 10, 10000 theta_range = 0.05, 10.0 ell_mask = (ell_range[0] < ell) & (ell < ell_range[1]) theta_mask = (theta_range[0] < theta) & (theta < theta_range[1]) for i in range(n_tomo_bin): for j in range(i + 1): frac_diff_cl_KCAP_CCL = data["shear_cl", f"bin_{i+1}_{j+1}"] / ccl_cl[i][j] - 1 frac_diff_cl_KCAP_MP = data["shear_cl", f"bin_{i+1}_{j+1}"] / mp_cl[i][j] - 1 print( f"Maximum fractional difference between KCAP and CCL in Cl (ell>10) for bin {i+1}-{j+1}: {max(np.abs(frac_diff_cl_KCAP_CCL[ell_mask]))}" ) print( f"Maximum fractional difference between KCAP and MP in Cl (ell>10) for bin {i+1}-{j+1}: {max(np.abs(frac_diff_cl_KCAP_MP[ell_mask]))}" ) frac_diff_xi_plus = data["shear_xi_plus", f"bin_{i+1}_{j+1}"] / ccl_xi[i][j][0] - 1 print( f"Maximum fractional difference in xi_p (theta<10 deg) for bin {i+1}-{j+1}: {max(np.abs(frac_diff_xi_plus[theta_mask]))}" ) frac_diff_xi_minus = data["shear_xi_minus", f"bin_{i+1}_{j+1}"] / ccl_xi[i][j][1] - 1 print( f"Maximum fractional difference in xi_m (theta>0.05 deg) for bin {i+1}-{j+1}: {max(np.abs(frac_diff_xi_minus[theta_mask]))}" ) if plot: import matplotlib.pyplot as plt print("Plotting P(k)") fig, ax = plt.subplots(2, 1, sharex=True, sharey=False, figsize=(5, 5)) fig.subplots_adjust(hspace=0, wspace=0) ax[0].loglog(k_lin, pk_lin_ccl, ls="--", label=f"CCL linear P(k)") ax[0].loglog(k_lin, data["matter_power_lin", "p_k"][0], ls="--", label=f"CosmoSIS linear P(k)") ax[0].loglog(k_nl, pk_nl_ccl, label=f"CCL non-linear P(k)") ax[0].loglog(k_nl, data["matter_power_nl", "p_k"][0], label=f"CosmoSIS non-linear P(k)") ax[1].semilogx(k_lin, data["matter_power_lin", "p_k"][0] / pk_lin_ccl - 1, ls="--") ax[1].semilogx(k_nl, data["matter_power_nl", "p_k"][0] / pk_nl_ccl - 1) ax[0].legend(frameon=False) ax[0].set_ylabel("$P(k)$ [$h^{-3}$ Mpc$^{3}$]") ax[1].set_ylim(-0.05, 0.05) ax[1].set_xlabel("$k$ [$h$ Mpc$^{-1}$]") ax[1].set_ylabel("$\Delta P(k)/P(k)$ [$h$ Mpc$^{-1}$]") fig.suptitle("KCAP vs. CCL, P(k)") fig.savefig("KV450_pofk_kcap_vs_ccl.pdf") ell_plot_lim = ell_range print("Plotting Cls") fig, ax = plt.subplots(n_tomo_bin, n_tomo_bin, sharex=True, sharey=True, figsize=(2 * n_tomo_bin, 1.5 * n_tomo_bin)) fig.subplots_adjust(hspace=0, wspace=0) u = ell**2 for i in range(n_tomo_bin): for j in range(n_tomo_bin): if j > i: ax[i][j].axis("off") else: ax[i][j].loglog(ell, u * ccl_cl[i][j], label=f"CCL bin {i+1}-{j+1}") ax[i][j].loglog(ell, u * data["shear_cl", f"bin_{i+1}_{j+1}"], label=f"CosmoSIS") ax[i][j].loglog(ell, u * mp_cl[i][j], label=f"MP") ax[i][j].legend(fontsize="small", frameon=False) ax[i][j].set_xlim(*ell_plot_lim) for p in ax[-1]: p.set_xlabel(r"$\ell$") for p in ax: p[0].set_ylabel(r"$\ell^2\ C_\ell$") fig.suptitle("KCAP vs. CCL vs. MP, Cls") fig.savefig("KV450_Cl_kcap_vs_ccl_vs_mp.pdf") print("Plotting Cl fractional differences.") fig, ax = plt.subplots(n_tomo_bin, n_tomo_bin, sharex=True, sharey=True, figsize=(2 * n_tomo_bin, 1.5 * n_tomo_bin)) fig.subplots_adjust(hspace=0, wspace=0) for i in range(n_tomo_bin): for j in range(n_tomo_bin): if j > i: ax[i][j].axis("off") else: label = f"bin {i+1}-{j+1}" ax[i][j].text(0.75, 0.80, label, horizontalalignment='center', transform=ax[i][j].transAxes) ax[i][j].semilogx( ell, data["shear_cl", f"bin_{i+1}_{j+1}"] / ccl_cl[i][j] - 1, label=f"KCAP vs. CCL") ax[i][j].semilogx( ell, data["shear_cl", f"bin_{i+1}_{j+1}"] / mp_cl[i][j] - 1, label="KCAP vs. MP") #ax[i][j].legend(fontsize="small", frameon=False) ax[i][j].axhline(0., ls='-', color='gray') for val in [0.01, 0.05]: ax[i][j].axhline(val, ls=':', color='gray') ax[i][j].axhline(-val, ls=':', color='gray') ax[i][j].set_xlim(*ell_plot_lim) ax[i][j].set_ylim(-0.1, 0.1) ax[1][1].legend(fontsize="small", frameon=False, bbox_to_anchor=(.95, 1.05)) for p in ax[-1]: p.set_xlabel(r"$\ell$") for p in ax: p[0].set_ylabel(r"$|\Delta C_\ell|/C_\ell$") fig.suptitle("KCAP vs. CCL vs. MP, Cls") fig.savefig("KV450_Cl_kcap_vs_ccl_vs_mp_frac_diff.pdf") print("Plotting xi fractional differences.") theta_plot_lim = theta_range fig, ax = plt.subplots(n_tomo_bin, n_tomo_bin, sharex=True, sharey=True, figsize=(2 * n_tomo_bin, 1.5 * n_tomo_bin)) fig.subplots_adjust(hspace=0, wspace=0) for i in range(n_tomo_bin): for j in range(n_tomo_bin): if j > i: ax[i][j].axis("off") else: ax[i][j].semilogx( theta, data["shear_xi_plus", f"bin_{i+1}_{j+1}"] / ccl_xi[i][j][0] - 1, label=f"xip bin {i+1}-{j+1}") ax[i][j].semilogx( theta, data["shear_xi_minus", f"bin_{i+1}_{j+1}"] / ccl_xi[i][j][1] - 1, label=f"xim bin {i+1}-{j+1}") ax[i][j].legend(fontsize="small", frameon=False) ax[i][j].set_xlim(*theta_plot_lim) ax[i][j].set_ylim(-0.1, 0.1) for p in ax[-1]: p.set_xlabel(r"$\theta$ [deg]") for p in ax: p[0].set_ylabel(r"$|\Delta \xi|/\xi$") fig.suptitle("KCAP vs. CCL, xis") fig.savefig("KV450_xi_kcap_vs_ccl_frac_diff.pdf") print("Plotting COSEBIs fractional differences.") # TODO: this range should be taken from CosmoSIS keywords!!! n_modes = 5 n_tomo_corrs = n_tomo_bin * (n_tomo_bin + 1) // 2 modes = np.arange(1, n_modes + 1) cosebis_mp = statistics_mp["K1K_COSEBIs"].reshape( n_tomo_corrs, n_modes) fig, ax = plt.subplots(n_tomo_bin, n_tomo_bin, sharex=True, sharey=True, figsize=(2 * n_tomo_bin, 1.5 * n_tomo_bin)) fig.subplots_adjust(hspace=0, wspace=0) idx_corr = 0 for i in range(n_tomo_bin): for j in range(n_tomo_bin): if j > i: ax[i][j].axis("off") else: # TODO: add also output from CosmoSIS! #ax[i][j].semilogx(modes, data["cosebis", f"bin_{i+1}_{j+1}"] / cosebis_mp[idx_corr, :] -1, label=f"COSEBIs bin {i+1}-{j+1}") ax[i][j].plot( modes, cosebis_mp[idx_corr, :] / cosebis_mp[idx_corr, :] - 1, label=f"COSEBIs bin {i+1}-{j+1}") ax[i][j].legend(fontsize="small", frameon=False) idx_corr += 1 ax[i][j].set_xlim([0., 6.]) ax[i][j].set_ylim([-0.1, 0.1]) for p in ax[-1]: p.set_xlabel(r"$n$") for p in ax: p[0].set_ylabel(r"$|\Delta E_n|/E_n$") fig.suptitle("KCAP vs. MP, COSEBIs") fig.savefig("KV450_cosebis_kcap_vs_mp_frac_diff.pdf") print("Plotting BandPowers fractional differences.") # TODO: this range should be taken from CosmoSIS keywords!!! n_ell_bins = 8 n_tomo_corrs = n_tomo_bin * (n_tomo_bin + 1) // 2 plot_ell = np.logspace(np.log10(100.), np.log10(1500.), n_ell_bins) bandpowers_mp = statistics_mp["K1K_BandPowers"].reshape( n_tomo_corrs, n_ell_bins) fig, ax = plt.subplots(n_tomo_bin, n_tomo_bin, sharex=True, sharey=True, figsize=(2 * n_tomo_bin, 1.5 * n_tomo_bin)) fig.subplots_adjust(hspace=0, wspace=0) idx_corr = 0 for i in range(n_tomo_bin): for j in range(n_tomo_bin): if j > i: ax[i][j].axis("off") else: # TODO: add also output from CosmoSIS! #ax[i][j].semilogx(modes, data["bandpower", f"bin_{i+1}_{j+1}"] / bandpowers_mp[idx_corr, :] -1, label=f"BandPowers bin {i+1}-{j+1}") ax[i][j].semilogx(plot_ell, bandpowers_mp[idx_corr, :] / bandpowers_mp[idx_corr, :] - 1, label=f"BandPowers bin {i+1}-{j+1}") ax[i][j].legend(fontsize="small", frameon=False) idx_corr += 1 ax[i][j].set_xlim([100., 1500.]) ax[i][j].set_ylim([-0.1, 0.1]) for p in ax[-1]: p.set_xlabel(r"$\ell$") for p in ax: p[0].set_ylabel(r"$|\Delta PeeE|/PeeE $") fig.suptitle("KCAP vs. MP, BandPowers") fig.savefig("MOCK_bandpowers_kcap_vs_mp_frac_diff.pdf") plt.show()
def test_no_sys_pipeline(plot=True): param_dict = {"cosmological_parameters" : {"omch2" : 0.1, "ombh2" : 0.022, "h0" : 0.7, "n_s" : 0.96, "ln_1e10_A_s" : 3.0, "omega_k" : 0.0, "w" : -1.0, "mnu" : 0.06}, "halo_model_parameters" : {"A" : 2.0,}} pipeline_ini = cosmosis.runtime.config.Inifile(PIPELINE_FILE) values_ini = cosmosis.runtime.config.Inifile(None) values_ini.read_dict(param_dict) pipeline = cosmosis.runtime.pipeline.LikelihoodPipeline(pipeline_ini, values=values_ini) data = pipeline.run_parameters([]) ccl_cosmo = ccl.Cosmology(Omega_c=data["cosmological_parameters", "omega_c"], Omega_b=data["cosmological_parameters", "omega_b"], Omega_k=data["cosmological_parameters", "omega_k"], h=data["cosmological_parameters", "h0"], n_s=data["cosmological_parameters", "n_s"], A_s=data["cosmological_parameters", "a_s"], Neff=data["cosmological_parameters", "n_eff"], m_nu=data["cosmological_parameters", "mnu"], w0=data["cosmological_parameters", "w"], ) print("Loading n(z) and creating CCL tracers.") nofz_files = pipeline_ini.get("load_nz", "filepath").split(" ") tracers = [] for nofz_file in nofz_files: z, nofz = np.loadtxt(nofz_file, unpack=True) z += (z[1]-z[0])/2 tracers.append(ccl.WeakLensingTracer(cosmo=ccl_cosmo, dndz=(z, nofz))) n_tomo_bin = len(tracers) print("Comparing P(k) at z=0") h = data["cosmological_parameters", "h0"] k_lin = data["matter_power_lin", "k_h"] k_nl = data["matter_power_nl", "k_h"] pk_lin_ccl = ccl.linear_matter_power(ccl_cosmo, k_lin*h, 1.0)*h**3 pk_nl_ccl = ccl.nonlin_matter_power(ccl_cosmo, k_nl*h, 1.0)*h**3 frac_diff_pk_lin = data["matter_power_lin", "p_k"][0]/pk_lin_ccl - 1 frac_diff_pk_nl = data["matter_power_nl", "p_k"][0]/pk_nl_ccl - 1 print(f"Maximum fractional difference in linear P(k) at z=0 for k<5 h/Mpc: {max(np.abs(frac_diff_pk_lin[k_lin < 5.0]))}") print(f"Maximum fractional difference in non-linear P(k) at z=0 for k<5 h/Mpc: {max(np.abs(frac_diff_pk_nl[k_nl < 5.0]))}") ell = data["shear_cl", "ell"] theta = data["shear_xi_plus", "theta"]*180/pi print("Running CCL for Cls and xis.") ccl_cl = {} ccl_xi = {} for i in range(n_tomo_bin): ccl_cl[i] = {} ccl_xi[i] = {} for j in range(i+1): print(f"Bin {i+1}-{j+1}") ccl_cl[i][j] = ccl.angular_cl(cosmo=ccl_cosmo, cltracer1=tracers[i], cltracer2=tracers[j], ell=ell) ell_for_xi = np.concatenate((np.arange(2,100, dtype=float), np.logspace(2,np.log10(ell[-1]), 300))) cl_for_xi = ccl.angular_cl(cosmo=ccl_cosmo, cltracer1=tracers[i], cltracer2=tracers[j], ell=ell_for_xi) cl_for_xi /= ((ell_for_xi-1)*ell_for_xi*(ell_for_xi+1)*(ell_for_xi+2)/(ell_for_xi+1/2)**4) xip = ccl.correlation(cosmo=ccl_cosmo, ell=ell_for_xi, C_ell=cl_for_xi, theta=theta, corr_type="L+") xim = ccl.correlation(cosmo=ccl_cosmo, ell=ell_for_xi, C_ell=cl_for_xi, theta=theta, corr_type="L-") ccl_xi[i][j] = xip, xim ell_range = 10, 10000 theta_range = 0.05, 10.0 ell_mask = (ell_range[0] < ell) & (ell < ell_range[1]) theta_mask = (theta_range[0] < theta) & (theta < theta_range[1]) for i in range(n_tomo_bin): for j in range(i+1): frac_diff_cl = data["shear_cl", f"bin_{i+1}_{j+1}"]/ccl_cl[i][j] - 1 print(f"Maximum fractional difference in Cl (ell>10) for bin {i+1}-{j+1}: {max(np.abs(frac_diff_cl[ell_mask]))}") frac_diff_xi_plus = data["shear_xi_plus", f"bin_{i+1}_{j+1}"]/ccl_xi[i][j][0] - 1 print(f"Maximum fractional difference in xi_p (theta<10 deg) for bin {i+1}-{j+1}: {max(np.abs(frac_diff_xi_plus[theta_mask]))}") frac_diff_xi_minus = data["shear_xi_minus", f"bin_{i+1}_{j+1}"]/ccl_xi[i][j][1] - 1 print(f"Maximum fractional difference in xi_m (theta>0.05 deg) for bin {i+1}-{j+1}: {max(np.abs(frac_diff_xi_plus[theta_mask]))}") if plot: import matplotlib.pyplot as plt print("Plotting P(k)") fig, ax = plt.subplots(2, 1, sharex=True, sharey=False, figsize=(5, 5)) fig.subplots_adjust(hspace=0, wspace=0) ax[0].loglog(k_lin, pk_lin_ccl, ls="--", label=f"CCL linear P(k)") ax[0].loglog(k_lin, data["matter_power_lin", "p_k"][0], ls="--", label=f"CosmoSIS linear P(k)") ax[0].loglog(k_nl, pk_nl_ccl, label=f"CCL non-linear P(k)") ax[0].loglog(k_nl, data["matter_power_nl", "p_k"][0], label=f"CosmoSIS non-linear P(k)") ax[1].semilogx(k_lin, data["matter_power_lin", "p_k"][0]/pk_lin_ccl-1, ls="--") ax[1].semilogx(k_nl, data["matter_power_nl", "p_k"][0]/pk_nl_ccl-1) ax[0].legend(frameon=False) ax[0].set_ylabel("$P(k)$ [$h^{-3}$ Mpc$^{3}$]") ax[1].set_ylim(-0.05, 0.05) ax[1].set_xlabel("$k$ [$h$ Mpc$^{-1}$]") ax[1].set_ylabel("$\Delta P(k)/P(k)$ [$h$ Mpc$^{-1}$]") fig.suptitle("KCAP vs CCL, P(k)") # fig.savefig("KV450_pofk_kcap_vs_ccl.pdf") print("Plotting Cls") ell_plot_lim = ell_range fig, ax = plt.subplots(n_tomo_bin, n_tomo_bin, sharex=True, sharey=True, figsize=(2*n_tomo_bin, 1.5*n_tomo_bin)) fig.subplots_adjust(hspace=0, wspace=0) u = ell**2 for i in range(n_tomo_bin): for j in range(n_tomo_bin): if j > i: ax[i][j].axis("off") else: ax[i][j].loglog(ell, u*ccl_cl[i][j], label=f"CCL bin {i+1}-{j+1}") ax[i][j].loglog(ell, u*data["shear_cl", f"bin_{i+1}_{j+1}"], label=f"CosmoSIS") ax[i][j].legend(fontsize="small", frameon=False) ax[i][j].set_xlim(*ell_plot_lim) for p in ax[-1]: p.set_xlabel(r"$\ell$") for p in ax: p[0].set_ylabel(r"$\ell^2\ C_\ell$") fig.suptitle("KCAP vs CCL, Cls") #fig.savefig("KV450_Cl_kcap_vs_ccl.pdf") print("Plotting Cl fractional differences.") fig, ax = plt.subplots(n_tomo_bin, n_tomo_bin, sharex=True, sharey=True, figsize=(2*n_tomo_bin, 1.5*n_tomo_bin)) fig.subplots_adjust(hspace=0, wspace=0) for i in range(n_tomo_bin): for j in range(n_tomo_bin): if j > i: ax[i][j].axis("off") else: ax[i][j].semilogx(ell, data["shear_cl", f"bin_{i+1}_{j+1}"]/ccl_cl[i][j]-1, label=f"bin {i+1}-{j+1}") ax[i][j].legend(fontsize="small", frameon=False) ax[i][j].set_xlim(*ell_plot_lim) ax[i][j].set_ylim(-0.1, 0.1) for p in ax[-1]: p.set_xlabel(r"$\ell$") for p in ax: p[0].set_ylabel(r"$|\Delta C_\ell|/C_\ell$") fig.suptitle("KCAP vs CCL, Cls") #fig.savefig("KV450_Cl_kcap_vs_ccl_frac_diff.pdf") print("Plotting xi fractional differences.") theta_plot_lim = theta_range fig, ax = plt.subplots(n_tomo_bin, n_tomo_bin, sharex=True, sharey=True, figsize=(2*n_tomo_bin, 1.5*n_tomo_bin)) fig.subplots_adjust(hspace=0, wspace=0) for i in range(n_tomo_bin): for j in range(n_tomo_bin): if j > i: ax[i][j].axis("off") else: ax[i][j].semilogx(theta, data["shear_xi_plus", f"bin_{i+1}_{j+1}"]/ccl_xi[i][j][0]-1, label=f"xip bin {i+1}-{j+1}") ax[i][j].semilogx(theta, data["shear_xi_minus", f"bin_{i+1}_{j+1}"]/ccl_xi[i][j][1]-1, label=f"xim bin {i+1}-{j+1}") ax[i][j].legend(fontsize="small", frameon=False) ax[i][j].set_xlim(*theta_plot_lim) ax[i][j].set_ylim(-0.1, 0.1) for p in ax[-1]: p.set_xlabel(r"$\theta$ [deg]") for p in ax: p[0].set_ylabel(r"$|\Delta \xi|/\xi$") fig.suptitle("KCAP vs CCL, xis") #fig.savefig("KV450_xi_kcap_vs_ccl_frac_diff.pdf") plt.show()
#Define Cosmological paramters as usual #Omega_c = CDM fractional density #Omega_b = baryon fractional density #A_s = amplitude of the power spectrum #n_s = tilt of the power spectrum #h = Hubble Constant cosmo = ccl.Cosmology(Omega_c=0.27, Omega_b=0.045, h=0.67, A_s=2.1e-9, n_s=0.96, transfer_function='boltzmann') #Calculate the matter power spectrum k = np.logspace(-4., 1., 100) #Wavenumber a = 1. #Scale factor #Matter power spectrum, lin and nonlin pk_lin = np.asarray(ccl.linear_matter_power(cosmo, k, a)) pk_nl = np.asarray(ccl.nonlin_matter_power(cosmo, k, a)) plt.plot(k, pk_lin, 'b-') plt.plot(k, pk_nl, 'r-') plt.xscale('log') plt.yscale('log') plt.savefig('power_spectrum.png', format='png') #Transforms these to lists k = k.tolist() pk_lin = pk_lin.tolist() pk_nl = pk_nl.tolist() #Adds a header line k = ['k'] + k pk_lin =['pk lin'] + pk_lin
nk=1024 lkmin=-5. lkmax=2. h0=0.69 #Hubble rate #Parameters for N(z) \propto z^\alpha \exp[-(z/z0)^\beta] alpha_nz=2. beta_nz=1.0 z0_nz=0.3 #Number density in arcmin^-2 ndens_amin2=40. cosmo=ccl.Cosmology(Omega_c=0.266,Omega_b=0.049,h=h0,sigma8=0.8,n_s=0.96) karr=10.**(lkmin+(lkmax-lkmin)*np.arange(nk)/(nk-1.)) pklinarr=ccl.linear_matter_power(cosmo,1.,karr*h0)*h0**3 pknlinarr=ccl.nonlin_matter_power(cosmo,1.,karr*h0)*h0**3 zarr=zmax*np.arange(nz)/(nz-1.) gzarr=ccl.growth_factor(cosmo,1./(1+zarr)) bzarr=0.95/gzarr nzarr=zarr**alpha_nz*np.exp(-(zarr/z0_nz)**beta_nz) nzf=interp1d(zarr,nzarr) #Normalize nz ntot=quad(nzf,0,zmax)[0] nzarr*=ndens_amin2*60.**2/ntot nzf=interp1d(zarr,nzarr) print "#Gals : %lE"%(0.4*4*np.pi*(180/np.pi)**2*quad(nzf,0,zmax)[0]) np.savetxt("pk_planck.txt",np.transpose([karr,pklinarr]))