Ejemplo n.º 1
0
 def compute_power_spectra(self, z):
     try:
         from classy import Class
     except ImportError:
         print("Cannot precompute power spectra because CLASS "+\
               "is not installed.")
         return
     cos = self.args['cosmology']
     h = cos['h']
     params = {
         'output': 'mPk',
         "h": h,
         "sigma8": cos['sigma8'],
         "n_s": cos['ns'],
         "Omega_b": cos['Omega_b'],
         "Omega_cdm": cos['Omega_m'] - cos['Omega_b'],
         'P_k_max_1/Mpc': 1000.,
         'z_max_pk': 1.0,
         'non linear': 'halofit'
     }
     class_cosmo = Class()
     class_cosmo.set(params)
     class_cosmo.compute()
     k = np.logspace(-5, 3, num=4000)  #1/Mpc comoving
     kh = k / h  #h/Mpc comoving
     #P(k) are in Mpc^3/h^3 comoving
     Pnl = np.array([class_cosmo.pk(ki, z) for ki in k]) * h**3
     Plin = np.array([class_cosmo.pk_lin(ki, z) for ki in k]) * h**3
     self.args['k'] = kh
     self.args['Plin'] = Plin
     self.args['Pnl'] = Pnl
     return
Ejemplo n.º 2
0
def calc_power_spec(cosmos, zs, lin=True):
    Nc = len(cosmos)
    Nz = len(zs)
    ps = np.zeros((Nc, Nz, len(k)))
    for i in range(Nc):
        obh2, och2, w, ns, ln10As, H0, Neff, s8 = cosmos[i]
        h = H0 / 100.
        Omega_b = obh2 / h**2
        Omega_c = och2 / h**2
        Omega_m = Omega_b + Omega_c
        params = {
            'output': 'mPk',
            'h': h,
            'ln10^{10}A_s': ln10As,
            'n_s': ns,
            'w0_fld': w,
            'wa_fld': 0.0,
            'Omega_b': Omega_b,
            'Omega_cdm': Omega_c,
            'Omega_Lambda': 1. - Omega_m,
            'N_eff': Neff,
            'P_k_max_1/Mpc': 10.,
            'z_max_pk': 5.
        }
        if not lin:
            params['non linear'] = 'halofit'
        cosmo = Class()
        cosmo.set(params)
        cosmo.compute()
        for j in range(len(zs)):
            if lin:
                ps[i, j] = np.array([cosmo.pk_lin(ki, zs[j]) for ki in k])
            else:
                ps[i, j] = np.array([cosmo.pk(ki, zs[j]) for ki in k])
            continue
        print("Finished box%d" % i)
    return ps
Ejemplo n.º 3
0
def get_ps(**kwargs):
    
    Om = kwargs['omega_m_0']
    Ob = kwargs['omega_b_0']
    s8 = kwargs['sigma_8']
    h0 = kwargs['hubble_0']
    ns = kwargs['primordial_index']
    
    Omega_ncdm = Om - Ob
    #m_ncdm = 77319.85488
    
    mTH = kwargs['hmf_extra_par1']
        
    #Bozek2015
    msn = 3.9*(mTH)**1.294*(0.1198/0.1225)**(-0.33333)*1000
    
    params = {
         'h': h0,
         'T_cmb': 2.726,
         'Omega_b': Ob,
         'Omega_cdm': 1e-10,
         'Omega_ncdm': Omega_ncdm,
         'N_eff': 3.04,
         'N_ncdm': 1,
         'm_ncdm': msn,
         #'m_ncdm_in_eV': msn * 1e3,
         'T_ncdm': 0.715985, # ?
         'n_s': ns,
         #'sigma8': s8,
         'A_s': 2.02539e-09,
         'P_k_max_h/Mpc': 500.,         # Shouldn't need to be more than ~500? 
         'k_per_decade_for_pk': 20,     # Shouldn't need to be more than ~20? 
         'output': 'mPk',
         'ncdm_fluid_approximation': 3,
         'use_ncdm_psd_files': 0,
         # tolerances
         'tol_ncdm_bg': 1e-3,
         #'tol_ncdm': 1e-3,
         
         'tol_perturb_integration': 1e-6,
         'perturb_sampling_stepsize': 0.01,
         
         'format': 'camb',
                  
    }

    # Revert to CDM
    if not np.isfinite(mTH):
        params['N_ncdm'] = 0
        params['Omega_ncdm'] = 0
        params['Omega_cdm'] = Om - Ob
        ncdm_pars = ['tol_ncdm_bg', 'Omega_ncdm', 'use_ncdm_psd_files', 
            'm_ncdm', 'T_ncdm']
        for par in ncdm_pars:
            del params[par]

    classinst = Class()
    classinst.set(params)
    classinst.compute()
        
    k_bin = np.logspace(-5, 2.5, 200)
    pk_bin = np.array([classinst.pk_lin(k_bin[i],0) for i in range(len(k_bin))])
        
    return k_bin / h0, pk_bin * h0**3
delta_b_ary = one_time['d_b']
delta_chi_ary = one_time['d_chi']

n_s = M.n_s()

# Primordial PS
k_pivot = 0.05
P_s = 2.105e-9 * (k_ary / k_pivot) ** (n_s - 1)

