}) lcdm.compute() b = lcdm.get_background() x = b["comov. dist"] z = b["xz"] Chi = int.interpd1(z,x) Z_s = 0.8 Z = 0.4 Chi_s = Chi(Z_s) Chi_z = Chi(Z) Omega_m = np.mean(df["omegach2"].values) H0 = np.mean(df["H0"].values) sigma8 = np.mean(df["sigma8*"].values) for x in range(10000): a[i] = random.uniform(0.5,1.6,size=5) fout = open("best_fit_para.txt","w") fout.write("%.3f" % a) fout.write("\n") for i in range(a.): BCP[i] = Omega_m**(a)*sigma8**(b)*H0**(2*c)*((Chi_z*(1+Z_s)/(Chi_s*(1+Z)))-1)**d*(lcdm.scale_independent_growth_factor(Z))**e*(1+Z)**2 fout.write("%.4f" % BCP[i]) fout.write("\n") break
b1 = b1ar[j] b2 = b2ar[j] bG2 = bG2ar[j] css0 = css0ar[j] css2 = css2ar[j] Pshot = Pshotar[j] bGamma3 = bGamma3ar[j] b4 = b4ar[j] fz = cosmo.scale_independent_growth_factor_f(z) da = cosmo.angular_distance(z) # print('DA=',da) hz = cosmo.Hubble(z) / kmsMpc # print('Hz=',hz) DV = (z * (1 + z)**2 * da**2 / cosmo.Hubble(z))**(1. / 3.) # print('DV=',DV) fs8 = cosmo.scale_independent_growth_factor( z) * cosmo.scale_independent_growth_factor_f(z) * cosmo.sigma8() # print('fs8=',fs8) # print('sigma8=',cosmo.sigma8()) print('rd/DV=', rd / DV) print('rdH=', rd * cosmo.Hubble(z)) print('rd/DA=', rd / da) P2noW = np.zeros(k_size) P0noW = np.zeros(k_size) for i in range(k_size): kinloop1 = k[i] * h P2noW[i] = ( norm**2. * cosmo.pk(kinloop1, z)[18] + norm**4. * (cosmo.pk(kinloop1, z)[24]) + norm**1. * b1 * cosmo.pk(kinloop1, z)[19] + norm**3. * b1 * (cosmo.pk(kinloop1, z)[25]) + b1**2. * norm**2. *
def Sijkl(z_arr, windows, cosmo_params=default_cosmo_params, precision=10, tol=1e-3, cosmo_Class=None): # Assert everything as the good type and shape, and find number of redshifts, bins etc zz = np.asarray(z_arr) win = np.asarray(windows) assert zz.ndim == 1, 'z_arr must be a 1-dimensional array' assert win.ndim == 2, 'windows must be a 2-dimensional array' nz = len(zz) nbins = win.shape[0] assert win.shape[1] == nz, 'windows must have shape (nbins,nz)' assert zz.min() > 0, 'z_arr must have values > 0' # If the cosmology is not provided (in the same form as CLASS), run CLASS if cosmo_Class is None: cosmo = Class() dico_for_CLASS = cosmo_params dico_for_CLASS['output'] = 'mPk' cosmo.set(dico_for_CLASS) cosmo.compute() else: cosmo = cosmo_Class h = cosmo.h() #for conversions Mpc/h <-> Mpc # Define arrays of r(z), k, P(k)... zofr = cosmo.z_of_r(zz) comov_dist = zofr[0] #Comoving distance r(z) in Mpc dcomov_dist = 1 / zofr[1] #Derivative dr/dz in Mpc dV = comov_dist**2 * dcomov_dist #Comoving volume per solid angle in Mpc^3/sr growth = np.zeros(nz) #Growth factor for iz in range(nz): growth[iz] = cosmo.scale_independent_growth_factor(zz[iz]) #Index pairs of bins npairs = (nbins * (nbins + 1)) // 2 pairs = np.zeros((2, npairs), dtype=int) count = 0 for ibin in range(nbins): for jbin in range(ibin, nbins): pairs[0, count] = ibin pairs[1, count] = jbin count += 1 # Compute normalisations Inorm = np.zeros(npairs) Inorm2D = np.zeros((nbins, nbins)) for ipair in range(npairs): ibin = pairs[0, ipair] jbin = pairs[1, ipair] integrand = dV * windows[ibin, :] * windows[jbin, :] integral = integrate.simps(integrand, zz) Inorm[ipair] = integral Inorm2D[ibin, jbin] = integral Inorm2D[jbin, ibin] = integral #Flag pairs with too small overlap as unreliable #Note: this will also speed up later computations #Default tolerance : tol=1e-3 flag = np.zeros(npairs, dtype=int) for ipair in range(npairs): ibin = pairs[0, ipair] jbin = pairs[1, ipair] ratio = abs(Inorm2D[ibin, jbin]) / np.sqrt( abs(Inorm2D[ibin, ibin] * Inorm2D[jbin, jbin])) if ratio < tol: flag[ipair] = 1 # Compute U(i,j;kk) keq = 0.02 / h #Equality matter radiation in 1/Mpc (more or less) klogwidth = 10 #Factor of width of the integration range. 10 seems ok kmin = min(keq, 1. / comov_dist.max()) / klogwidth kmax = max(keq, 1. / comov_dist.min()) * klogwidth nk = 2**precision #10 seems to be enough. Increase to test precision, reduce to speed up. #kk = np.linspace(kmin,kmax,num=nk) #linear grid on k logkmin = np.log(kmin) logkmax = np.log(kmax) logk = np.linspace(logkmin, logkmax, num=nk) kk = np.exp(logk) #logarithmic grid on k Pk = np.zeros(nk) for ik in range(nk): Pk[ik] = cosmo.pk(kk[ik], 0.) #In Mpc^3 Uarr = np.zeros((npairs, nk)) for ipair in range(npairs): if flag[ipair] == 0: ibin = pairs[0, ipair] jbin = pairs[1, ipair] for ik in range(nk): kr = kk[ik] * comov_dist integrand = dV * windows[ibin, :] * windows[ jbin, :] * growth * np.sin(kr) / kr Uarr[ipair, ik] = integrate.simps(integrand, zz) # Compute Sijkl finally Cl_zero = np.zeros((nbins, nbins, nbins, nbins)) #For ipair<=jpair for ipair in range(npairs): if flag[ipair] == 0: U1 = Uarr[ipair, :] / Inorm[ipair] ibin = pairs[0, ipair] jbin = pairs[1, ipair] for jpair in range(ipair, npairs): if flag[jpair] == 0: U2 = Uarr[jpair, :] / Inorm[jpair] kbin = pairs[0, jpair] lbin = pairs[1, jpair] integrand = kk**2 * Pk * U1 * U2 #integral = 2/(i * integrate.simps(integrand,kk) #linear integration integral = 2 / pi * integrate.simps(integrand * kk, logk) #log integration #Run through all valid symmetries to fill the 4D array #Symmetries: i<->j, k<->l, (i,j)<->(k,l) Cl_zero[ibin, jbin, kbin, lbin] = integral Cl_zero[ibin, jbin, lbin, kbin] = integral Cl_zero[jbin, ibin, kbin, lbin] = integral Cl_zero[jbin, ibin, lbin, kbin] = integral Cl_zero[kbin, lbin, ibin, jbin] = integral Cl_zero[kbin, lbin, jbin, ibin] = integral Cl_zero[lbin, kbin, ibin, jbin] = integral Cl_zero[lbin, kbin, jbin, ibin] = integral Sijkl = Cl_zero / (4 * pi) return Sijkl # End of PySSC.py
#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 if (not z_lin == 0): print("Rescaling the linear theory power spectrum") Pvec *= (D_0 / D_lin)**2 #Get background quantities from CLASS (reverse the order of the arrays) background = cosmo.get_background() bg_t = background['proper time [Gyr]'][::-1]
def Sij_alt(z_arr, windows, cosmo_params=default_cosmo_params, cosmo_Class=None): # Assert everything as the good type and shape, and find number of redshifts, bins etc zz = np.asarray(z_arr) win = np.asarray(windows) assert zz.ndim == 1, 'z_arr must be a 1-dimensional array' assert win.ndim == 2, 'windows must be a 2-dimensional array' nz = len(zz) nbins = win.shape[0] assert win.shape[1] == nz, 'windows must have shape (nbins,nz)' assert zz.min() > 0, 'z_arr must have values > 0' # If the cosmology is not provided (in the same form as CLASS), run CLASS if cosmo_Class is None: cosmo = Class() dico_for_CLASS = cosmo_params dico_for_CLASS['output'] = 'mPk' cosmo.set(dico_for_CLASS) cosmo.compute() else: cosmo = cosmo_Class h = cosmo.h() #for conversions Mpc/h <-> Mpc # Define arrays of r(z), k, P(k)... zofr = cosmo.z_of_r(zz) comov_dist = zofr[0] #Comoving distance r(z) in Mpc dcomov_dist = 1 / zofr[1] #Derivative dr/dz in Mpc dV = comov_dist**2 * dcomov_dist #Comoving volume per solid angle in Mpc^3/sr growth = np.zeros(nz) #Growth factor for iz in range(nz): growth[iz] = cosmo.scale_independent_growth_factor(zz[iz]) keq = 0.02 / h #Equality matter radiation in 1/Mpc (more or less) klogwidth = 10 #Factor of width of the integration range. #10 seems ok ; going higher needs to increase nk_fft to reach convergence (fine cancellation issue noted in Lacasa & Grain) kmin = min(keq, 1. / comov_dist.max()) / klogwidth kmax = max(keq, 1. / comov_dist.min()) * klogwidth nk_fft = 2**11 #seems to be enough. Increase to test precision, reduce to speed up. k_4fft = np.linspace(kmin, kmax, nk_fft) #linear grid on k, as we need to use an FFT Deltak = kmax - kmin Dk = Deltak / nk_fft Pk_4fft = np.zeros(nk_fft) for ik in range(nk_fft): Pk_4fft[ik] = cosmo.pk(k_4fft[ik], 0.) #In Mpc^3 dr_fft = np.linspace(0, nk_fft // 2, nk_fft // 2 + 1) * 2 * pi / Deltak # Compute necessary FFTs and make interpolation functions fft0 = np.fft.rfft(Pk_4fft) * Dk dct0 = fft0.real dst0 = -fft0.imag Pk_dct = interp1d(dr_fft, dct0, kind='cubic') # Compute sigma^2(z1,z2) sigma2_nog = np.zeros((nz, nz)) #First with P(k,z=0) and z1<=z2 for iz in range(nz): r1 = comov_dist[iz] for jz in range(iz, nz): r2 = comov_dist[jz] rsum = r1 + r2 rdiff = abs(r1 - r2) Icp0 = Pk_dct(rsum) Icm0 = Pk_dct(rdiff) sigma2_nog[iz, jz] = (Icm0 - Icp0) / (4 * pi**2 * r1 * r2) #Now fill by symmetry and put back growth functions sigma2 = np.zeros((nz, nz)) for iz in range(nz): growth1 = growth[iz] for jz in range(nz): growth2 = growth[jz] sigma2[iz, jz] = sigma2_nog[min(iz, jz), max(iz, jz)] * growth1 * growth2 # Compute normalisations Inorm = np.zeros(nbins) for i1 in range(nbins): integrand = dV * windows[i1, :]**2 Inorm[i1] = integrate.simps(integrand, zz) # Compute Sij finally prefactor = sigma2 * (dV * dV[:, None]) Sij = np.zeros((nbins, nbins)) #For i<=j for i1 in range(nbins): for i2 in range(i1, nbins): integrand = prefactor * (windows[i1, :]**2 * windows[i2, :, None]**2) Sij[i1, i2] = integrate.simps(integrate.simps(integrand, zz), zz) / (Inorm[i1] * Inorm[i2]) #Fill by symmetry for i1 in range(nbins): for i2 in range(nbins): Sij[i1, i2] = Sij[min(i1, i2), max(i1, i2)] return Sij
def turboSij(zstakes=default_zstakes, cosmo_params=default_cosmo_params, cosmo_Class=None): # If the cosmology is not provided (in the same form as CLASS), run CLASS if cosmo_Class is None: cosmo = Class() dico_for_CLASS = cosmo_params dico_for_CLASS['output'] = 'mPk' cosmo.set(dico_for_CLASS) cosmo.compute() else: cosmo = cosmo_Class h = cosmo.h() #for conversions Mpc/h <-> Mpc # Define arrays of z, r(z), k, P(k)... nzbins = len(zstakes) - 1 nz_perbin = 10 z_arr = np.zeros((nz_perbin, nzbins)) comov_dist = np.zeros((nz_perbin, nzbins)) for j in range(nzbins): z_arr[:, j] = np.linspace(zstakes[j], zstakes[j + 1], nz_perbin) comov_dist[:, j] = (cosmo.z_of_r(z_arr[:, j]))[0] #In Mpc keq = 0.02 / h #Equality matter radiation in 1/Mpc (more or less) klogwidth = 10 #Factor of width of the integration range. 10 seems ok ; going higher needs to increase nk_fft to reach convergence (fine cancellation issue noted in Lacasa & Grain) kmin = min(keq, 1. / comov_dist.max()) / klogwidth kmax = max(keq, 1. / comov_dist.min()) * klogwidth nk_fft = 2**11 #seems to be enough. Increase to test precision, reduce to speed up. k_4fft = np.linspace(kmin, kmax, nk_fft) #linear grid on k, as we need to use an FFT Deltak = kmax - kmin Dk = Deltak / nk_fft Pk_4fft = np.zeros(nk_fft) for ik in range(nk_fft): Pk_4fft[ik] = cosmo.pk(k_4fft[ik], 0.) #In Mpc^3 dr_fft = np.linspace(0, nk_fft // 2, nk_fft // 2 + 1) * 2 * pi / Deltak # Compute necessary FFTs and make interpolation functions fft2 = np.fft.rfft(Pk_4fft / k_4fft**2) * Dk dct2 = fft2.real dst2 = -fft2.imag km2Pk_dct = interp1d(dr_fft, dct2, kind='cubic') fft3 = np.fft.rfft(Pk_4fft / k_4fft**3) * Dk dct3 = fft3.real dst3 = -fft3.imag km3Pk_dst = interp1d(dr_fft, dst3, kind='cubic') fft4 = np.fft.rfft(Pk_4fft / k_4fft**4) * Dk dct4 = fft4.real dst4 = -fft4.imag km4Pk_dct = interp1d(dr_fft, dct4, kind='cubic') # Compute Sij finally Sij = np.zeros((nzbins, nzbins)) for j1 in range(nzbins): rmin1 = (comov_dist[:, j1]).min() rmax1 = (comov_dist[:, j1]).max() zmean1 = ((z_arr[:, j1]).min() + (z_arr[:, j1]).max()) / 2 growth1 = cosmo.scale_independent_growth_factor(zmean1) pref1 = 3. * growth1 / (rmax1**3 - rmin1**3) for j2 in range(nzbins): rmin2 = (comov_dist[:, j2]).min() rmax2 = (comov_dist[:, j2]).max() zmean2 = ((z_arr[:, j2]).min() + (z_arr[:, j2]).max()) / 2 growth2 = cosmo.scale_independent_growth_factor(zmean2) pref2 = 3. * growth2 / (rmax2**3 - rmin2**3) #p1p2: rmax1 & rmax2 rsum = rmax1 + rmax2 rdiff = abs(rmax1 - rmax2) rprod = rmax1 * rmax2 Icp2 = km2Pk_dct(rsum) Icm2 = km2Pk_dct(rdiff) Isp3 = km3Pk_dst(rsum) Ism3 = km3Pk_dst(rdiff) Icp4 = km4Pk_dct(rsum) Icm4 = km4Pk_dct(rdiff) Fp1p2 = -Icp4 + Icm4 - rsum * Isp3 + rdiff * Ism3 + rprod * (Icp2 + Icm2) #p1m2: rmax1 & rmin2 rsum = rmax1 + rmin2 rdiff = abs(rmax1 - rmin2) rprod = rmax1 * rmin2 Icp2 = km2Pk_dct(rsum) Icm2 = km2Pk_dct(rdiff) Isp3 = km3Pk_dst(rsum) Ism3 = km3Pk_dst(rdiff) Icp4 = km4Pk_dct(rsum) Icm4 = km4Pk_dct(rdiff) Fp1m2 = -Icp4 + Icm4 - rsum * Isp3 + rdiff * Ism3 + rprod * (Icp2 + Icm2) #m1p2: rmin1 & rmax2 rsum = rmin1 + rmax2 rdiff = abs(rmin1 - rmax2) rprod = rmin1 * rmax2 Icp2 = km2Pk_dct(rsum) Icm2 = km2Pk_dct(rdiff) Isp3 = km3Pk_dst(rsum) Ism3 = km3Pk_dst(rdiff) Icp4 = km4Pk_dct(rsum) Icm4 = km4Pk_dct(rdiff) Fm1p2 = -Icp4 + Icm4 - rsum * Isp3 + rdiff * Ism3 + rprod * (Icp2 + Icm2) #m1m2: rmin1 & rmin2 rsum = rmin1 + rmin2 rdiff = abs(rmin1 - rmin2) rprod = rmin1 * rmin2 Icp2 = km2Pk_dct(rsum) Icm2 = km2Pk_dct(rdiff) Isp3 = km3Pk_dst(rsum) Ism3 = km3Pk_dst(rdiff) Icp4 = km4Pk_dct(rsum) Icm4 = km4Pk_dct(rdiff) Fm1m2 = -Icp4 + Icm4 - rsum * Isp3 + rdiff * Ism3 + rprod * (Icp2 + Icm2) #now group everything Fsum = Fp1p2 - Fp1m2 - Fm1p2 + Fm1m2 Sij[j1, j2] = pref1 * pref2 * Fsum / (4 * pi**2) return Sij
def Sij(z_arr, windows, cosmo_params=default_cosmo_params, precision=10, cosmo_Class=None): # Assert everything as the good type and shape, and find number of redshifts, bins etc zz = np.asarray(z_arr) win = np.asarray(windows) assert zz.ndim == 1, 'z_arr must be a 1-dimensional array' assert win.ndim == 2, 'windows must be a 2-dimensional array' nz = len(zz) nbins = win.shape[0] assert win.shape[1] == nz, 'windows must have shape (nbins,nz)' assert zz.min() > 0, 'z_arr must have values > 0' # If the cosmology is not provided (in the same form as CLASS), run CLASS if cosmo_Class is None: cosmo = Class() dico_for_CLASS = cosmo_params dico_for_CLASS['output'] = 'mPk' cosmo.set(dico_for_CLASS) cosmo.compute() else: cosmo = cosmo_Class h = cosmo.h() #for conversions Mpc/h <-> Mpc # Define arrays of r(z), k, P(k)... zofr = cosmo.z_of_r(zz) comov_dist = zofr[0] #Comoving distance r(z) in Mpc dcomov_dist = 1 / zofr[1] #Derivative dr/dz in Mpc dV = comov_dist**2 * dcomov_dist #Comoving volume per solid angle in Mpc^3/sr growth = np.zeros(nz) #Growth factor for iz in range(nz): growth[iz] = cosmo.scale_independent_growth_factor(zz[iz]) # Compute normalisations Inorm = np.zeros(nbins) for i1 in range(nbins): integrand = dV * windows[i1, :]**2 Inorm[i1] = integrate.simps(integrand, zz) # Compute U(i,k) keq = 0.02 / h #Equality matter radiation in 1/Mpc (more or less) klogwidth = 10 #Factor of width of the integration range. 10 seems ok kmin = min(keq, 1. / comov_dist.max()) / klogwidth kmax = max(keq, 1. / comov_dist.min()) * klogwidth nk = 2**precision #10 seems to be enough. Increase to test precision, reduce to speed up. #kk = np.linspace(kmin,kmax,num=nk) #linear grid on k logkmin = np.log(kmin) logkmax = np.log(kmax) logk = np.linspace(logkmin, logkmax, num=nk) kk = np.exp(logk) #logarithmic grid on k Pk = np.zeros(nk) for ik in range(nk): Pk[ik] = cosmo.pk(kk[ik], 0.) #In Mpc^3 Uarr = np.zeros((nbins, nk)) for ibin in range(nbins): for ik in range(nk): kr = kk[ik] * comov_dist integrand = dV * windows[ibin, :]**2 * growth * np.sin(kr) / kr Uarr[ibin, ik] = integrate.simps(integrand, zz) # Compute Sij finally Cl_zero = np.zeros((nbins, nbins)) #For i<=j for ibin in range(nbins): U1 = Uarr[ibin, :] / Inorm[ibin] for jbin in range(ibin, nbins): U2 = Uarr[jbin, :] / Inorm[jbin] integrand = kk**2 * Pk * U1 * U2 #Cl_zero[ibin,jbin] = 2/pi * integrate.simps(integrand,kk) #linear integration Cl_zero[ibin, jbin] = 2 / pi * integrate.simps( integrand * kk, logk) #log integration #Fill by symmetry for ibin in range(nbins): for jbin in range(nbins): Cl_zero[ibin, jbin] = Cl_zero[min(ibin, jbin), max(ibin, jbin)] Sij = Cl_zero / (4 * pi) return Sij
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()
'omega_b': 0.023, 'Omega_cdm': 0.1093, 'Omega_Lambda': 0.73 } # Create an instance of the CLASS wrapper cosmo = Class() # Set the parameters to the cosmological code cosmo.set(params) cosmo.compute() #### Define the linear growth factor and growth rate (growth factor f in class) h = cosmo.h() fz = cosmo.scale_independent_growth_factor_f(z) Dz = cosmo.scale_independent_growth_factor(z) karray = np.logspace(np.log10(kmin), np.log10(kmax), kbins) #~ Plin = cosmo.get_pk_cb_array(karray*h, np.array([z]), len(karray), znumber, 0) # if we want Pcb Plin = np.zeros(len(karray)) for i, k in enumerate(karray): Plin[i] = (cosmo.pk(k, z)) # function .pk(k,z) ######################################################################## ######################################################################## ### Compute the non linear power spectrum ######################################################################## ######################################################################## # A summary of your configuration is printed in the terminal P1 = ps_calc(coord[0], kcase, Mnu, mbin, rsd, bias_model, karray, z, fog, Plin, fz, Dz)
def constraints(params, zs): cosmo = Class() cosmo.set(params) cosmo.compute() h = cosmo.Hubble(0) * 299792.458 om0 = cosmo.Omega0_m() #print(cosmo.pars) zarr2 = cosmo.get_background().get('z') hz = cosmo.get_background().get('H [1/Mpc]') hf = interpolate.InterpolatedUnivariateSpline(zarr2[-1:0:-1], hz[-1:0:-1]) chiz = cosmo.get_background().get('comov. dist.') chif = interpolate.InterpolatedUnivariateSpline(zarr2[-1:0:-1], chiz[-1:0:-1]) pkz = np.zeros((nk, nz)) pklz2 = np.zeros((nk, nz)) dprime = np.zeros((nk, 1)) zarr = np.linspace(0, zmax, nz) karr = np.logspace(-3, np.log10(20), nk) rcollarr = np.zeros(nz) kcarr = np.zeros(nz) delz = 0.01 for i in np.arange(nz): Dz = (cosmo.scale_independent_growth_factor(zarr[i]) / cosmo.scale_independent_growth_factor(0)) sigz = lambda x: Dz * cosmo.sigma(x, zarr[i]) - 1.192182033080519 if (sigz(1e-5) > 0) & (sigz(10) < 0): rcollarr[i] = optimize.brentq(sigz, 1e-5, 10) else: rcollarr[i] = 0 for j in np.arange(nk): pkz[j, i] = cosmo.pk(karr[j], zarr[i]) for i in np.arange(nk): pklz0 = np.log(cosmo.pk(karr[i], zs - delz) / cosmo.pk(karr[i], 0)) pklz1 = np.log(cosmo.pk(karr[i], zs + delz) / cosmo.pk(karr[i], 0)) pklz2[i] = cosmo.pk(karr[i], 0) dprime[i] = -hf(zs) * np.sqrt( cosmo.pk(karr[i], zs) / pklz2[i, 0]) * (pklz1 - pklz0) / 4 / delz #divided by 2 for step size, another for defining D' w0 = params.get('w0_fld') wa = params.get('wa_fld') mt = 5 * np.log10(cosmo.luminosity_distance(zs)) #mt = 5*np.log10(fanal.dlatz(zs, om0, og0, w0, wa)) Rc = (2 * 4.302e-9 * Mc / h**2 / om0)**(1 / 3) mask = (0 < rcollarr) & (rcollarr < Rc) kcarr[mask] = 2 * np.pi / rcollarr[mask] mask = (rcollarr >= Rc) kcarr[mask] = 2 * np.pi / Rc #plt.semilogy(zarr, kcarr) pksmooth = pdf.pkint(karr, zarr, pkz, kcarr) par2 = {'w0': w0, 'wa': wa, 'Omega_m': om0} print(par2) #kmin = conv.kmin(zs, chif, hf)*(-3./2.*hf(0)**2*om0) kvar = conv.kvar(zs, pksmooth, chif, hf) * (3. / 2. * hf(0)**2 * om0)**2 #sigln = np.log(1+kvar/np.abs(kmin)**2) #L = pdf.convpdf(kmin, sigln, sig, mfid-mt) #sigln = np.sqrt(sig**2+(5/np.log(10))**2*kvar) #L = pdf.gausspdf(sig, mfid-mt) #lnL = mt/sig vvar = np.trapz(pklz2[:, 0] * dprime[:, 0]**2, karr) / 6 / np.pi**2 * (1 - (1 + zs) / hf(zs) / chif(zs))**2 #var_tot = norm*kvar+sig**2 lnL = -mt**2 / 2 print('Sigmasq = {}, {}, Likelihood = {}'.format(kvar, vvar, lnL)) cosmo.struct_cleanup() cosmo.empty() return [mt, kvar, vvar] #[mt, var_tot]
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