def comoving_dimensions_from_survey(cosmo, angular_extent, freq_range=None, z_range=None, line_freq=1420.405752): """ Return the comoving dimensions and central redshift of a survey volume, given its angular extent and redshift/frequency range. Parameters: cosmo (ccl.Cosmology object): CCL object that defines the cosmology to use. angular_extent (tuple): Angular extent of the survey in the x and y directions on the sky, given in degrees. For example, `(10, 30)` denotes a 10 deg x 30 deg survey area. freq_range (tuple, optional): The frequency range of the survey, given in MHz. z_range (tuple, optional): The redshift range of the survey. line_freq (float, optional): Frequency of the emission line used as redshift reference, in MHz. Returns: zc (float): Redshift of the centre of the comoving box. dimensions (tuple): Tuple of comoving dimensions of the survey volume, (Lx, Ly, Lz), in Mpc. """ # Check inputs if (freq_range is not None and z_range is not None) \ or (freq_range is None and z_range is None): raise ValueError("Must specify either freq_range of z_range.") assert len(angular_extent) == 2, "angular_extent must be tuple of length 2" # Convert frequency range to z range if needed if freq_range is not None: assert len(freq_range) == 2, "freq_range must be tuple of length 2" z_range = (line_freq/freq_range[0] - 1., line_freq/freq_range[1] - 1.) assert len(z_range) == 2, "z_range must be tuple of length 2" # Sort z_range zmin, zmax = sorted(z_range) # Convert z_range to comoving r range rmin = ccl.comoving_radial_distance(cosmo, 1./(1.+zmin)) rmax = ccl.comoving_radial_distance(cosmo, 1./(1.+zmax)) Lz = rmax - rmin # Get comoving centroid of volume _z = np.linspace(zmin, zmax, 100) _r = ccl.comoving_radial_distance(cosmo, 1./(1.+_z)) rc = 0.5 * (rmax + rmin) zc = interp1d(_r, _z, kind='linear')(rc) # Get transverse extent of box, evaluated at centroid redshift r_trans = ccl.comoving_angular_distance(cosmo, 1./(1.+zc)) Lx = angular_extent[0] * np.pi/180. * r_trans Ly = angular_extent[1] * np.pi/180. * r_trans return zc, (Lx, Ly, Lz)
def number_density_to_area_density(cosmo, ngal, zmin, zmax, degrees=False): """ Convert comoving galaxy number density (in Mpc^-3) to an area density (per unit solid angle). Parameters: cosmo (ccl.Cosmology): CCL Cosmology object. ngal (float): Comoving galaxynumber density, in Mpc^-3. zmin, zmax (float): Minimum and maximum redshift of the redshift bin. degrees (bool): Whether to return the area density in degrees^2 or steradians. Returns: Ngal (float): Galaxy number density in this redshift bin, per unit solid angle. """ # Calculate comoving distances rmin = ccl.comoving_radial_distance(cosmo, a=1.0 / (1.0 + zmin)) rmax = ccl.comoving_radial_distance(cosmo, a=1.0 / (1.0 + zmax)) # Calculate volume of shell, in Mpc^3 vol = (4.0 / 3.0) * np.pi * (rmax**3.0 - rmin**3.0) # Calculate total no. of galaxies in shell and divide by area of sky Ngal = (ngal * vol) / (4.0 * np.pi) # No. gals. per steradian if degrees: return Ngal * (np.pi / 180.0)**2.0 # No. gals per deg^2 else: return Ngal # No. gals per ster.
def test_cosmology_lcdm(): """Check that the default vanilla cosmology behaves as expected""" c1 = ccl.Cosmology(Omega_c=0.25, Omega_b=0.05, h=0.67, n_s=0.96, sigma8=0.81) c2 = ccl.CosmologyVanillaLCDM() assert_(ccl.comoving_radial_distance(c1, 0.5) == ccl.comoving_radial_distance(c2, 0.5))
def LSSTSpecParams(C): biasfunc = lambda z: 0.95 / ccl.growth_factor(C, 1 / (1 + z)) ndens = 49 ## per /arcmin^2, LSST SRD, page 47 dndz = lambda z: z**2 * np.exp(-(z / 0.28)**0.94) ## LSST SRD, page 47 arcminfsky = 1 / (4 * np.pi / (np.pi / (180 * 60))**2) ## volume between z=3 zmax = 3 V = 4 * np.pi**3 / 3 * ccl.comoving_radial_distance(C, 1 / (1 + zmax))**3 dVdz = lambda z: 3e3 / C['h'] * 1 / ccl.h_over_h0(C, 1 / ( 1 + z)) * 4 * np.pi * ccl.comoving_radial_distance(C, 1 / (1 + z))**2 norm = ndens / (quad(dndz, 0, zmax)[0] * arcminfsky) nbarofz = lambda z: norm * dndz(z) / dVdz(z) return biasfunc, nbarofz, 0, 3, None
def test_cosmology_repr(): """Check that we can make a Cosmology object from its repr.""" import pyccl # noqa: F401 cosmo = ccl.Cosmology( Omega_c=0.25, Omega_b=0.05, h=0.7, A_s=2.1e-9, n_s=0.96, m_nu=[0.02, 0.1, 0.05], m_nu_type='list', z_mg=[0.0, 1.0], df_mg=[0.01, 0.0]) cosmo2 = eval(str(cosmo)) assert_( ccl.comoving_radial_distance(cosmo, 0.5) == ccl.comoving_radial_distance(cosmo2, 0.5)) cosmo3 = eval(repr(cosmo)) assert_( ccl.comoving_radial_distance(cosmo, 0.5) == ccl.comoving_radial_distance(cosmo3, 0.5)) # same test with arrays to be sure cosmo = ccl.Cosmology( Omega_c=0.25, Omega_b=0.05, h=0.7, A_s=2.1e-9, n_s=0.96, m_nu=np.array([0.02, 0.1, 0.05]), m_nu_type='list', z_mg=np.array([0.0, 1.0]), df_mg=np.array([0.01, 0.0])) cosmo2 = eval(str(cosmo)) assert_( ccl.comoving_radial_distance(cosmo, 0.5) == ccl.comoving_radial_distance(cosmo2, 0.5)) cosmo3 = eval(repr(cosmo)) assert_( ccl.comoving_radial_distance(cosmo, 0.5) == ccl.comoving_radial_distance(cosmo3, 0.5))
def check_background_nu(cosmo): """ Check that background functions can be run and that the growth functions exit gracefully in functions with massive neutrinos (not implemented yet). """ # Types of scale factor input (scalar, list, array) a_scl = 0.5 a_lst = [0.2, 0.4, 0.6, 0.8, 1.] a_arr = np.linspace(0.2, 1., 5) # growth_factor assert_raises(CCLError, ccl.growth_factor, cosmo, a_scl) assert_raises(CCLError, ccl.growth_factor, cosmo, a_lst) assert_raises(CCLError, ccl.growth_factor, cosmo, a_arr) # growth_factor_unnorm assert_raises(CCLError, ccl.growth_factor_unnorm, cosmo, a_scl) assert_raises(CCLError, ccl.growth_factor_unnorm, cosmo, a_lst) assert_raises(CCLError, ccl.growth_factor_unnorm, cosmo, a_arr) # growth_rate assert_raises(CCLError, ccl.growth_rate, cosmo, a_scl) assert_raises(CCLError, ccl.growth_rate, cosmo, a_lst) assert_raises(CCLError, ccl.growth_rate, cosmo, a_arr) # comoving_radial_distance assert_(all_finite(ccl.comoving_radial_distance(cosmo, a_scl))) assert_(all_finite(ccl.comoving_radial_distance(cosmo, a_lst))) assert_(all_finite(ccl.comoving_radial_distance(cosmo, a_arr))) # h_over_h0 assert_(all_finite(ccl.h_over_h0(cosmo, a_scl))) assert_(all_finite(ccl.h_over_h0(cosmo, a_lst))) assert_(all_finite(ccl.h_over_h0(cosmo, a_arr))) # luminosity_distance assert_(all_finite(ccl.luminosity_distance(cosmo, a_scl))) assert_(all_finite(ccl.luminosity_distance(cosmo, a_lst))) assert_(all_finite(ccl.luminosity_distance(cosmo, a_arr))) # scale_factor_of_chi assert_(all_finite(ccl.scale_factor_of_chi(cosmo, a_scl))) assert_(all_finite(ccl.scale_factor_of_chi(cosmo, a_lst))) assert_(all_finite(ccl.scale_factor_of_chi(cosmo, a_arr))) # omega_m_a assert_(all_finite(ccl.omega_x(cosmo, a_scl, 'matter'))) assert_(all_finite(ccl.omega_x(cosmo, a_lst, 'matter'))) assert_(all_finite(ccl.omega_x(cosmo, a_arr, 'matter')))
def check_background(cosmo): """ Check that background and growth functions can be run. """ # Types of scale factor input (scalar, list, array) a_scl = 0.5 a_lst = [0.2, 0.4, 0.6, 0.8, 1.] a_arr = np.linspace(0.2, 1., 5) # growth_factor assert_( all_finite(ccl.growth_factor(cosmo, a_scl)) ) assert_( all_finite(ccl.growth_factor(cosmo, a_lst)) ) assert_( all_finite(ccl.growth_factor(cosmo, a_arr)) ) # growth_factor_unnorm assert_( all_finite(ccl.growth_factor_unnorm(cosmo, a_scl)) ) assert_( all_finite(ccl.growth_factor_unnorm(cosmo, a_lst)) ) assert_( all_finite(ccl.growth_factor_unnorm(cosmo, a_arr)) ) # growth_rate assert_( all_finite(ccl.growth_rate(cosmo, a_scl)) ) assert_( all_finite(ccl.growth_rate(cosmo, a_lst)) ) assert_( all_finite(ccl.growth_rate(cosmo, a_arr)) ) # comoving_radial_distance assert_( all_finite(ccl.comoving_radial_distance(cosmo, a_scl)) ) assert_( all_finite(ccl.comoving_radial_distance(cosmo, a_lst)) ) assert_( all_finite(ccl.comoving_radial_distance(cosmo, a_arr)) ) # h_over_h0 assert_( all_finite(ccl.h_over_h0(cosmo, a_scl)) ) assert_( all_finite(ccl.h_over_h0(cosmo, a_lst)) ) assert_( all_finite(ccl.h_over_h0(cosmo, a_arr)) ) # luminosity_distance assert_( all_finite(ccl.luminosity_distance(cosmo, a_scl)) ) assert_( all_finite(ccl.luminosity_distance(cosmo, a_lst)) ) assert_( all_finite(ccl.luminosity_distance(cosmo, a_arr)) ) # scale_factor_of_chi assert_( all_finite(ccl.scale_factor_of_chi(cosmo, a_scl)) ) assert_( all_finite(ccl.scale_factor_of_chi(cosmo, a_lst)) ) assert_( all_finite(ccl.scale_factor_of_chi(cosmo, a_arr)) ) # omega_m_a assert_( all_finite(ccl.omega_x(cosmo, a_scl, 'matter')) ) assert_( all_finite(ccl.omega_x(cosmo, a_lst, 'matter')) ) assert_( all_finite(ccl.omega_x(cosmo, a_arr, 'matter')) )
def fisher(zbins, params_in, dparams, expt): """ Calculate Fisher matrices for a series of redshift bins. """ # Define fiducial cosmology cosmo0, params0 = build_ccl_cosmo(params_in) # Redshift bin centroid zc = 0.5 * (zbins[1:] + zbins[:-1]) # Get signal and noise covariance for each redshift bin cs = [signal_covariance(_zc, cosmo0, params0) for _zc in zc] cn = [noise_covariance(_zc, params0) for _zc in zc] # Calculate derivatives of signal covariance w.r.t. cosmological parameters pnames, derivs = signal_derivs(zc, params_in, dparams) # Calculate volume factor for each redshift bin fsky = expt['survey_area'] / (4. * np.pi * (180. / np.pi)**2.) # SAREA in deg^2 rbins = ccl.comoving_radial_distance(cosmo0, 1. / (1. + zbins)) Veff = fsky * (4. / 3.) * np.pi * (rbins[1:]**3. - rbins[:-1]**3.) print "Volumes (Gpc^3):", Veff / 1e9 # Calculate Fisher matrix for each redshift bin Fz = [ Veff[i] * integrate_fisher(zc[i], cs[i], cn[i], derivs[:, i]) for i in range(zc.size) ] return pnames, np.array(Fz)
def test_tracer_nz_support(): z_max = 1.0 a = np.linspace(1 / (1 + z_max), 1.0, 100) background_def = { "a": a, "chi": ccl.comoving_radial_distance(COSMO, a), "h_over_h0": ccl.h_over_h0(COSMO, a) } calculator_cosmo = ccl.CosmologyCalculator(Omega_c=0.27, Omega_b=0.045, h=0.67, sigma8=0.8, n_s=0.96, background=background_def) z = np.linspace(0., 2., 2000) n = dndz(z) with pytest.raises(ValueError): _ = ccl.WeakLensingTracer(calculator_cosmo, (z, n)) with pytest.raises(ValueError): _ = ccl.NumberCountsTracer(calculator_cosmo, has_rsd=False, dndz=(z, n), bias=(z, np.ones_like(z))) with pytest.raises(ValueError): _ = ccl.CMBLensingTracer(calculator_cosmo, z_source=2.0)
def compare_distances_mnu_hiz(z, chi_bench, dm_bench, Omega_v, w0, wa, Neff_mnu, mnu): """ Compare distances calculated by pyccl with the distances in the benchmark file. """ # Set Omega_K in a consistent way Omega_k = 1.0 - Omega_c - Omega_b - Omega_v cosmo = ccl.Cosmology(Omega_c=Omega_c, Omega_b=Omega_b, Neff=Neff, h=h, A_s=A_s, n_s=n_s, Omega_k=Omega_k, w0=w0, wa=wa, m_nu=mnu) # Calculate distance using pyccl a = 1. / (1. + z) chi = ccl.comoving_radial_distance(cosmo, a) # Compare to benchmark data assert_allclose(chi, chi_bench, atol=1e-12, rtol=DISTANCES_TOLERANCE_MNU) # compare distance moudli where a!=1 a_not_one = (a != 1).nonzero() dm = ccl.distance_modulus(cosmo, a[a_not_one]) assert_allclose(dm, dm_bench[a_not_one], atol=1e-3, rtol=DISTANCES_TOLERANCE_MNU)
def compare_distances(z, chi_bench, dm_bench, Omega_v, w0, wa): """ Compare distances calculated by pyccl with the distances in the benchmark file. This test is only valid when radiation is explicitly set to 0. """ # Set Omega_K in a consistent way Omega_k = 1.0 - Omega_c - Omega_b - Omega_v cosmo = ccl.Cosmology(Omega_c=Omega_c, Omega_b=Omega_b, Neff=Neff, h=h, A_s=A_s, n_s=n_s, Omega_k=Omega_k, w0=w0, wa=wa, Omega_g=0) # Calculate distance using pyccl a = 1. / (1. + z) chi = ccl.comoving_radial_distance(cosmo, a) * h # Compare to benchmark data assert_allclose(chi, chi_bench, atol=1e-12, rtol=DISTANCES_TOLERANCE) # compare distance moudli where a!=1 a_not_one = (a != 1).nonzero() dm = ccl.distance_modulus(cosmo, a[a_not_one]) assert_allclose(dm, dm_bench[a_not_one], atol=1e-3, rtol=DISTANCES_TOLERANCE * 10)
def compare_distances_hiz(z, chi_bench, Omega_v, w0, wa): """ Compare distances calculated by pyccl with the distances in the benchmark file. This test is only valid when radiation is explicitly set to 0. """ # Set Omega_K in a consistent way Omega_k = 1.0 - Omega_c - Omega_b - Omega_v cosmo = ccl.Cosmology(Omega_c=Omega_c, Omega_b=Omega_b, Neff=Neff, h=h, A_s=A_s, n_s=n_s, Omega_k=Omega_k, w0=w0, wa=wa, Omega_g=0) # Calculate distance using pyccl a = 1. / (1. + z) chi = ccl.comoving_radial_distance(cosmo, a) * h # Compare to benchmark data assert_allclose(chi, chi_bench, atol=1e-12, rtol=DISTANCES_TOLERANCE)
def compare_distances_hiz_muSig(z, chi_bench, Omega_v, w0, wa): """ Compare distances calculated by pyccl with the distances in the benchmark file, for a ccl cosmology with mu / Sigma parameterisation of gravity. Nonzero mu / Sigma should NOT affect distances so we compare to the same benchmarks as the mu = Sigma = 0 case deliberately. """ # Set Omega_K in a consistent way Omega_k = 1.0 - Omega_c - Omega_b - Omega_v # Create new Parameters and Cosmology objects cosmo = ccl.Cosmology(Omega_c=Omega_c, Omega_b=Omega_b, Neff=Neff, h=h, A_s=A_s, n_s=n_s, Omega_k=Omega_k, w0=w0, wa=wa, mu_0=mu_0, sigma_0=sigma_0, Omega_g=0.) # Calculate distance using pyccl a = 1. / (1. + z) chi = ccl.comoving_radial_distance(cosmo, a) * h # Compare to benchmark data assert_allclose(chi, chi_bench, atol=1e-12, rtol=DISTANCES_TOLERANCE)
def test_cosmology_pickles(): """Check that a Cosmology object pickles.""" cosmo = ccl.Cosmology( Omega_c=0.25, Omega_b=0.05, h=0.7, A_s=2.1e-9, n_s=0.96, m_nu=[0.02, 0.1, 0.05], m_nu_type='list', z_mg=[0.0, 1.0], df_mg=[0.01, 0.0]) with tempfile.TemporaryFile() as fp: pickle.dump(cosmo, fp) fp.seek(0) cosmo2 = pickle.load(fp) assert_( ccl.comoving_radial_distance(cosmo, 0.5) == ccl.comoving_radial_distance(cosmo2, 0.5))
def cutWedge(self, noise, kperp, kpar, z, NW=3.0): r = ccl.comoving_radial_distance(self.C, 1 / (1. + z)) H = self.C['H0'] * ccl.h_over_h0(self.C, 1. / (1. + z)) slope = r * H / 3e5 * 1.22 * 0.21 / self.D * NW / 2.0 noiseout = np.copy(noise) noiseout[np.where(kpar < kperp * slope)] = 1e30 return noiseout
def compare_class_distances(z, chi_bench, dm_bench, Neff=3.0, m_nu=0.0, Omega_k=0.0, w0=-1.0, wa=0.0): """ Compare distances calculated by pyccl with the distances in the CLASS benchmark file. """ cosmo = ccl.Cosmology(Omega_c=Omega_c, Omega_b=Omega_b, Neff=Neff, h=h, A_s=A_s, n_s=n_s, Omega_k=Omega_k, m_nu=m_nu, w0=w0, wa=wa) # Calculate distance using pyccl a = 1. / (1. + z) chi = ccl.comoving_radial_distance(cosmo, a) # Compare to benchmark data assert_allclose(chi, chi_bench, rtol=DISTANCES_TOLERANCE_CLASS) # Compare distance moudli where a!=1 a_not_one = a != 1 dm = ccl.distance_modulus(cosmo, a[a_not_one]) assert_allclose(dm, dm_bench[a_not_one], rtol=DISTANCES_TOLERANCE_CLASS)
def compare_distances(z, chi_bench, Omega_v, w0, wa): """ Compare distances calculated by pyccl with the distances in the benchmark file. """ # Set Omega_K in a consistent way Omega_k = 1.0 - Omega_c - Omega_b - Omega_n - Omega_v # Create new Parameters and Cosmology objects p = ccl.Parameters(Omega_c=Omega_c, Omega_b=Omega_b, Omega_n=Omega_n, h=h, A_s=A_s, n_s=n_s, Omega_k=Omega_k, w0=w0, wa=wa) p.parameters.Omega_g = 0. # Hack to set to same value used for benchmarks cosmo = ccl.Cosmology(p) # Calculate distance using pyccl a = 1. / (1. + z) chi = ccl.comoving_radial_distance(cosmo, a) * h # Compare to benchmark data assert_allclose(chi, chi_bench, atol=1e-12, rtol=DISTANCES_TOLERANCE)
def compute_covmat_cv(cosmo, zm, dndz): # Area COSMOS area_deg2 = 1.7 area_rad2 = area_deg2 * (np.pi / 180)**2 theta_rad = np.sqrt(area_rad2 / np.pi) # TODO: Where do we get the area # Bin widths dz = np.mean(zm[1:] - zm[:-1]) # Number of galaxies in each bin dn = dndz * dz # z bin edges zb = np.append((zm - dz / 2.), zm[-1] + dz / 2.) # Comoving distance to bin edges chis = ccl.comoving_radial_distance(cosmo, 1. / (1 + zb)) # Mean comoving distance in each bin chi_m = 0.5 * (chis[1:] + chis[:-1]) # Comoving distance width dchi = chis[1:] - chis[:-1] # Disc radii R_m = theta_rad * chi_m # Galaxy bias b_m = 0.95 / ccl.growth_factor(cosmo, 1. / (1 + zm)) # Growth rate (for RSDs) f_m = ccl.growth_rate(cosmo, 1. / (1 + zm)) # Transverse k bins n_kt = 512 # Parallel k bins n_kp = 512 plt.plot(zm, dn, 'b-') plt.savefig('N_z.png') plt.close() # Transverse modes kt_arr = np.geomspace(0.00005, 10., n_kt) # Parallel modes kp_arr = np.geomspace(0.00005, 10., n_kp) # Total wavenumber k_arr = np.sqrt(kt_arr[None, :]**2 + kp_arr[:, None]**2) # B.H. changed a to float(a) pk_arr = np.array([(b+f*kp_arr[:,None]**2/k_arr**2)**2* ccl.nonlin_matter_power(cosmo,k_arr.flatten(),float(a)).reshape([n_kp,n_kt])\ for a,b,f in zip(1./(1+zm),b_m,f_m)]) window = np.array([2*jv(1,kt_arr[None,:]*R)/(kt_arr[None,:]*R)*np.sin(0.5*kp_arr[:,None]*dc)/\ (0.5*kp_arr[:,None]*dc) for R,dc in zip(R_m,dchi)]) # Estimating covariance matrix # avoiding getting 0s in covariance eps = 0.0 # Changed from dn to dndz B.H. and A.S. TODO: Check print("covmat_cv...") covmat_cv = np.array([[(ni+eps)*(nj+eps)*covar(i,j,window,pk_arr,chi_m,kp_arr,kt_arr) \ for i,ni in enumerate(dndz)] \ for j,nj in enumerate(dndz)]) return covmat_cv
def test_spline1d(): cosmo = ccl.CosmologyVanillaLCDM() cosmo.compute_distances() chi_gsl_spline = cosmo.cosmo.data.chi a_arr, chi_arr = ccl.pyutils._get_spline1d_arrays(chi_gsl_spline) chi = ccl.comoving_radial_distance(cosmo, a_arr) assert np.allclose(chi_arr, chi)
def test_cosmology_context(): """Check that using a Cosmology object in a context manager frees C resources properly.""" with ccl.Cosmology( Omega_c=0.25, Omega_b=0.05, h=0.7, A_s=2.1e-9, n_s=0.96, m_nu=np.array([0.02, 0.1, 0.05]), m_nu_type='list', z_mg=np.array([0.0, 1.0]), df_mg=np.array([0.01, 0.0])) as cosmo: # make sure it works assert not cosmo.has_distances ccl.comoving_radial_distance(cosmo, 0.5) assert cosmo.has_distances # make sure it does not! assert_(not hasattr(cosmo, "cosmo")) assert_(not hasattr(cosmo, "_params")) with pytest.raises(AttributeError): cosmo.has_growth
def PNoise(self, z, kperp): """Thermal noise power spectrum. Parameters ---------- z : float Redshift. kperp : float or array kperp value(s), in Mpc^-1. Returns ------- Pn : float or array Thermal noise power spectrum, in K^2 Mpc^3. """ # Observed wavelength lam = 0.21 * (1 + z) # m # Comoving radial distance to redshift z r = ccl.comoving_radial_distance(self.C, 1 / (1. + z)) # Mpc # Conversion between kperp and uv-plane (vector norm) u u = np.asarray(kperp) * r / (2 * np.pi) # Baseline length corresponding to u l = u * lam # m # Number density of baselines in uv plane Nu = self.nofl(l) * lam**2 # Inaccurate approximation for uv-plane baseline density #umax=self.Dmax/lam #Nu=self.Nd**2/(2*np.pi*umax**2) # Field of view of single dish FOV = (lam / self.Deff)**2 # sr # Hubble parameter H(z) Hz = self.C['H0'] * ccl.h_over_h0(self.C, 1. / (1. + z)) # km s^-1 Mpc^-1 # Conversion factor from frequency to physical space y = 3e5 * (1 + z)**2 / (1420e6 * Hz) # Mpc s # System temperature (sum of telescope and sky temperatures) Tsys = self.Tsky(1420. / (1 + z)) + self.Tscope # K # 21cm noise power spectrum (Eq. D4 of paper). # Hard-codes 2 polarizations Pn = Tsys**2 * r**2 * y * (lam**4 / self.Ae**2) * 1 / ( 2 * Nu * self.ttotal) * (self.Sarea / FOV) # K^2 Mpc^3 # Catastrophically fail if we've gotten negative power spectrum values if np.any(Pn < 0): print(Nu, Pn, l, self.nofl(l), self.nofl(l / 2)) stop() return Pn
def __init__(self, cosmo, z_max=6., n_chi=1024): self.chi_max = ccl.comoving_radial_distance(cosmo, 1. / (1 + z_max)) chi = np.linspace(0, self.chi_max, n_chi) a_arr = ccl.scale_factor_of_chi(cosmo, chi) H0 = cosmo['h'] / ccl.physical_constants.CLIGHT_HMPC OM = cosmo['Omega_c'] + cosmo['Omega_b'] Ez = ccl.h_over_h0(cosmo, a_arr) fz = ccl.growth_rate(cosmo, a_arr) w_arr = 3 * cosmo['T_CMB'] * H0**3 * OM * Ez * chi**2 * (1 - fz) self._trc = [] self.add_tracer(cosmo, kernel=(chi, w_arr), der_bessel=-1)
def thermal_n(kperp, zz, D=6.0, Ns=256, hex=True): """The thermal noise for PUMA -- note noise rescaling from 5->5/4 yr.""" # Some constants. etaA = 0.7 # Aperture efficiency. Aeff = etaA * np.pi * (D / 2)**2 # m^2 lam21 = 0.21 * (1 + zz) # m nuobs = 1420 / (1 + zz) # MHz # The cosmology-dependent factors. hub = C['h'] Ez = ccl.h_over_h0(C, 1. / (1. + zz)) chi = ccl.comoving_radial_distance(C, 1 / (1. + zz)) * hub # Mpc/h. #hub = cc.H(0).value / 100.0 #Ez = cc.H(zz).value / cc.H(0).value #chi = cc.comoving_distance(zz).value * hub # Mpc/h. OmHI = 4e-4 * (1 + zz)**0.6 / Ez**2 Tbar = 0.188 * hub * (1 + zz)**2 * Ez * OmHI # K # Eq. (3.3) of Chen++19 d2V = chi**2 * 2997.925 / Ez * (1 + zz)**2 # Eq. (3.5) of Chen++19 if hex: # Hexagonal array of Ns^2 elements. n0, c1, c2, c3, c4, c5 = ( Ns / D)**2, 0.5698, -0.5274, 0.8358, 1.6635, 7.3177 uu = kperp * chi / (2 * np.pi) xx = uu * lam21 / Ns / D # Dimensionless. nbase = n0 * (c1 + c2 * xx) / ( 1 + c3 * xx**c4) * np.exp(-xx**c5) * lam21**2 + 1e-30 #nbase[uu< D/lam21 ]=1e-30 nbase[uu > Ns * D / lam21 * 1.3] = 1e-30 else: # Square array of Ns^2 elements. n0, c1, c2, c3, c4, c5 = (Ns / D)**2, 0.4847, -0.33, 1.3157, 1.5974, 6.8390 uu = kperp * chi / (2 * np.pi) xx = uu * lam21 / Ns / D # Dimensionless. nbase = n0 * (c1 + c2 * xx) / ( 1 + c3 * xx**c4) * np.exp(-xx**c5) * lam21**2 + 1e-30 #nbase[uu< D/lam21 ]=1e-30 nbase[uu > Ns * D / lam21 * 1.4] = 1e-30 # Eq. (3.2) of Chen++19 npol = 2 fsky = 0.5 tobs = 5. * 365.25 * 24. * 3600. # sec. tobs /= 4.0 # Scale to 1/2-filled array. Tamp = 62.0 # K Tgnd = 33.0 # K Tsky = 2.7 + 25 * (400. / nuobs)**2.75 # K Tsys = Tamp + Tsky + Tgnd Omp = (lam21 / D)**2 / etaA # Return Pth in "cosmological units", with the Tbar divided out. Pth = (Tsys/Tbar)**2*(lam21**2/Aeff)**2 *\ 4*np.pi*fsky/Omp/(npol*1420e6*tobs*nbase) * d2V return (Pth)
def plot_covar(predir, sample, bn, sample_label, kmax=1., lmin=0.): z, nz = np.loadtxt('data/dndz/' + sample.upper() + '_bin%d.txt' % bn, unpack=True) zmean = np.sum(z * nz) / np.sum(nz) chi = ccl.comoving_radial_distance(cosmo, 1 / (1 + zmean)) lmax = kmax * chi - 0.5 if sample != "2mpz": gsample = sample + '%d' % bn else: gsample = sample l = np.load("output_default/cls_" + gsample + '_' + gsample + ".npz")['ls'] msk_gg = (l <= lmax) & (l >= lmin) msk_gy = (l <= lmax) ngg = np.sum(msk_gg) ngy = np.sum(msk_gy) nt = ngg + ngy cv_gg_gg = np.load(predir + '/cov_comb_m_' + gsample + '_' + gsample + '_' + gsample + '_' + gsample + '.npz')['cov'][msk_gg, :][:, msk_gg] cv_gg_gy = np.load(predir + '/cov_comb_m_' + gsample + '_' + gsample + '_' + gsample + '_y_milca.npz')['cov'][msk_gg, :][:, msk_gy] cv_gy_gy = np.load(predir + '/cov_comb_m_' + gsample + '_y_milca_' + gsample + '_y_milca.npz')['cov'][msk_gy, :][:, msk_gy] cov = np.zeros([nt, nt]) cov[:ngg, :ngg] = cv_gg_gg cov[:ngg, ngg:] = cv_gg_gy cov[ngg:, :ngg] = cv_gg_gy.T cov[ngg:, ngg:] = cv_gy_gy plt.figure() ax = plt.gca() im = ax.imshow(get_corr(cov), interpolation='nearest', vmin=0, vmax=1, cmap=cm.gray) ax.tick_params(length=0) ax.set_xticks([ngg / 2, ngg + ngy / 2]) ax.set_xticklabels(['$g\\,\\times\\,g$', '$g\\,\\times\\,y$']) ax.set_yticks([0.4 * ngg, ngg + 0.4 * ngy]) ax.set_yticklabels(['$g\\,\\times\\,g$', '$g\\,\\times\\,y$'], rotation=90) ax.text(0.03, 0.04, sample_label, transform=ax.transAxes, bbox=dict(facecolor='white', alpha=1), fontsize=14) ax.tick_params(labelsize="x-large") plt.savefig('notes/paper/cov_' + gsample + '.pdf', bbox_inches='tight')
def Ntot(z, mhmin, fsky=1.): """ Calculate the total number of dark matter halos above a given mass threshold, as a function of maximum redshift and sky fraction. """ # Calculate cumulative number density n(>M_min) as a fn of M_min and redshift ndens = nm(z, mhmin=mhmin) # Integrate over comoving volume of lightcone r = ccl.comoving_radial_distance(cosmo, a) # Comoving distance, r H = 100. * cosmo['h'] * ccl.h_over_h0(cosmo, a) # H(z) in km/s/Mpc Ntot = integrate.cumtrapz(ndens * r**2. / H, z, initial=0.) Ntot *= 4. * np.pi * fsky * C_kms return Ntot
def __init__(self, m, kmax=np.inf): self.name = m['name'] self.type = m['type'] self.beam = m['beam'] self.syst = m.get('systematics') self.lmax = np.inf self.profile = None self.tracer = None if m['type'] == 'y': self.profile = ccl.halos.HaloProfilePressureGNFW() else: cM = m["halo_concentration"] if m['type'] == 'g': # truncate N(z)'s self.dndz = m['dndz'] self.z, self.nz = np.loadtxt(self.dndz).T self.nzf = interp1d(self.z, self.nz, kind='cubic', bounds_error=False, fill_value=0.) self.z_avg = np.average(self.z, weights=self.nz) self.zrange = self.z[self.nz >= 0.005].take([0, -1]) # determine max ell cosmo = ccl.CosmologyVanillaLCDM() chimean = ccl.comoving_radial_distance(cosmo, 1 / (1 + self.z_avg)) self.lmax = kmax * chimean - 0.5 self.bz = np.ones_like(self.z) ns_ind = m.get("ns_independent", False) self.profile = ccl.halos.HaloProfileHOD(c_m_relation=cM, ns_independent=ns_ind) elif m['type'] == 'k': self.profile = ccl.halos.HaloProfileNFW(c_m_relation=cM) if self.profile is not None: try: func = self.profile.update_parameters if hasattr(func, "__wrapped__"): # bypass the decorator func = func.__wrapped__ args = func.__code__.co_varnames code = func.__code__ count = code.co_argcount + code.co_kwonlyargcount self.args = args[1:count] # discard self & locals except AttributeError: # profile has no parameters self.args = {}
def test_iswcl(): # Cosmology Ob = 0.05 Oc = 0.25 h = 0.7 COSMO = ccl.Cosmology(Omega_b=Ob, Omega_c=Oc, h=h, n_s=0.96, sigma8=0.8, transfer_function='bbks') # CCL calculation ls = np.arange(2, 100) zs = np.linspace(0, 0.6, 256) nz = np.exp(-0.5 * ((zs - 0.3) / 0.05)**2) bz = np.ones_like(zs) tr_n = ccl.NumberCountsTracer(COSMO, has_rsd=False, dndz=(zs, nz), bias=(zs, bz)) tr_i = ccl.ISWTracer(COSMO) cl = ccl.angular_cl(COSMO, tr_n, tr_i, ls) # Benchmark from Eq. 6 in 1710.03238 pz = nz / simps(nz, x=zs) H0 = h / ccl.physical_constants.CLIGHT_HMPC # Prefactor prefac = 3 * COSMO['T_CMB'] * (Oc + Ob) * H0**3 / (ls + 0.5)**2 # H(z)/H0 ez = ccl.h_over_h0(COSMO, 1. / (1 + zs)) # Linear growth and derivative dz = ccl.growth_factor(COSMO, 1. / (1 + zs)) gz = np.gradient(dz * (1 + zs), zs[1] - zs[0]) / dz # Comoving distance chi = ccl.comoving_radial_distance(COSMO, 1 / (1 + zs)) # P(k) pks = np.array([ ccl.nonlin_matter_power(COSMO, (ls + 0.5) / (c + 1E-6), 1. / (1 + z)) for c, z in zip(chi, zs) ]).T # Limber integral cl_int = pks[:, :] * (pz * ez * gz)[None, :] clbb = simps(cl_int, x=zs) clbb *= prefac assert np.all(np.fabs(cl / clbb - 1) < 1E-3)
def rofZ(self, z): """Calculate comoving radial distance from redshift. Parameters ---------- z : np.array Array of cosmological redshifts Returns ------- r : np.array Array of comoving radial distance corresponding to input redshifts """ r = ccl.comoving_radial_distance(self._cosmo, 1 / (z + 1.)) return r
def test_Sigma2B(): # Check projected variance calculation against # explicit integration from scipy.special import jv from scipy.integrate import simps fsky = 0.1 # Default sampling a, s2b_a = ccl.sigma2_B_disc(COSMO, fsky=fsky) idx = (a > 0.5) & (a < 1) a_use = a[idx] # Input sampling s2b_b = ccl.sigma2_B_disc(COSMO, a=a_use, fsky=fsky) # Scalar input sampling s2b_c = np.array([ccl.sigma2_B_disc(COSMO, a=a, fsky=fsky) for a in a_use]) # Alternative calculation chis = ccl.comoving_radial_distance(COSMO, a_use) Rs = np.arccos(1 - 2 * fsky) * chis def integrand(lk, a, R): k = np.exp(lk) x = k * R w = 2 * jv(1, x) / x pk = ccl.linear_matter_power(COSMO, k, a) return w * w * k * k * pk / (2 * np.pi) lk_arr = np.log(np.geomspace(1E-4, 1E1, 1024)) s2b_d = np.array( [simps(integrand(lk_arr, a, R), x=lk_arr) for a, R in zip(a_use, Rs)]) assert np.all(np.fabs(s2b_b / s2b_a[idx] - 1) < 1E-10) assert np.all(np.fabs(s2b_c / s2b_a[idx] - 1) < 1E-10) assert np.all(np.fabs(s2b_d / s2b_a[idx] - 1) < 1E-3) # Check calculation based on mask Cls against the disc calculation ell = np.arange(1000) theta = np.arccos(1 - 2 * fsky) kR = (ell + 0.5) * theta mask_wl = (ell + 0.5) / (2 * np.pi) * (2 * jv(1, kR) / (kR))**2 a_use = np.array([0.2, 0.5, 1.0]) s2b_e = ccl.sigma2_B_from_mask(COSMO, a=a_use, mask_wl=mask_wl) s2b_f = ccl.sigma2_B_disc(COSMO, a=a_use, fsky=fsky) assert np.all(np.fabs(s2b_e / s2b_f - 1) < 1E-3)
def __init__(self, m, cosmo, kmax): self.name = m['name'] self.type = m['type'] self.beam = m['beam'] self.dndz = m.get('dndz') # Estimate z-range and ell-max if self.dndz is not None: z, nz = np.loadtxt(self.dndz, unpack=True) z_inrange = z[nz >= 0.005 * np.amax(nz)] self.z_range = [z_inrange[0], z_inrange[-1]] zmean = np.sum(z * nz) / np.sum(nz) chimean = ccl.comoving_radial_distance(cosmo, 1. / (1 + zmean)) self.lmax = kmax * chimean - 0.5 else: self.z_range = [1E-6, 6] self.lmax = 100000 self.profile = get_profile(m) self.syst = m.get('systematics')
def main(): parser = OptionParser() parser.add_option('--input-sacc','-i',dest="fname_in",default=None, help='Name of input SACC file') parser.add_option('--output-sacc','-o',dest="fname_out",default=None, help='Name of output SACC file') parser.add_option('--show-plot',dest="show_plot",default=False,action="store_true", help="Show plot comparing data and theory") parser.add_option('--param-file',dest="param_file",default=None, help="Path to CoLoRe param file") parser.add_option('--power-spectrum-type',dest="pk",default='linear',type=str, help="Power spectrum type: [`linear`,`halofit`]") parser.add_option('--transfer-function',dest="tf",default='boltzmann',type=str, help="Type of transfer function: [`eisenstein_hu`,`bbks`,`boltzmann`,`halofit`]") parser.add_option("--include-rsd",dest="rsd",default=False,action="store_true", help="Include RSD") parser.add_option("--dz-lognormal",dest="dz_ln",default=0.05,type=float, help="Redshift interval to use in computation of lognormal prediction") parser.add_option("--do-lognormal",dest="do_ln",default=False,action="store_true", help="Do we want to do the lognormal transformation?") (o, args) = parser.parse_args() #Read cosmological parameters and set cosmology object print("Reading CoLoRe params") with io.open(o.param_file) as f : colore_dict=lcf.load(f) ob=colore_dict['cosmo_par']['omega_B'] om=colore_dict['cosmo_par']['omega_M'] oc=om-ob hhub=colore_dict['cosmo_par']['h'] ns=colore_dict['cosmo_par']['ns'] sigma8=colore_dict['cosmo_par']['sigma_8'] cosmo = ccl.Cosmology(ccl.Parameters(Omega_c=oc,Omega_b=ob,h=hhub,sigma8=sigma8,n_s=ns,), matter_power_spectrum=o.pk,transfer_function=o.tf) #Calculate effective smoothing scale zmax=colore_dict['global']['z_max'] ngrid=colore_dict['field_par']['n_grid'] rsm0=colore_dict['field_par']['r_smooth'] Lbox=2*ccl.comoving_radial_distance(cosmo,1./(1+zmax))*(1+2./ngrid)*hhub a_grid=Lbox/ngrid rsm_tot=np.sqrt(rsm0**2+a_grid**2/12.) #Estimate lognormal prediction print("Estimating lognormal prediction") cmd="./lnpred " cmd+="%lf "%om cmd+="%lf "%ob cmd+="%lf "%hhub cmd+="%lf "%ns cmd+="%lf "%sigma8 cmd+=colore_dict['srcs1']['bias_filename']+" " cmd+="%lf "%rsm_tot cmd+="%lf "%zmax cmd+="%lf "%o.dz_ln cmd+=o.tf+" " cmd+=o.fname_out+".lnpred " if o.do_ln>0 : cmd+="1 " else : cmd+="0 " # cmd+="> "+o.fname_out+".lnpred_log" os.system(cmd) #Read lognormal prediction # Note that the lognormal prediction can be negative due to numerical instabilities. # The lines below make sure that the power spectrum is always positive, and extrapolate # it beyond the range where it becomes unreliable numz=int(zmax/o.dz_ln) numk=len(np.loadtxt(o.fname_out+".lnpred_pk_z0.000.txt",unpack=True)[0]) pk2d=np.zeros([numz,numk]) zarr=o.dz_ln*(numz-1-np.arange(numz)) aarr=1./(1+zarr) for i in np.arange(numz) : z=o.dz_ln*(numz-1-i) karr,pk,dum1,dum2=np.loadtxt(o.fname_out+".lnpred_pk_z%.3lf.txt"%z,unpack=True) idpos=np.where(pk>0)[0]; if len(idpos)>0 : idmax=idpos[-1] pk=np.maximum(pk,pk[idmax]) w=1./karr**6 pk[idmax:]=pk[idmax]*w[idmax:]/w[idmax] pk2d[i,:]=pk pk2d=pk2d.flatten() karr*=hhub pk2d/=hhub**3 #Cleanup os.system('rm '+o.fname_out+'.lnpred*') #Update power spectrum in cosmo to lognormal prediction (both linear and non-linear) ccl.update_matter_power(cosmo,karr,aarr,pk2d,is_linear=True) ccl.update_matter_power(cosmo,karr,aarr,pk2d,is_linear=False) print('Reading SACC file') #SACC File with the N(z) to analyze binning_sacc = sacc.SACC.loadFromHDF(o.fname_in) print("Setting up CCL tracers") tracers = binning_sacc.tracers cltracers=[ccl.ClTracer(cosmo,'nc',has_rsd=o.rsd,has_magnification=False,n=(t.z,t.Nz), bias=(t.z,np.ones_like(t.z))) for t in tracers] print('Computing power spectra') theories = getTheories(cosmo,binning_sacc,cltracers) mean=getTheoryVec(binning_sacc,theories) csacc=sacc.SACC(tracers,binning_sacc.binning,mean) csacc.printInfo() csacc.saveToHDF(o.fname_out,save_precision=False) if o.show_plot: plt.figure() for t in tracers : plt.plot(t.z,t.Nz) plt.show() print('Done')