# Power spectra from transfer function
# In units of Mpc^3 / h^3
Pk_b_ary = P_s * (delta_b_ary) ** 2 / (k_ary ** 3 / (2 * np.pi ** 2)) * h ** 3
Pk_chi_ary = P_s * (delta_chi_ary) ** 2 / \
    (k_ary ** 3 / (2 * np.pi ** 2)) * h ** 3
Pk_chi_b_ary = P_s * (delta_chi_ary * delta_b_ary) / \
    (k_ary ** 3 / (2 * np.pi ** 2)) * h ** 3
Pk_tot_lin_ary = np.array([M.pk_lin(k, z_compute) * h ** 3 for k in k_ary])
Pk_tot_nonlin_ary = np.array([M.pk(k, z_compute) * h ** 3 for k in k_ary])

np.savez(output_dir + "p_k_chi_k_max_500_z_" + str(iz_compute),
         k_ary=k_ary / h,  # Convert back to h / Mpc
         Pk_b_ary=Pk_b_ary,
         Pk_chi_ary=Pk_chi_ary,
         Pk_chi_b_ary=Pk_chi_b_ary,
         Pk_e_ary=Pk_b_ary + Pk_chi_ary + 2 * Pk_chi_b_ary,
         Pk_e_b_ary=Pk_chi_b_ary + Pk_b_ary,
         Pk_tot_lin_ary=Pk_tot_lin_ary,
         Pk_tot_nonlin_ary=Pk_tot_nonlin_ary
         )
Ejemplo n.º 5
0
Om = 0.31834
Ocdm = Om - Ob
h = 0.670435
params = {
        'output': 'mPk',
        "h":h,
        "A_s":2.1e-9,
        "n_s":0.96191,
        "Omega_b":Ob,
        "Omega_cdm":Ocdm,
        'YHe':0.24755048455476272,#By hand, default value
        'P_k_max_h/Mpc':3000.,
        'z_max_pk':1.0,
        'non linear':'halofit'}

cosmo = Class()
cosmo.set(params)
cosmo.compute()


k = np.logspace(-5, 3, base=10, num=4000) #1/Mpc, apparently
np.savetxt("txt_files/P_files/k.txt", k/h) #h/Mpc now
for i in range(len(zs)):
    z = zs[i]

    Pmm  = np.array([cosmo.pk(ki, z) for ki in k]) 
    Plin = np.array([cosmo.pk_lin(ki, z) for ki in k]) 
    np.savetxt("txt_files/P_files/Pnl_z%.2f.txt"%(z), Pmm*h**3) #Mpc^3/h^3
    np.savetxt("txt_files/P_files/Plin_z%.2f.txt"%(z), Plin*h**3) #Mpc^3/h^3
    print "Done with z%.2f"%z
Ejemplo n.º 6
0
}

# Create an instance of the CLASS wrapper
cosmo = Class()
# Set the parameters to the cosmological code
cosmo.set(params_def)
cosmo.compute()
#### Define the linear growth factor and growth rate (growth factor f in class)
h = cosmo.h()
# ~mcu = cosmo.N_ur()
# ~print(mcu)

Plin = np.zeros(len(karray))
Pnonlin = np.zeros(len(karray))
for i, k in enumerate(karray):
    Plin[i] = (cosmo.pk_lin(k, z))  # function .pk(k,z)
    Pnonlin[i] = (cosmo.pk(k, z))  # function .pk(k,z)

Plin *= h**3
Pnonlin *= h**3

