def clkk_gen(Omega_m, A_se9, zs=1.0): A_s = A_se9 * 1e-9 omch2 = (OmegaM - OmegaB) * h**2 LambdaCDM = Class() LambdaCDM.set({ 'omega_b': ombh2, 'omega_cdm': omch2, 'h': h, 'A_s': A_s, 'n_s': n_s }) LambdaCDM.set({ 'output': 'mPk,sCl', 'P_k_max_1/Mpc': 10.0, 'l_switch_limber': 100, 'selection': 'dirac', 'selection_mean': zs, 'l_max_lss': lmax, 'non linear': 'halofit' }) # run class LambdaCDM.compute() si8 = LambdaCDM.sigma8() cls = LambdaCDM.density_cl(lmax) ell = cls['ell'][2:] clphiphi = cls['ll'][0][2:] clkk = 1.0 / 4 * (ell + 2.0) * (ell + 1.0) * (ell) * (ell - 1.0) * clphiphi return si8, ell, clkk
def class_pk(self, z, cosmo_params=None, pk_params=None, return_s8=False): if cosmo_params is None: cosmo_params = self.cosmo_params if pk_params is None: pk_params = self.pk_params cosmoC = Class() h = cosmo_params['h'] class_params = { 'h': h, 'omega_b': cosmo_params['Omb'] * h**2, 'omega_cdm': (cosmo_params['Om'] - cosmo_params['Omb']) * h**2, 'A_s': cosmo_params['Ase9'] * 1.e-9, 'n_s': cosmo_params['ns'], 'output': 'mPk', 'z_max_pk': 100, #max(z)*2, #to avoid class error. #Allegedly a compiler error, whatever that means 'P_k_max_1/Mpc': pk_params['kmax'] * h * 1.1, } if pk_params['non_linear'] == 1: class_params['non linear'] = 'halofit' class_params['N_ur'] = 3.04 #ultra relativistic species... neutrinos if cosmo_params['mnu'] != 0: class_params['N_ur'] -= 1 #one massive neutrino class_params['m_ncdm'] = cosmo_params['mnu'] class_params['N_ncdm'] = 3.04 - class_params['N_ur'] if cosmo_params['w'] != -1 or cosmo_params['wa'] != 0: class_params['Omega_fld'] = cosmo_params['Oml'] class_params['w0_fld'] = cosmo_params['w'] class_params['wa_fld'] = cosmo_params['wa'] for ke in class_accuracy_settings.keys(): class_params[ke] = class_accuracy_settings[ke] cosmoC = Class() cosmoC.set(class_params) try: cosmoC.compute() except Exception as err: print(class_params, err) raise Exception('Class crashed') k = self.kh * h pkC = np.array([[cosmoC.pk(ki, zj) for ki in k] for zj in z]) pkC *= h**3 s8 = cosmoC.sigma8() cosmoC.struct_cleanup() if return_s8: return pkC, self.kh, s8 else: return pkC, self.kh
def class_pk(self, z, cosmo_params=None, pk_params=None, return_s8=False): #output is in same unit as CAMB if not cosmo_params: cosmo_params = self.cosmo_params if not pk_params: pk_params = self.pk_params kh = np.logspace(np.log10(pk_params['kmin']), np.log10(pk_params['kmax']), pk_params['nk']) cosmoC = Class() h = cosmo_params['h'] class_params = { 'h': h, 'omega_b': cosmo_params['Omb'] * h**2, 'omega_cdm': (cosmo_params['Om'] - cosmo_params['Omb']) * h**2, 'A_s': cosmo_params['As'], 'n_s': cosmo_params['ns'], 'output': 'mPk', 'z_max_pk': max(z) + 0.1, 'P_k_max_1/Mpc': pk_params['kmax'] * h, } if pk_params['non_linear'] == 1: class_params['non linear'] = 'halofit' class_params['N_ur'] = 3.04 #ultra relativistic species... neutrinos if cosmo_params['mnu'] != 0: class_params['N_ur'] -= 1 #one massive neutrino class_params['m_ncdm'] = cosmo_params['mnu'] class_params['N_ncdm'] = 3.04 - class_params['N_ur'] if cosmo_params['w'] != -1: class_params['Omega_fld'] = cosmo_params['Oml'] class_params['w0_fld'] = cosmo_params['w'] class_params['wa_fld'] = cosmo_params['wa'] for ke in class_accuracy_settings.keys(): class_params[ke] = class_accuracy_settings[ke] cosmoC = Class() cosmoC.set(class_params) cosmoC.compute() k = kh * h #output is in same unit as CAMB pkC = np.array([[cosmoC.pk(ki, zj) for ki in k] for zj in z]) pkC *= h**3 s8 = cosmoC.sigma8() cosmoC.struct_cleanup() if return_s8: return pkC, kh, s8 else: return pkC, kh
def compute_Sigma8(self): # compute the values of sigma_8 # given that we have already assigned # the cosmologies # this part does not depend on the systematics cosmo = Class() cosmo.set(self.cosmoParams) if self.settings.include_neutrino: cosmo.set(self.other_settings) cosmo.set(self.neutrino_settings) cosmo.set(self.class_argumets) try: cosmo.compute() except CosmoComputationError as failure_message: print(failure_message) self.sigma_8 = np.nan except CosmoSevereError as critical_message: print(critical_message) self.sigma_8 = np.nan sigma_8 = cosmo.sigma8() cosmo.struct_cleanup() cosmo.empty() del cosmo return sigma_8
def setup_class(self): obh2, och2, w, ns, ln10As, H0, Neff = self.parameters 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, #'sigma8':sigma8, '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.,'non linear':'halofit'} cosmo = Class() cosmo.set(params) print("CLASS is computing") cosmo.compute() print("\tCLASS done") self.class_cosmo_object = cosmo self.sigma8 = cosmo.sigma8() return
b4ar = [ 256.82199304134315, 78.62142674299282, 374.08451421691973, -146.54664459312085 ] norm = 1. # b1 = 1.909433 # b2 = -2.357092 # bG2 = 3.818261e-01 # css0 = -2.911944e+01 # css2 = -1.235181e+01 # Pshot = 2.032084e+03 # bGamma3 = 0. # b4 = 1.924983e+02 print('S8=', cosmo.sigma8() * (cosmo.Omega_m() / 0.3)**0.5) kmsMpc = 3.33564095198145e-6 rd = cosmo.rs_drag() print('rd=', rd) for j in range(len(chunk)): z = zs[j] b1 = b1ar[j] b2 = b2ar[j] bG2 = bG2ar[j] css0 = css0ar[j] css2 = css2ar[j] Pshot = Pshotar[j] bGamma3 = bGamma3ar[j] b4 = b4ar[j]
def fitEE(self): # function to cimpute the band powers cosmo = Class() cosmo.set(self.cosmoParams) if self.settings.include_neutrino: cosmo.set(self.other_settings) cosmo.set(self.neutrino_settings) cosmo.set(self.class_argumets) try: cosmo.compute() except CosmoComputationError as failure_message: print(failure_message) self.sigma_8 = np.nan cosmo.struct_cleanup() cosmo.empty() return np.array([np.nan] * self.nzcorrs * self.bo_EE), np.array( [np.nan] * self.nzcorrs * self.bo_EE), np.array( [np.nan] * self.nzcorrs * self.bo_EE) except CosmoSevereError as critical_message: print(critical_message) self.sigma_8 = np.nan cosmo.struct_cleanup() cosmo.empty() return np.array([np.nan] * self.nzcorrs * self.bo_EE), np.array( [np.nan] * self.nzcorrs * self.bo_EE), np.array( [np.nan] * self.nzcorrs * self.bo_EE) # retrieve Omega_m and h from cosmo (CLASS) self.Omega_m = cosmo.Omega_m() self.small_h = cosmo.h() self.rho_crit = self.get_critical_density() # derive the linear growth factor D(z) linear_growth_rate = np.zeros_like(self.redshifts) # print self.redshifts for index_z, z in enumerate(self.redshifts): try: # for CLASS ver >= 2.6: linear_growth_rate[ index_z] = cosmo.scale_independent_growth_factor(z) except BaseException: # my own function from private CLASS modification: linear_growth_rate[index_z] = cosmo.growth_factor_at_z(z) # normalize to unity at z=0: try: # for CLASS ver >= 2.6: linear_growth_rate /= cosmo.scale_independent_growth_factor(0.) except BaseException: # my own function from private CLASS modification: linear_growth_rate /= cosmo.growth_factor_at_z(0.) # get distances from cosmo-module: r, dzdr = cosmo.z_of_r(self.redshifts) self.sigma_8 = cosmo.sigma8() # Get power spectrum P(k=l/r,z(r)) from cosmological module # this doesn't really have to go into the loop over fields! pk = np.zeros((self.settings.nellsmax, self.settings.nzmax), 'float64') k_max_in_inv_Mpc = self.settings.k_max_h_by_Mpc * self.small_h # note that this is being computed at only nellsmax # followed by an interplation record = np.zeros((self.settings.nellsmax, self.settings.nzmax)) record_k = np.zeros((self.settings.nellsmax, self.settings.nzmax)) for index_ells in range(self.settings.nellsmax): for index_z in range(1, self.settings.nzmax): k_in_inv_Mpc = (self.ells[index_ells] + 0.5) / r[index_z] z = self.redshifts[index_z] record[index_ells, index_z] = self.baryon_feedback_bias_sqr( k_in_inv_Mpc / self.small_h, self.redshifts[index_z], A_bary=self.systematics['A_bary']) record_k[index_ells, index_z] = k_in_inv_Mpc self.record_bf = record[:, 1:].flatten() self.record_k = record_k[:, 1:].flatten() self.k_max_in_inv_Mpc = k_max_in_inv_Mpc for index_ells in range(self.settings.nellsmax): for index_z in range(1, self.settings.nzmax): # standard Limber approximation: # k = ells[index_ells] / r[index_z] # extended Limber approximation (cf. LoVerde & Afshordi 2008): k_in_inv_Mpc = (self.ells[index_ells] + 0.5) / r[index_z] if k_in_inv_Mpc > k_max_in_inv_Mpc: pk_dm = 0. else: pk_dm = cosmo.pk(k_in_inv_Mpc, self.redshifts[index_z]) # pk[index_ells,index_z] = cosmo.pk(ells[index_ells]/r[index_z], self.redshifts[index_z]) if self.settings.baryon_feedback: pk[index_ells, index_z] = pk_dm * self.baryon_feedback_bias_sqr( k_in_inv_Mpc / self.small_h, self.redshifts[index_z], A_bary=self.systematics['A_bary']) else: pk[index_ells, index_z] = pk_dm # for KiDS-450 constant biases in photo-z are not sufficient: if self.settings.bootstrap_photoz_errors: # draw a random bootstrap n(z); borders are inclusive! random_index_bootstrap = np.random.randint( int(self.settings.index_bootstrap_low), int(self.settings.index_bootstrap_high) + 1) # print 'Bootstrap index:', random_index_bootstrap pz = np.zeros((self.settings.nzmax, self.nzbins), 'float64') pz_norm = np.zeros(self.nzbins, 'float64') for zbin in range(self.nzbins): redshift_bin = self.redshift_bins[zbin] # ATTENTION: hard-coded subfolder! # index can be recycled since bootstraps for tomographic bins # are independent! fname = os.path.join( self.settings.data_directory, '{:}/bootstraps/{:}/n_z_avg_bootstrap{:}.hist'.format( self.settings.photoz_method, redshift_bin, random_index_bootstrap)) z_hist, n_z_hist = np.loadtxt(fname, unpack=True) shift_to_midpoint = np.diff(z_hist)[0] / 2. spline_pz = itp.splrep(z_hist + shift_to_midpoint, n_z_hist) mask_min = self.redshifts >= z_hist.min() + shift_to_midpoint mask_max = self.redshifts <= z_hist.max() + shift_to_midpoint mask = mask_min & mask_max # points outside the z-range of the histograms are set to 0! pz[mask, zbin] = itp.splev(self.redshifts[mask], spline_pz) dz = self.redshifts[1:] - self.redshifts[:-1] pz_norm[zbin] = np.sum(0.5 * (pz[1:, zbin] + pz[:-1, zbin]) * dz) pr = pz * (dzdr[:, np.newaxis] / pz_norm) else: pr = self.pz * (dzdr[:, np.newaxis] / self.pz_norm) # pr[pr < 0] = 0 g = np.zeros((self.settings.nzmax, self.nzbins), 'float64') for zbin in range(self.nzbins): # assumes that z[0] = 0 for nr in range(1, self.settings.nzmax - 1): # for nr in range(self.nzmax - 1): fun = pr[nr:, zbin] * (r[nr:] - r[nr]) / r[nr:] g[nr, zbin] = np.sum(0.5 * (fun[1:] + fun[:-1]) * (r[nr + 1:] - r[nr:-1])) g[nr, zbin] *= 2. * r[nr] * (1. + self.redshifts[nr]) # Start loop over l for computation of C_l^shear Cl_GG_integrand = np.zeros( (self.settings.nzmax, self.nzbins, self.nzbins), 'float64') Cl_GG = np.zeros((self.settings.nellsmax, self.nzbins, self.nzbins), 'float64') Cl_II_integrand = np.zeros_like(Cl_GG_integrand) Cl_II = np.zeros_like(Cl_GG) Cl_GI_integrand = np.zeros_like(Cl_GG_integrand) Cl_GI = np.zeros_like(Cl_GG) dr = r[1:] - r[:-1] for index_ell in range(self.settings.nellsmax): # find Cl_integrand = (g(r) / r)**2 * P(l/r,z(r)) for zbin1 in range(self.nzbins): for zbin2 in range(zbin1 + 1): # self.nzbins): Cl_GG_integrand[1:, zbin1, zbin2] = g[1:, zbin1] * \ g[1:, zbin2] / r[1:]**2 * pk[index_ell, 1:] factor_IA = self.get_factor_IA( self.redshifts[1:], linear_growth_rate[1:], self.systematics['A_IA']) # / self.dzdr[1:] # print F_of_x # print self.eta_r[1:, zbin1].shape Cl_II_integrand[1:, zbin1, zbin2] = pr[1:, zbin1] * \ pr[1:, zbin2] * factor_IA**2 / r[1:]**2 * pk[index_ell, 1:] pref = g[1:, zbin1] * pr[1:, zbin2] + g[1:, zbin2] * pr[ 1:, zbin1] Cl_GI_integrand[1:, zbin1, zbin2] = pref * factor_IA / r[1:]**2 * pk[ index_ell, 1:] # Integrate over r to get C_l^shear_ij = P_ij(l) # C_l^shear_ii = 9/4 Omega0_m^2 H_0^4 \sum_0^rmax dr (g_i(r) g_j(r) # /r**2) P(k=l/r,z(r)) for zbin1 in range(self.nzbins): for zbin2 in range(zbin1 + 1): # self.nzbins): Cl_GG[index_ell, zbin1, zbin2] = np.sum( 0.5 * (Cl_GG_integrand[1:, zbin1, zbin2] + Cl_GG_integrand[:-1, zbin1, zbin2]) * dr) # here we divide by 16, because we get a 2^2 from g(z)! Cl_GG[index_ell, zbin1, zbin2] *= 9. / 16. * \ self.Omega_m**2 # in units of Mpc**4 # dimensionless Cl_GG[index_ell, zbin1, zbin2] *= (self.small_h / 2997.9)**4 Cl_II[index_ell, zbin1, zbin2] = np.sum( 0.5 * (Cl_II_integrand[1:, zbin1, zbin2] + Cl_II_integrand[:-1, zbin1, zbin2]) * dr) Cl_GI[index_ell, zbin1, zbin2] = np.sum( 0.5 * (Cl_GI_integrand[1:, zbin1, zbin2] + Cl_GI_integrand[:-1, zbin1, zbin2]) * dr) # here we divide by 4, because we get a 2 from g(r)! Cl_GI[index_ell, zbin1, zbin2] *= 3. / 4. * self.Omega_m Cl_GI[index_ell, zbin1, zbin2] *= (self.small_h / 2997.9)**2 # ordering of redshift bins is correct in definition of theory below! theory_EE_GG = np.zeros((self.nzcorrs, self.bo_EE), 'float64') theory_EE_II = np.zeros((self.nzcorrs, self.bo_EE), 'float64') theory_EE_GI = np.zeros((self.nzcorrs, self.bo_EE), 'float64') index_corr = 0 # A_noise_corr = np.zeros(self.nzcorrs) for zbin1 in range(self.nzbins): for zbin2 in range(zbin1 + 1): # self.nzbins): # correlation = 'z{:}z{:}'.format(zbin1 + 1, zbin2 + 1) # print(zbin1, zbin2) Cl_sample_GG = Cl_GG[:, zbin1, zbin2] spline_Cl_GG = itp.splrep(self.ells, Cl_sample_GG) D_l_EE_GG = self.ell_norm * \ itp.splev(self.ells_sum, spline_Cl_GG) theory_EE_GG[index_corr, :] = self.get_theory( self.ells_sum, D_l_EE_GG, self.band_window_matrix, index_corr, band_type_is_EE=True) Cl_sample_GI = Cl_GI[:, zbin1, zbin2] spline_Cl_GI = itp.splrep(self.ells, Cl_sample_GI) D_l_EE_GI = self.ell_norm * \ itp.splev(self.ells_sum, spline_Cl_GI) theory_EE_GI[index_corr, :] = self.get_theory( self.ells_sum, D_l_EE_GI, self.band_window_matrix, index_corr, band_type_is_EE=True) Cl_sample_II = Cl_II[:, zbin1, zbin2] spline_Cl_II = itp.splrep(self.ells, Cl_sample_II) D_l_EE_II = self.ell_norm * \ itp.splev(self.ells_sum, spline_Cl_II) theory_EE_II[index_corr, :] = self.get_theory( self.ells_sum, D_l_EE_II, self.band_window_matrix, index_corr, band_type_is_EE=True) index_corr += 1 cosmo.struct_cleanup() cosmo.empty() return theory_EE_GG.flatten(), theory_EE_GI.flatten( ), theory_EE_II.flatten()
Plin = calc(params, z, reset=True) ax.loglog(k, Plin, c=colors[i], label=r"$z=%.1f$" % z) ax.legend(frameon=False) #Now the cosmo models cmap = vapeplot.cmap('vaporwave') colors = [cmap(ci) for ci in np.linspace(0, 1, 3)] z = 0 ax = axes[0] Plin = calc(params, 0, reset=False) ax.loglog(k, Plin, c=colors[0], label=r'$\Omega_m = %.2f,\ \sigma_8=%.2f$' % (0.3, cosmo.sigma8())) Om = 0.35 params['Omega_cdm'] = Om - 0.05 cosmo.set(params) cosmo.compute() Plin = calc(params, 0, reset=False) ax.loglog(k, Plin, c=colors[1], label=r'$\Omega_m = %.2f,\ \sigma_8=%.2f$' % (Om, cosmo.sigma8())) Om = 0.3 params['Omega_cdm'] = Om - 0.05 params['sigma8'] = 0.98
def lookup_Pk(cosmology='planck',nonlinear=0): """ it saves the lookup table of the (non) linear power spectrum generate from CLASS. If nonlinear is False (default) it generates the linear power spectrum. You can choose between - planck - wmap - ML Choose also whether you want a nonlinear power spectrum, default is linear (nonlinear=0) """ # k in h/Mpc k = N.logspace(-4., 3., 3*1024) if nonlinear==1: hf = 'halofit' saveto = 'data_itam/'+cosmology+'_pk.txt' else: hf = '' saveto = 'data_itam/'+cosmology+'_pk_linear.txt' if cosmology == 'planck': class_params = { 'non linear': hf, 'output': ['mPk','vTk'], 'P_k_max_1/Mpc': 1000., 'z_pk': 0., 'A_s': 2.3e-9, 'n_s': 0.96, 'h': 0.7, 'omega_b': 0.0225, 'Omega_cdm': 0.25, } sig8_0 = 0.8 elif cosmology == 'wmap': class_params = { 'non linear': hf, 'output': ['mPk','vTk'], 'P_k_max_1/Mpc': 1000., 'z_pk': 0., 'A_s': 2.3e-9, 'n_s': 0.967, 'h': 0.704, 'omega_b': 0.02253, 'Omega_cdm': 0.226, } sig8_0 = 0.81 elif cosmology == 'ML': class_params = { 'non linear': hf, 'output': ['mPk','vTk'], 'P_k_max_1/Mpc': 1000., 'z_pk': 0., 'A_s': 2.3e-9, 'n_s': 1., 'h': 0.73, 'omega_b': 0.045*0.73**2, 'Omega_cdm': 0.25-0.045, } sig8_0 = 0.9 else: raise ValueError("the cosmology you chose does not exist") cosmoClass_nl = Class() cosmoClass_nl.set(class_params) cosmoClass_nl.compute() # rescale the normalization of matter power spectrum to have sig8=0.8 today sig8 = cosmoClass_nl.sigma8() A_s = cosmoClass_nl.pars['A_s'] cosmoClass_nl.struct_cleanup() # does not clean the input class_params, cosmo.empty() does that cosmoClass_nl.set(A_s=A_s*(sig8_0*1./sig8)**2) cosmoClass_nl.compute() h = cosmoClass_nl.pars['h'] pk_nl = N.asarray([ cosmoClass_nl.pk(x*h, 0.,)*h**3 for x in k ]) kpk = N.vstack((k,pk_nl)) N.savetxt(saveto,kpk) print('saving', saveto ) return
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
class ModelPk(object): """ """ logger = logging.getLogger(__name__) def __init__(self, **param_dict): """ """ self.params = params.copy() self.class_params = class_params.copy() self.set(**param_dict) #other params for CLASS self._cosmo = None self._redshift_func = None self._logpk_func = None if self.params['mpk'] is not None: self.load_pk_from_file(self.params['mpk']) def load_pk_from_file(self, path): """ """ self.logger.info(f"Loading matter power spectrum from file {path}") k, pk = np.loadtxt(path, unpack=True) self.logger.info(f"min k: {k.min()}, max k: {k.max()}, steps {len(k)}") pk *= self.params['bias']**2 lk = np.log(k) lpk = np.log(pk) self._logpk_func = interpolate.interp1d(lk, lpk, bounds_error=False, fill_value=(0, 0)) def set(self, **param_dict): """ """ for key, value in param_dict.items(): if key == 'non_linear': key = 'non linear' self.logger.debug("Set %s=%s", key, value) found = False if key in self.class_params: self.class_params[key] = value found = True if key in self.params: self.params[key] = value found = True if not found: continue @property def cosmo(self): """ """ if not self._cosmo: self._cosmo = Class() self._cosmo.set(self.class_params) self.logger.info("Initializing Class") self._cosmo.compute() if self.params['fix_sigma8']: sig8 = self._cosmo.sigma8() A_s = self._cosmo.pars['A_s'] self._cosmo.struct_cleanup() # renormalize to fix sig8 self.A_s = A_s * (self.params['sigma8'] * 1. / sig8)**2 self._cosmo.set(A_s=self.A_s) self._cosmo.compute() sig8 = self._cosmo.sigma8() self.params['sigma8'] = sig8 self.params['A_s'] = self._cosmo.pars['A_s'] self.params[ 'sigma8z'] = sig8 * self._cosmo.scale_independent_growth_factor( self.class_params['z_pk']) self.params['f'] = self._cosmo.scale_independent_growth_factor_f( self.class_params['z_pk']) self.logger.info(f" z: {self.class_params['z_pk']}") self.logger.info(f" sigma_8: {self.params['sigma8']}") self.logger.info(f" sigma_8(z): {self.params['sigma8z']}") self.logger.info(f" f(z): {self.params['f']}") self.logger.info( f"f sigma8(z): {self.params['f']*self.params['sigma8z']}") return self._cosmo def class_pk(self, k): """ """ self.logger.info("Computing power spectrum with Class") z = np.array([self.class_params['z_pk']]).astype('d') shape = k.shape k = k.flatten() nk = len(k) k = np.reshape(k, (nk, 1, 1)) pk = self.cosmo.get_pk(k * self.class_params['h'], z, nk, 1, 1).reshape((nk, )) k = k.reshape((nk, )) # set h units pk *= self.class_params['h']**3 pk *= self.params['bias']**2 pk = pk.reshape(shape) return pk def get_pk(self, k): ii = k > 0 out = np.zeros(k.shape, dtype='d') out[ii] = np.exp(self.logpk_func(np.log(k[ii]))) return out @property def logpk_func(self): if self._logpk_func is None: k = np.logspace(self.params['log_kmin'], self.params['log_kmax'], self.params['log_ksteps']) pk = self.class_pk(k) lk = np.log(k) lpk = np.log(pk) print("logk min", lk.min()) self._logpk_func = interpolate.interp1d(lk, lpk, bounds_error=False, fill_value=(0, 0)) return self._logpk_func def comoving_distance(self, z): """ """ return (1 + z) * self.cosmo.angular_distance(z) * self.class_params['h'] def redshift_at_comoving_distance(self, r): """ """ try: z = 10**self.redshift_func(r) - 1 except ValueError: self.logger.error(f"r min {r.min()} max {r.max()}", file=sys.stderr) raise return z @property def redshift_func(self): """ """ if self._redshift_func is None: zz = np.logspace(self.params['logzmin'], self.params['logzmax'], self.params['logzsteps']) - 1 r = np.zeros(len(zz)) for i, z in enumerate(zz): r[i] = self.comoving_distance(z) self._redshift_func = interpolate.interp1d(r, np.log10(1 + zz)) return self._redshift_func
class Peturbations: def __init__(self): self.cosmo = Class() def cosmo_GR(self, zlist): """ Compute cosmology for General Relativity with Planck15 parameters. """ zstr = ','.join(map(str, zlist + zlist[-1] + 2)) lcdmpars = { 'output': 'mPk, tCl, pCl, lCl', 'lensing': 'yes', 'P_k_max_h/Mpc': 20, 'z_pk': zstr, 'background_verbose': 1, #Info 'tau_reio': 0.07, 'omega_cdm': 0.11987, 'A_s': 2.204e-9, 'h': 0.6715918, #computed from 100*theta_s=1.042143 'N_ur': 3.046 - 1., 'N_ncdm': 1., 'm_ncdm': 0.06, 'omega_b': 0.022252, 'n_s': 0.96475, } self.cosmo.set(lcdmpars) self.cosmo.compute() def cosmo_MG(self, zlist, alpha_b, alpha_m, a_trans, r): """ Compute cosmology for Modified gravity with a LCDM background expansion (with Planck15 parameters) and 'hill_scale' parameterization for the property functions. """ zstr = ','.join(map(str, zlist + zlist[-1] + 2)) mgpars = { 'output': 'mPk, tCl, pCl, lCl', 'lensing': 'yes', 'P_k_max_h/Mpc': 20, 'z_pk': zstr, 'background_verbose': 1, #Info 'tau_reio': 0.07, 'omega_cdm': 0.11987, 'A_s': 2.204e-9, 'h': 0.6715918, #computed from 100*theta_s=1.042143 'N_ur': 3.046 - 1., 'N_ncdm': 1., 'm_ncdm': 0.06, 'omega_b': 0.022252, 'n_s': 0.96475, 'Omega_Lambda': 0, 'Omega_fld': 0, 'Omega_smg': -1, 'expansion_model': 'lcdm', 'gravity_model': 'hill_scale', } # Planck Mass Mstarsq = 1. # Property Functions alpha_t = 0. alpha_k = 0.001 mgpars['parameters_smg'] = "{}, {}, {}, {}, {}, {}, {}".format( Mstarsq, alpha_k, alpha_b, alpha_m, alpha_t, a_trans, r) self.cosmo.set(mgpars) self.cosmo.compute() def D(self, z): """ Linear growth function D(z) = ( P(k_ls, z) / P(k_ls, 0) )^(1 / 2) where k_ls is a large-scale mode. """ k = 0.01 #Our choice of large-scale mode mPk = self.cosmo.pk(k, z) mPk_norm = self.cosmo.pk(k, 0) #Normalize at z=0 D = np.sqrt(mPk / mPk_norm) return D def f(self, z): """ Linear growth rate f(z) where f(a) = d log D / d log a where a = 1 / (1 + z) is the scale factor. """ a = 1. / (1. + z) da = 0.01 #*a gp, g, gm = [self.D(1. / ia - 1.) for ia in [a + da, a, a - da]] f = a * (gp - gm) / (2 * g * da) return f def sigma8(self, z): """ sigma8(z) = sigma8*D(z) """ s8 = self.cosmo.sigma8() * self.D(z) return s8 def fsigma8(self, z): """ Growth rate of structure fsigma8(z) = f(z) * sigma8(z) """ fs8 = self.f(z) * self.sigma8(z) return fs8 def fsigma8_GR(self, zlist): """ Get fsigma8 for General Relativity """ self.cosmo_GR(zlist) fs8_GR = np.array([self.fsigma8(z) for z in zlist]) return fs8_GR def fsigma8_MG(self, zlist, alpha_b, alpha_m, a_trans, r): """ Get fsigma8 for Modified Gravity with a LCDM background expansion and hill_scale parameterization for the property functions. """ self.cosmo_MG(zlist, alpha_b, alpha_m, a_trans, r) fs8_MG = np.array([self.fsigma8(z) for z in zlist]) return fs8_MG def fsigma8_MG_fit(self, zlist, alpha_b, a_trans, r): """ Get fsigma8 for Modified Gravity with a LCDM background expansion and hill_scale parameterization for the property functions. """ alpha_m = 0.1 #a_trans = 1./(1.+7.) #r = 4. self.cosmo_MG(zlist, alpha_b, alpha_m, a_trans, r) fs8_MG = np.array([self.fsigma8(z) for z in zlist]) return fs8_MG def sigma8_GR(self, zlist): """ Get fsigma8 for General Relativity """ self.cosmo_GR(zlist) s8_GR = np.array([self.sigma8(z) for z in zlist]) return s8_GR def sigma8_MG(self, zlist, alpha_b, alpha_m, a_trans, r): """ Get sigma8 for Modified Gravity with a LCDM background expansion and hill_scale parameterization for the property functions. """ self.cosmo_MG(zlist, alpha_b, alpha_m, a_trans, r) s8_MG = np.array([self.sigma8(z) for z in zlist]) return s8_MG def Cl_TT_GR(self, zlist, llist): """ Get C_ell^TT for General Relativity """ self.cosmo_GR(zlist) lmax = llist[-1] Cl_TT_GR = self.cosmo.lensed_cl(lmax)['tt'][2:] Cl_TT_GR = (1. / (2. * np.pi)) * (llist * (llist + 1.)) * Cl_TT_GR return Cl_TT_GR def Cl_TT_MG(self, zlist, llist, alpha_b, alpha_m, a_trans, r): """ Get C_ell^TT for Modified Gravity with a LCDM background expansion and hill_scale parameterization for the property functions. """ self.cosmo_MG(zlist, alpha_b, alpha_m, a_trans, r) lmax = llist[-1] Cl_TT_MG = self.cosmo.lensed_cl(lmax)['tt'][2:] Cl_TT_MG = (1. / (2. * np.pi)) * (llist * (llist + 1.)) * Cl_TT_MG return Cl_TT_MG def Cl_kappa_kappa_GR(self, zlist, llist): """ Get C_ell^kappakappa for General Relativity """ self.cosmo_GR(zlist) lmax = llist[-1] Cl_phi_phi_GR = self.cosmo.lensed_cl(lmax)['pp'][2:] Cl_kap_kap_GR = (1. / 4.) * ((llist * (llist + 1.))**2.) * Cl_phi_phi_GR return Cl_kap_kap_GR def Cl_kappa_kappa_MG(self, zlist, llist, alpha_b, alpha_m, a_trans, r): """ Get C_ell^kappakappa for Modified Gravity with a LCDM background expansion and hill_scale parameterization for the property functions. """ self.cosmo_MG(zlist, alpha_b, alpha_m, a_trans, r) lmax = llist[-1] Cl_phi_phi_MG = self.cosmo.lensed_cl(lmax)['pp'][2:] Cl_kap_kap_MG = (1. / 4.) * ((llist * (llist + 1.))**2.) * Cl_phi_phi_MG return Cl_kap_kap_MG
params = { 'output': 'mPk', "h":h, "A_s":1.9735e-9, #Yields sigma8 = 0.8 "n_s":0.96, "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() print "sigma8 is:", cosmo.sigma8() k = np.logspace(-5, 3, base=10, num=4000) #1/Mpc, apparently np.savetxt("k.txt", k/h) #h/Mpc now """for i in range(len(meanz)): for j in range(len(meanz[i])): z = meanz[i,j] 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("pnl_z%d_l%d.txt"%(i,j), Pmm*h**3) #Mpc^3/h^3 np.savetxt("plin_z%d_l%d.txt"%(i,j), Plin*h**3) #Mpc^3/h^3 print "Done with z%d"%i """ for z in [0.577]: Pmm = np.array([cosmo.pk(ki, z) for ki in k]) Plin = np.array([cosmo.pk_lin(ki, z) for ki in k])