#-------------------------------------------------------------------------
#-------------------------------------------------------------------------
m_1 = 0.02
ocdm_1 = 0.261205 - m_1 * 3 / (93.14 * h**2)
params_1 = {
    'output': 'mPk',
    'non linear': 'halofit',
    'Omega_cdm': ocdm_1,
    'N_ncdm': 3,
    'N_ur': 0.00441,
Ejemplo n.º 7
0
# omcdm = cosmo.omegach2()
# print("omega_cdm =",omcdm)

#k1 = 0.7*1.028185622909e-5
#k1 = 1.e-6
#z = 0.0
#k1 = 0.1
#print(cosmo.pk(k1,z))
#print(cosmo.pk_lin(k1,z))

k = np.linspace(log(0.0001), log(50), 200)
k = np.exp(k)
testout = [[0 for x in range(42)] for y in range(len(k))]
for i in range(len(k)):
    testout[i][0] = k[i]
    testout[i][41] = cosmo.pk_lin(k[i] * h, z) * h**3
    for j in range(40):
        #        print("j=",j)
        testout[i][j + 1] = cosmo.pk(k[i] * h, z)[j] * h**3
#        testout[i][0] = k[i]
#        testout[i][1] = cosmo.pk(k[i],z)[0]
#        testout[i][2] = cosmo.pk(k[i],z)[1]
#        testout[i][3] = cosmo.pk(k[i],z)[2]
#        testout[i][4] = cosmo.pk(k[i],z)[3]
#        testout[i][5] = cosmo.pk(k[i],z)[4]
#        testout[i][6] = cosmo.pk(k[i],z)[5]
#        testout[i][7] = cosmo.pk(k[i],z)[6]
#        testout[i][8] = cosmo.pk(k[i],z)[7]
#        testout[i][9] = cosmo.pk(k[i],z)[8]
#	testout[i][10] = cosmo.pk_lin(k[i],0)
# np.savetxt('ede_pk_nl_bestfit_z038.dat', testout)
Ejemplo n.º 8
0
cosmo = Class()
cosmo.set(params)
cosmo.compute()

#Derive value of Omega_m density
Omega_m = cosmo.Om_m(0)
#redshift zero

#Prepare logarithmically spaced array of wavenumbers
kvec = np.exp(np.log(10) * np.arange(-5, 1, 0.1))
nk = len(kvec)

#Interpolate the linear theory power spectrum
Pvec = np.zeros(nk)
for i in range(nk):
    Pvec[i] = cosmo.pk_lin(kvec[i], z_lin)

#Store the linear power spectrum data as text file (before rescaling!)
PowData = np.array([kvec, Pvec])
np.savetxt("PowData.txt", PowData.T, header="k [1/Mpc] Pk [Mpc^3]")

#Perform rescaling if necessary
D_0 = cosmo.scale_independent_growth_factor(0)
D_f = cosmo.scale_independent_growth_factor(z_f)
D_lin = cosmo.scale_independent_growth_factor(z_lin)
print("D_0: ", D_0)
print("D_f: ", D_f)
print("D_lin: ", D_lin)

#MeshPT needs a z=0 power spectrum, so one can rescale a power spectrum to z=0
#if a different input redshift is desired
Ejemplo n.º 9
0
plt.plot((ttCLASS[:ell_max + 1] - ttCAMB[:ell_max + 1]) / ttCAMB[:ell_max + 1],
         '-')
plt.xlabel(r'$\ell$')
plt.ylabel(r'$\Delta C_{\ell}^{TT} / C_{\ell}^{TT}$')
plt.title('TT Comparison of CAMB and CLASS')

########## P(k) #########################

pars.set_matter_power(redshifts=[0.], kmax=2.0)
pars.NonLinear = model.NonLinear_none
results = camb.get_results(pars)
kh, z, pk = results.get_matter_power_spectrum(minkh=1e-4, maxkh=1, npoints=200)
s8 = np.array(results.get_sigma8())

PCLASS = np.array([cosmo.pk_lin(ki * cosmo.h(), 0) for ki in kh])

# plt.loglog(kh, Pmm, '-')
plt.loglog(kh, PCLASS / (cosmo.h())**(-3), '-')
plt.loglog(kh, pk[0, :], '-')
plt.title('LINEAR')

# P(k) Comparison

plt.loglog(kh, np.abs((PCLASS / (cosmo.h())**(-3) - pk[0, :]) / pk[0, :]))
plt.xlabel(r'$k/h$')
plt.ylabel(r'$|\Delta P(k)| / P(k)$')

# Nonlinear P(k) Difference

pars.NonLinear = model.NonLinear_both
print(omb)

#k1 = 0.7*1.028185622909e-5
#k1 = 1.e-6
#z = 0.0
#k1 = 0.1
#print(cosmo.pk(k1,z))
#print(cosmo.pk_lin(k1,z))

k = np.linspace(log(0.0001), log(50), 400)
k = np.exp(k)
testout = [[0 for x in range(42)] for y in range(len(k))]
for i in range(len(k)):
    testout[i][0] = k[i]
    testout[i][41] = cosmo.pk_lin(k[i], z)
    for j in range(40):
        #        print("j=",j)
        testout[i][j + 1] = cosmo.pk(k[i], z)[j]
#        testout[i][0] = k[i]
#        testout[i][1] = cosmo.pk(k[i],z)[0]
#        testout[i][2] = cosmo.pk(k[i],z)[1]
#        testout[i][3] = cosmo.pk(k[i],z)[2]
#        testout[i][4] = cosmo.pk(k[i],z)[3]
#        testout[i][5] = cosmo.pk(k[i],z)[4]
#        testout[i][6] = cosmo.pk(k[i],z)[5]
#        testout[i][7] = cosmo.pk(k[i],z)[6]
#        testout[i][8] = cosmo.pk(k[i],z)[7]
#        testout[i][9] = cosmo.pk(k[i],z)[8]
#	testout[i][10] = cosmo.pk_lin(k[i],0)
np.savetxt('las_damas_pk_nl.dat', testout)
Ejemplo n.º 11
0
def get_Buzzard_args(z_index, lambda_index, RM):
    assert z_index in [0, 1, 2]
    assert lambda_index in [0, 1, 2, 3]

    zstr = ["0.2_0.35", "0.35_0.5", "0.5_0.65"][z_index]
    lstr = ["20_30", "30_45", "45_60", "60_10000"][lambda_index]
    z_title = ["0.2,0.35", "0.35,0.5", "0.5, 0.65"][z_index]
    lam_title = ["20,30", "30,45", "45,60", "60,\infty"][lambda_index]

    base = "../data/DeltaSigma_from_Buzzard/"
    if RM:
        inpath = base + "DeltaSigma_z_{0}_lam_{1}.dat".format(zstr, lstr)
    else:
        inpath = base + "DeltaSigma_same_mass_redshift_distribution_z_{0}_lam_{1}.dat".format(
            zstr, lstr)

    columns = ["R", "DeltaSigma", "DeltaSigma_err"]
    dat = pd.read_csv(inpath, sep=' ', skiprows=0, usecols=[0, 1, 2])
    dat.columns = columns
    DS_data = dat.DeltaSigma
    Cov = np.diag(dat["DeltaSigma_err"]**2)
    DS_unc = dat["DeltaSigma_err"]

    index = 4 * z_index + lambda_index
    z = np.loadtxt(
        "../data/DeltaSigma_from_Buzzard/Buzzard_redMaPPer_redshift_information.dat"
    )[index, 4]
    richness = np.array([25, 37.5, 52.5, 70])[lambda_index]
    R_lambda = (richness / 100.)**0.2  #Mpc/h comoving

    #Define the cosmology
    h = 0.7  #Hubble constant
    Omega_m = 0.286  #check this
    Sigma_crit_inverse = 1.  #For now

    #Radial bin edges in Mpc physical
    #Radial arrays
    r = np.logspace(-2, 3, num=1000)  #Mpc/h comoving; 3d radii
    R = np.logspace(-2, 2.4, 1000,
                    base=10)  #Mpc/h comoving; 2d projected radii
    #k = np.logspace(-5, 3, num=4000) #1/Mpc comoving; wavenumbers
    k = np.logspace(-3, 2, num=1000)  #1/Mpc comoving; wavenumbers
    M = np.logspace(12, 17, 500)  #Msun/h; halo masses

    R_edges = np.logspace(np.log10(0.0323), np.log10(30.), num=15 + 1)

    #PERFORM SCALE CUTS HERE
    R_mid = (R_edges[:-1] + R_edges[1:]) / 2.
    cut = R_mid > 0.2  #cut at 200 kpc phys.
    DeltaSigma_data = DS_data[cut]
    DeltaSigma_unc = DS_unc[cut]
    Cov = Cov[cut]
    Cov = Cov[:, cut]
    Re_inds = []
    for i in range(len(R_edges) - 1):
        if R_edges[i] > 0.4 - R_edges[i + 1]:  #cut criteria
            Re_inds.append(i - 1)
    Re_inds.append(len(R_edges) - 1)
    R_edges = R_edges[Re_inds]
    R_mid = (R_edges[:-1] + R_edges[1:]) / 2.

    #Convert units to Mpc/h comoving
    R_edges *= h * (1 + z)
    R_mid *= h * (1 + z)
    DeltaSigma_data /= h * (1 + z)**2
    DeltaSigma_unc /= h * (1 + z)**2
    Cov /= (h * (1 + z)**2)

    #Precompute theory quantities
    class_params = {  # 'N_eff': 3.04
        'output': 'mPk',
        "h": h,
        "sigma8": 0.82,
        "n_s": 0.96,
        "Omega_b": 0.047,
        "Omega_cdm": Omega_m - 0.047,
        "N_eff": 3.04,
        'YHe': 0.24755048455476272,  #By hand, default value
        'P_k_max_1/Mpc': 100.,
        'z_max_pk': 0.5,
        'non linear': 'halofit'
    }
    class_cosmo = Class()
    class_cosmo.set(class_params)
    print("Running CLASS for P(k)")
    class_cosmo.compute()
    P_nl = np.array([class_cosmo.pk(ki, z) for ki in k]) * h**3
    P_lin = np.array([class_cosmo.pk_lin(ki, z) for ki in k]) * h**3
    print("CLASS computation complete")
    xi_lin = ct.xi.xi_mm_at_r(r, k / h, P_lin)
    xi_nl = ct.xi.xi_mm_at_r(r, k / h, P_nl)
    biases = ct.bias.bias_at_M(M, k, P_lin, Omega_m)
    bias_spline = IUS(np.log(M), biases)

    #Assemble the args dict
    args = {
        "z": z,
        "richness": richness,
        "R_lambda": R_lambda,
        "h": h,
        "Omega_m": Omega_m,
        "Sigma_crit_inverse": Sigma_crit_inverse,
        "DeltaSigma_data": DeltaSigma_data,
        "DeltaSigma_cov": Cov,
        "DeltaSigma_unc": DeltaSigma_unc,
        "R_mid": R_mid,
        "r": r,
        "R": R,
        "k": k / h,
        "P_lin": P_lin,
        "P_nl": P_nl,
        "xi_lin": xi_lin,
        "xi_nl": xi_nl,
        "bias_spline": bias_spline,
        "R_edges": R_edges,
        "z_title": z_title,
        "lambda_title": z_title
    }
    return args
Ejemplo n.º 12
0
def make_LSS_data(z, cosmo_dict, outfile=None):
    """
    Args:
        z (float): redshift
        cosmo_dict (dictionary): the CLASS cosmology
        outfile (string): file to save to
            
    """
    if outfile is None:
        outfile = "LSS_dict"

    LSS_dict = {}

    h = cosmo_dict["h"]
    Omega_b = cosmo_dict["Omega_b"]
    Omega_m = cosmo_dict["Omega_cdm"] + cosmo_dict["Omega_b"]
    n_s = cosmo_dict["n_s"]
    cosmo = Class()
    cosmo.set(cosmo_dict)
    cosmo.compute()
    sigma8 = cosmo.sigma8()
    print("sigma8 is:", sigma8)

    k = np.logspace(-5, 3, base=10, num=4000)  #1/Mpc; comoving
    kh = k / h  #h/Mpc; comoving
    r = np.logspace(-2, 3, num=1000)  #Mpc/h comoving
    M = np.logspace(12, 16.3, 1000)  #Msun/h

    z = np.asarray(z)
    for zi in z:
        P_nl = np.array([cosmo.pk(ki, zi) for ki in k]) * h**3
        P_lin = np.array([cosmo.pk_lin(ki, zi) for ki in k]) * h**3

        xi_nl = ct.xi.xi_mm_at_r(r, kh, P_nl)
        xi_lin = ct.xi.xi_mm_at_r(r, kh, P_lin)

        c = np.array([
            conc.concentration_at_M(Mi,
                                    kh,
                                    P_lin,
                                    n_s,
                                    Omega_b,
                                    Omega_m,
                                    h,
                                    Mass_type="mean") for Mi in M
        ])
        bias = ct.bias.bias_at_M(M, kh, P_lin, Omega_m)

        args_at_z = {
            "k": kh,
            "P_lin": P_lin,
            "P_nl": P_nl,
            "r": r,
            "xi_lin": xi_lin,
            "xi_nl": xi_nl,
            "M": M,
            "concentration": c,
            "bias": bias,
            "h": h,
            "Omega_m": Omega_m,
            "n_s": n_s,
            "sigma8": sigma8,
            "Omega_b": Omega_b
        }
        LSS_dict["args_at_{z:.3f}".format(z=zi)] = args_at_z

    #np.save(outfile, LSS_dict)
    pickle.dump(LSS_dict, open(outfile + ".p", "wb"))
    print("Saved {0}".format(outfile))
    return
Ejemplo n.º 13
0
def get_arguments(perc_index, fox_z_index, fox_lambda_index, zi, lj):
    """Creates the arguments dictionary that is passed around
    the various functions.

    Args:
        perc_index (int): index of the percolation model (0-3)
        fox_z_index (int): z-index for the fox snapshots (0-3)
        fox_lambda_index (int): lambda-index for the fox richness bins (0-6)
        zi (int): z-index of the DES Y1 data set (0-1), zi=2 should NOT be used in fox
        lj (int): lambda-index of the DES Y1 data set (3-6)
    """
    if not (0 <= fox_z_index <= 3):
        raise Exception("Invalid fox_z_inded value.")
    if not (0 <= fox_lambda_index <= 6):
        raise Exception("Invalid fox_lambda_inded value.")
    if not (0 <= zi <= 1): raise Exception("Invalid zi value.")
    if not (3 <= lj <= 6): raise Exception("Invalid lj value.")
    #Create a dictionary to add things
    print "Creating arguments dictionary"
    args = {}

    #Add the redshift
    zs = [1.0, 0.5, 0.25, 0.0]
    z = zs[fox_z_index]
    args['z'] = z
    print "\tz = %.2f" % z

    #Add the richnesses and compure R_lambda (Rlam) in Mpc/h comoving
    lams = np.loadtxt("Percolation_data/lambdas")
    lam = lams[fox_lambda_index]
    Rlams = (lams / 100.)**0.2  #Mpc/h comoving
    Rlam = Rlams[lj]
    args['Rlam'] = Rlam
    print "\tlambda = %.1f" % lam

    #Add the cosmology
    h = cosmo['h']  #to be used in this script
    args['h'] = h
    args['Omega_m'] = cosmo['om']
    print "\th = %.3f" % h
    print "\tOmega_m = %.3f" % args['Omega_m']

    #Add the prior for the multiplicative bias
    deltap1 = np.loadtxt("photoz_calibration/Y1_deltap1.txt")[zi, lj]
    deltap1_var = np.loadtxt("photoz_calibration/Y1_deltap1_var.txt")[zi, lj]
    Am_prior = deltap1 + 0.012  #photo-z + shear
    Am_prior_var = deltap1_var + 0.013**2  #photo-z + shear variance
    args['Am_prior'] = Am_prior
    args['Am_prior_var'] = Am_prior_var
    print "\tAm = %.3f +- %.3f" % (args['Am_prior'], args['Am_prior_var'])

    #Add the Sigma_crit_inverse value, after converting to pc^2/hMsun comoving
    SCI = np.loadtxt("photoz_calibration/sigma_crit_inv.txt")[zi, lj] * h * (
        1 + z)**2
    args['Sigma_crit_inv'] = SCI

    #Add on radial bins
    r = np.logspace(-2, 3, num=1000, base=10)  #3d radii, Mpc/h comoving
    Rp = np.logspace(-2, 2.4, num=1000,
                     base=10)  #perpendicular radii, Mpc/h comoving
    args['r'] = r
    args['Rp'] = Rp

    #Compute the power spectrum and xi_mm
    #First, make a 'CLASS-formatted' cosmology dictionary
    from classy import Class
    params = {
        "output": "mPk",
        "h": h,
        "sigma8": 0.835,
        "n_s": cosmo["ns"],
        "Omega_b": cosmo["ob"],
        "Omega_cdm": cosmo["om"] - cosmo["ob"],
        "YHe": 0.24755048455476272,  #By hand, default value
        "P_k_max_1/Mpc": 1000.,  #3000.,
        "z_max_pk": 1.0,
        "non linear": "halofit"
    }
    class_cosmo = Class()
    class_cosmo.set(params)
    print "\tConfiguring CLASS cosmology"
    class_cosmo.compute()
    print "\tComputing P(k,z) using CLASS"
    k = np.logspace(-5, 3, base=10, num=4000)  #1/Mpc, apparently
    kh = k / h  #h/Mpc
    args['k'] = kh
    #Call class to compute P(k,z)
    Pnl = np.array([class_cosmo.pk(ki, z) for ki in k])
    Plin = np.array([class_cosmo.pk_lin(ki, z) for ki in k])
    Pnl *= h**3  #matter power spectrum, (Mpc/h)^3
    Plin *= h**3  #linear matter power spectrum, (Mpc/h)^3
    args['Pnl'] = Pnl
    args['Plin'] = Plin
    #Call the toolkit to compute xi(r,z) from P(k,z)
    print "\tcalling the toolkit to compute xi_mm"
    xi_nl = ct.xi.xi_mm_at_R(r, k, Pnl)
    xi_lin = ct.xi.xi_mm_at_R(r, k, Plin)
    args['xi_nl'] = xi_nl
    args['xi_lin'] = xi_lin

    #Add the edges of the radial bins (Y1 version), Mpc/h comoving
    #Note that the bin edges are defined in Mpc physical
    Nbins = 15
    Redges = np.logspace(np.log10(0.0323), np.log10(30.), num=Nbins + 1)
    Rmid = (Redges[:-1] + Redges[1:]) / 2.
    print Rmid
    args['Redges'] = Redges * h * (1 + z)  #converted to Mpc/h comoving

    #Add the indices used for scale cuts
    #Note: no upper limit scale cut
    inds = (Rmid > 0.2) * (Rmid < 9999)  #0.2 Mpc physical scale cut
    args['inds'] = inds

    #Add the covariance matrix
    #fullbase = "/Users/tmcclintock/Data" #laptop
    #fullbase = "/calvin1/tmcclintock/DES_DATA_FILES" #calvin
    #y1base = fullbase+"/DATA_FILES/y1_data_files/FINAL_FILES/"
    covpath = "SACs/SAC_z%d_l%d.txt" % (zi, lj)
    #y1base+"SACs/SAC_z%d_l%d.txt"%(zi, lj)
    cov = np.genfromtxt(covpath)
    cov = cov[inds]
    cov = cov[:, inds]
    #Apply the hartlap correction
    Njk = 100.
    D = len(Rmid[inds])
    cov *= (Njk - 1) / (Njk - D - 2)
    print "\tlen(DeltaSigma) = %d\n\tNjk = %d" % (D, Njk)
    icov = np.linalg.inv(cov)
    args['icov'] = icov  #(pc^2/Msun physical)^2

    #Add the boost factor data
    #boostpath = y1base+"/full-unblind-v2-mcal-zmix_y1clust_l%d_z%d_zpdf_boost.dat"%(lj, zi)
    #bcovpath = y1base+"/full-unblind-v2-mcal-zmix_y1clust_l%d_z%d_zpdf_boost_cov.dat"%(lj, zi)
    boostpath = "boostfactors/full-unblind-v2-mcal-zmix_y1clust_l%d_z%d_zpdf_boost.dat" % (
        lj, zi)
    bcovpath = "boostfactors/full-unblind-v2-mcal-zmix_y1clust_l%d_z%d_zpdf_boost_cov.dat" % (
        lj, zi)
    Bcov = np.loadtxt(bcovpath)
    Rb, Bp1, Be = np.genfromtxt(boostpath, unpack=True)  #Rb is Mpc physical
    Becut = (Be > 1e-6) * (Rb > 0.2)  #Some boost factors are 0. Exclude those
    Bp1 = Bp1[Becut]
    Rb = Rb[Becut]
    Be = Be[Becut]
    Bcov = Bcov[Becut]
    Bcov = Bcov[:, Becut]
    Njk = 100.
    D = len(Rb)
    Bcov *= (Njk - 1.) / (Njk - D - 2)  #Apply the Hartlap correction
    icov_B = np.linalg.inv(Bcov)
    args['Rb'] = Rb
    args['iBcov'] = icov_B
    args['Bp1'] = Bp1

    #Add the DeltaSigma data vector
    mass_lim_labels = [
        "3e12_5e12", "5e12_9e12", "9e12_2e13", "2e13_6e13", "6e13_2e14",
        "2e14_5e14", "5e14_5e15"
    ]
    lab = mass_lim_labels[fox_lambda_index]
    DS = np.loadtxt("Percolation_data/fixedmeanDeltaSigma_i%d_%s_z%.1f" %
                    (perc_index, lab, z))  #h Msun/pc^2 comoving
    DS *= h * (1 + z)**2  #Msun/pc^2 physical
    args['ds'] = DS[inds]  #take only the useful indices

    return args
Ejemplo n.º 14
0
class Cosmology(object):
    """
    Class to hold the basic cosmology and CLASS attributes. This can be initialized by a set of cosmological parameters or a pre-defined cosmology.

    Loaded cosmological models:

    - **Planck18**: Bestfit cosmology from Planck 2018, using the baseline TT,TE,EE+lowE+lensing likelihood.
    - **Quijote**: Fiducial cosmology from the Quijote simulations of Francisco Villaescusa-Navarro et al.
    - **Abacus**: Fiducial cosmology from the Abacus simulations of Lehman Garrison et al.

    Args:
        redshift (float): Desired redshift :math:`z`
        name (str): Load cosmology from a list of predetermined cosmologies (see above).
        params (kwargs): Any other CLASS parameters. (Note that sigma8 does not seem to be supported by CLASS in Python 3).

    Keyword Args:
        verb (bool): If true output useful messages througout run-time, default: False.
        npoints (int): Number of points to use in the interpolators for sigma^2, default: 100000

    """

    loaded_models = {'Quijote':{"h":0.6711,"omega_cdm":(0.3175 - 0.049)*0.6711**2,
                                "Omega_b":0.049, "n_s":0.9624,
                                "N_eff":3.046, "A_s":2.134724e-09}, #"sigma8":0.834,
                     'Abacus':{"h":0.6726,"omega_cdm":0.1199,
                                "omega_b":0.02222,"n_s":0.9652,"A_s":2.135472e-09,#"sigma8":0.830,
                                "N_eff":3.046},
                     'Planck18':{"h":0.6732,"omega_cdm":0.12011,"omega_b":0.022383,
                                "n_s":0.96605,"A_s":2.042644e-09}}#,"sigma8":0.8120}}

    def __init__(self,redshift,name="",verb=False,npoints=int(1e5),**params):

        """
        Initialize the cosmology class with cosmological parameters or a defined model.

        """
        ## Load parameters into a dictionary to pass to CLASS
        class_params = dict(**params)
        if len(name)>0:
            if len(params.items())>0:
                raise Exception('Must either choose a preset cosmology or specify parameters!')
            if name in self.loaded_models.keys():
                if verb: print('Loading the %s cosmology at z = %.2f'%(name,redshift))
                loaded_model = self.loaded_models[name]
                for key in loaded_model.keys():
                    class_params[key] = loaded_model[key]
            else:
                raise Exception("This cosmology isn't yet implemented")
        else:
            if len(params.items())==0:
                if verb: print('Using default CLASS cosmology')
            for name, param in params.items():
                class_params[name] = param

        ## # Check we have the correct parameters
        if 'sigma8' in class_params.keys() and 'A_s' in class_params.keys():
            raise NameError('Cannot specify both A_s and sigma8!')

        ## Define other parameters
        self.z = redshift
        self.a = 1./(1.+redshift)
        if 'output' not in class_params.keys():
            class_params['output']='mPk'
        if 'P_k_max_h/Mpc' not in class_params.keys() and 'P_k_max_1/Mpc' not in class_params.keys():
            class_params['P_k_max_h/Mpc']=300.
        if 'z_pk' in class_params.keys():
            assert class_params['z_pk']==redshift, "Can't pass multiple redshifts!"
        else:
            class_params['z_pk']=redshift

        ## Load CLASS and set parameters
        if verb: print('Loading CLASS')
        self.cosmo = Class()
        self.cosmo.set(class_params)
        self.cosmo.compute()
        self.h = self.cosmo.h()
        self.name = name
        self.npoints = npoints
        self.verb = verb

        ## Check if we're using neutrinos here
        if self.cosmo.Omega_nu>0.:
            if self.verb: print("Using a neutrino fraction of Omega_nu = %.3e"%self.cosmo.Omega_nu)
            self.use_neutrinos = True
            # Define neutrino mass fraction
            self.f_nu = self.cosmo.Omega_nu/self.cosmo.Omega_m()
            if self.cosmo.Neff()>3.5:
                print("N_eff > 3.5, which seems large (standard value: 3.046). This may indicate that N_ur has not been set.")
        else:
            if self.verb: print("Assuming massless neturinos.")
            self.use_neutrinos = False

        ## Create a vectorized sigma(R) function from CLASS
        if self.use_neutrinos:
            self.vector_sigma_R = np.vectorize(lambda r: self.cosmo.sigma_cb(r/self.h,self.z))
        else:
            self.vector_sigma_R = np.vectorize(lambda r: self.cosmo.sigma(r/self.h,self.z))

        # get density in physical units at z = 0
        # rho_critical is in Msun/h / (Mpc/h)^3 units
        # rhoM is in **physical** units of Msun/Mpc^3
        self.rho_critical = ((3.*100.*100.)/(8.*np.pi*6.67408e-11)) * (1000.*1000.*3.085677581491367399198952281E+22/1.9884754153381438E+30)
        self.rhoM = self.rho_critical*self.cosmo.Omega0_m()

    def compute_linear_power(self,kh,kh_min=0.,with_neutrinos=False):
        """Compute the linear power spectrum from CLASS for a vector of input k.

        If set, we remove any modes below some minimum k.

        Args:
            kh (float, np.ndarray): Wavenumber or vector of wavenumbers (in h/Mpc units) to compute linear power with.

        Keyword Args:
            kh_min (float): Value of k (in h/Mpc units) below which to set :math:`P(k) = 0`, default: 0.
            with_neutrinos (bool): If True, return the full matter power spectrum, else return the CDM+baryon power spectrum (which is generally used in the halo model). Default: False.

        Returns:
            np.ndarray: Linear power spectrum in :math:`(h^{-1}\mathrm{Mpc})^3` units
        """

        if type(kh)==np.ndarray:

            # Define output vector and filter modes with too-small k
            output = np.zeros_like(kh)
            filt = np.where(kh>kh_min)
            N_k = len(filt[0])

            # Compute Pk using CLASS (vectorized)
            if not hasattr(self,'vector_linear_power'):
                ## NB: This works in physical 1/Mpc units so we convert here
                if self.use_neutrinos:
                    # Here we need both the CDM+baryon (cb) power spectra and the full matter power spectra
                    # The CDM+baryon spectrum is used for the halo model parts, and the residual (matter-cb) added at the end
                    self.vector_linear_power = np.vectorize(lambda k: self.cosmo.pk_cb_lin(k*self.h,self.z)*self.h**3.)
                    self.vector_linear_power_total = np.vectorize(lambda k: self.cosmo.pk_lin(k*self.h,self.z)*self.h**3.)
                else:
                    self.vector_linear_power = np.vectorize(lambda k: self.cosmo.pk_lin(k*self.h,self.z)*self.h**3.)

            if self.use_neutrinos and with_neutrinos:
                output[filt] = self.vector_linear_power_total(kh[filt])
            else:
                output[filt] = self.vector_linear_power(kh[filt])
            return output

        else:
            if kh<kh_min:
                return 0.
            else:
                if self.use_neutrinos and with_neutrinos:
                    return self.vector_linear_power_total(kh)
                else:
                    return self.vector_linear_power(kh)

    def sigma_logM_int(self,logM_h):
        """Return the value of :math:`\sigma(M,z)` using the prebuilt interpolators, which are constructed if not present.

        Args:
            logM (np.ndarray): Input :math:`\log_{10}(M/h^{-1}M_\mathrm{sun})`

        Returns:
            np.ndarray: :math:`\sigma(M,z)`
        """
        if not hasattr(self,'sigma_logM_int_func'):
            self._interpolate_sigma_and_deriv(npoints=self.npoints)
        return self._sigma_logM_int_func(logM_h)

    def dlns_dlogM_int(self,logM_h):
        """Return the value of :math:`d\ln\sigma/d\log M` using the prebuilt interpolators, which are constructed if not present.

        Args:
            logM (np.ndarray): Input :math:`\log_{10}(M/h^{-1}M_\mathrm{sun})`

        Returns:
            np.ndarray: :math:`d\ln\sigma/d\log M`
        """
        if not hasattr(self,'dlns_dlogM_int_func'):
            self._interpolate_sigma_and_deriv(npoints=self.npoints)
        return self._dlns_dlogM_int_func(logM_h)

    def _sigmaM(self,M_h):
        """Compute :math:`\sigma(M,z)` from CLASS as a vector function.

        Args:
            M_h (np.ndarray): Mass in :math:`h^{-1}M_\mathrm{sun}` units.
            z (float): Redshift.

        Returns:
            np.ndarray: :math:`\sigma(M,z)`
        """
        # convert to Lagrangian radius
        r_h = np.power((3.*M_h)/(4.*np.pi*self.rhoM),1./3.)
        sigma_func = self.vector_sigma_R(r_h)
        return sigma_func

    def _interpolate_sigma_and_deriv(self,logM_h_min=6,logM_h_max=17,npoints=int(1e5)):
        """Create an interpolator function for :math:`d\ln\sigma/d\log M` and :math:`sigma(M)`.

        NB: This has no effect if the interpolator has already been computed.

        Keyword Args:
            logM_min (float): Minimum mass in :math:`\log_{10}(M/h^{-1}M_\mathrm{sun})`, default: 6
            logM_max (float): Maximum mass in :math:`\log_{10}(M/h^{-1}M_\mathrm{sun})`, default 17
            npoints (int): Number of sampling points, default 100000

        """

        if not hasattr(self,'_sigma_logM_int_func'):
            if self.verb: print("Creating an interpolator for sigma(M) and its derivative.")
            ## Compute log derivative by interpolation and numerical differentiation
            # First compute the grid of M and sigma
            M_h_grid = np.logspace(logM_h_min,logM_h_max,10000)
            all_sigM = self._sigmaM(M_h_grid)
            logM_h_grid = np.log10(M_h_grid)

            # Define ln(sigma) and numerical derivatives
            all_lns = np.log(all_sigM)
            all_diff = -np.diff(all_lns)/np.diff(logM_h_grid)
            mid_logM_h = 0.5*(logM_h_grid[:-1]+logM_h_grid[1:])

            self._sigma_logM_int_func = interp1d(logM_h_grid,all_sigM)
            self._dlns_dlogM_int_func = interp1d(mid_logM_h,all_diff)

    def _h_over_h0(self):
        """Return the value of :math:`H(z)/H(0)` at the class redshift

        Returns:
            float: :math:`H(z)/H(0)`
        """
        Omega0_k = 1.-self.cosmo.Omega0_m()-self.cosmo.Omega_Lambda()
        Ea = np.sqrt((self.cosmo.Omega0_m()+self.cosmo.Omega_Lambda()*pow(self.a,-3)+Omega0_k*self.a)/pow(self.a,3))
        return Ea

    def _Omega_m(self):
        """Return the value of :math:`\Omega_m(z)` at the class redshift