def __init__(self): # read file of parameters of polynomial fit to k-correction cmin, cmax, A, B, C, D, E, cmed = \ np.loadtxt(par.k_corr_file, unpack=True) self.z0 = 0.1 # reference redshift # Polynomial fit parameters self.__A_interpolator = self.__initialize_parameter_interpolator( A, cmed) self.__B_interpolator = self.__initialize_parameter_interpolator( B, cmed) self.__C_interpolator = self.__initialize_parameter_interpolator( C, cmed) self.__D_interpolator = self.__initialize_parameter_interpolator( D, cmed) self.__E = E[0] self.colour_min = np.min(cmed) self.colour_max = np.max(cmed) self.colour_med = cmed self.cosmo = Cosmology(par.h0, par.OmegaM, par.OmegaL) # Linear extrapolation self.__X_interpolator = lambda x: None self.__Y_interpolator = lambda x: None self.__X_interpolator, self.__Y_interpolator = \ self.__initialize_line_interpolators()
def set_agelim(self, redshift): ''' Set the Age limit based on age of the universe ''' C = Cosmology() # self.age_lims[1] = np.log10(C.lookback_time(20.) - # C.lookback_time(redshift)) self.age = np.log10(C.lookback_time(20.) - C.lookback_time(redshift)) self.tdiff = np.diff(10**np.vstack([[0.] + self.ages, [self.age + 9.] * (len(self.ages) + 1)]).min(axis=0))
def set_agelim(self, redshift): ''' Set the Age limit based on age of the universe ''' C = Cosmology() self.age = np.log10(C.lookback_time(20.) - C.lookback_time(redshift)) # adjust priors on all age bins that are too old indx_too_old = np.where( self.age < np.array(self.ages)-9. )[0] if len(indx_too_old) > 1: for num in indx_too_old[1:]+1: setattr(self, 'sfr_' + str(num), -99.) setattr(self, 'sfr_' + str(num) + '_lims', [-99-1e-9,-99+1e-9]) setattr(self, 'sfr_' + str(num) + '_delta', 1e-9)
def run_class_fs8_bao(self, cosmo=Cosmology.Planck2018(), z=0.): extra = self.run_class(cosmo, Cosmology.compute_fs8_bao, todo_kwargs={'z': z}) for par in extra: self.latex[par] = cosmology.par_to_latex( par) + '(z={:.3f})'.format(z)
def get_r200(self, comoving=True): """ Returns R200mean of each halo Args: comoving: (optional) if True convert to comoving distance Returns: array of R200mean [Mpc/h] """ cosmo = Cosmology(par.h0, par.OmegaM, par.OmegaL) rho_mean = cosmo.mean_density(self.get("zcos")) r200 = (3./(800*np.pi) * self.get("mass") / rho_mean)**(1./3) if comoving: return r200 * (1.+self.get("zcos")) else: return r200
def plotpractice(self, wave, z): from cosmology import Cosmology C = Cosmology() D = C.luminosity_distance(z) dustem1 = self.evaluate(wave) dustem = np.interp(wave, wave * (1. + z), dustem1 * (1. + z)) dustem/=D**2 #Divide by distance ^ 2 (to get flux) dustem*=1.0e-29 #Go from uJy to erg/cm^2/s/Hz nu = 3.0e18/wave plt.figure() plt.loglog(wave/1.0e4, nu*dustem, 'b-') xlims = np.array([2.0,1000.])/(1.+z) plt.xlim(xlims) plt.xlabel(r"$\lambda$ ($\mu m$)") plt.ylabel(r"Dust emissivity (erg cm$^{-1}$ s$^{-1}$) ") plt.savefig("DustTesting/%.2f_%.4f_%.2f_%.3f.png"%(self.umin,self.gamma,self.qpah,self.mdust)) plt.show()
def test(): from cosmology import Cosmology import parameters as par cos = Cosmology(par.h0, par.OmegaM, par.OmegaL) from halo_catalogue import MXXLCatalogue halo_cat = MXXLCatalogue() gal_cat = BGSGalaxyCatalogue(halo_cat, cos) from hod import HOD_BGS hod = HOD_BGS() gal_cat.add_galaxies(hod) print(len(gal_cat.get("abs_mag")), len(gal_cat.get_halo("ra"))) print(len(gal_cat.haloes.get("ra"))) gal_cat.position_galaxies() ##gal_cat.cut(gal_cat.get("zcos")<0.1) rah, dech = gal_cat.get_halo("ra"), gal_cat.get_halo("dec") zcosh, zobsh = gal_cat.get_halo("zcos"), gal_cat.get_halo("zobs") ra, dec = gal_cat.get("ra"), gal_cat.get("dec") zcos, zobs = gal_cat.get("zcos"), gal_cat.get("zobs") ra[ra > 100] -= 360 is_sat = gal_cat.get("is_sat") import matplotlib.pyplot as plt plt.scatter(rah, dech, s=3, edgecolor="none") plt.scatter(ra[is_sat], dec[is_sat], s=3, edgecolor="none") plt.show() plt.scatter(zcos, zcosh, s=1, edgecolor="none") plt.show() plt.scatter(zobs, zobsh, s=1, edgecolor="none") plt.show() plt.scatter(zcosh, ra - rah, s=1, edgecolor="none") plt.show() plt.scatter(zcosh, dec - dech, s=1, edgecolor="none") plt.show()
def __init__(self): self.mf = MassFunction() self.cosmo = Cosmology(par.h0, par.OmegaM, par.OmegaL) self.lf = LuminosityFunctionTarget(par.lf_file, par.Phi_star, par.M_star, par.alpha, par.P, par.Q) self.kcorr = GAMA_KCorrection() self.__slide_interpolator = self.__initialize_slide_factor_interpolator( ) self.__logMmin_interpolator = \ self.__initialize_mass_interpolator(par.Mmin_Ls, par.Mmin_Mt, par.Mmin_am) self.__logM1_interpolator = \ self.__initialize_mass_interpolator(par.M1_Ls, par.M1_Mt, par.M1_am) self.__central_interpolator = self.__initialize_central_interpolator() self.__satellite_interpolator = \ self.__initialize_satellite_interpolator()
def get_max_ssp_age(args, z=None): ''' Identify the maximum SSP age for the sample (i.e., at upper/lower redshifts) Max SSP age is the time between redshift z=20 and redshift of the galaxy Parameters ---------- args : class The args class is carried from function to function with information from command line input and config.py z : float (optional) if specific redshift is passed, evaluate max age at that redshift otherwise, evaluate for the range of redshifts of the sample Returns ------- maxage : tuple of (float, float) the youngest and oldest maximum age (in log years) of sample galaxies ''' C = Cosmology() if z is not None: maxage = np.log10(C.lookback_time(20) - C.lookback_time(z)) + 9. return maxage if not args.test: F = Table.read(args.filename, format='ascii') z = F['z'] zrange = (min(z), max(z)) else: zrange = args.test_zrange # ages in log years: maxage_lo = np.log10(C.lookback_time(20) - C.lookback_time(zrange[1])) + 9. maxage_hi = np.log10(C.lookback_time(20) - C.lookback_time(zrange[0])) + 9. return (maxage_lo, maxage_hi)
def __init__(self, haloes): self._quantities = {} self.size = 0 self.haloes = haloes self.cosmology = Cosmology(par.h0, par.OmegaM, par.OmegaL)
n_simulations = len(sim_dirs) sim_ids = range(n_simulations) sim_ids_local = split_indices(sim_ids, rank, n_procs) print(f'proc_id: {rank} sim_ids_local:{sim_ids_local}') for sim_id in sim_ids_local: sim_dir = root_dir + sim_dirs[sim_id] + '/' uvb_rates_file = sim_dir + 'UVB_rates.h5' output_dir = thermal_dir + f'{sim_dirs[sim_id]}/' print(f'UVB Rates File: {uvb_rates_file}') print(f'Output Dir: {output_dir}') create_directory(output_dir, print_out=False) # Initialize Cosmology z_start = 16 cosmo = Cosmology(z_start) # Initialize parameters n_samples = 10000 z_end = 2. T_start = 5 X = 0.75984 # Set Number Densities rho_gas_mean = cosmo.rho_gas_mean # kg cm^-3 rho_H = X * rho_gas_mean rho_He = (1 - X) * rho_gas_mean n_H_comov = rho_H / M_p # cm^-3 n_He_comov = rho_He / (4 * M_p) # cm^-3 a_start = 1. / (z_start + 1) rho_cgs = rho_gas_mean * 1e3 / a_start**3
def set_agelim(self, redshift): ''' Set the Age limit based on age of the universe ''' C = Cosmology() self.age = np.log10(C.lookback_time(20.) - C.lookback_time(redshift))
class PowerSpec(object): """ Class containing the linear power spectrum and useful methods Args: filename: Tabulated file of linear P(k) at z=0 h0: Hubble parameter at z=0, in units [100 km/s/Mpc] OmegaM: Omega matter at z=0 """ def __init__(self, filename, h0, OmegaM): self.k, self.P = np.loadtxt(filename, unpack=True) self.cosmo = Cosmology(h0, OmegaM) self.tck = self.__get_sigma_spline() #spline fit to sigma(M,z=0) def P_lin(self, k, z): """ Returns the linear power spectrum at redshift z Args: k: array of k in units [h/Mpc] z: array of z Returns: array of linear power spectrum in units [Mpc/h]^-3 """ tck = splrep(np.log10(self.k), np.log10(self.P)) P0 = 10**splev(np.log10(k), tck) return P0 * self.cosmo.growth_factor(z)**2 def Delta2_lin(self, k, z): """ Returns the dimensionless linear power spectrum at redshift z, defined as Delta^2(k) = 4pi * (k/2pi)^3 * P(k) Args: k: array of k in units [h/Mpc] z: array of z Returns: array of dimensionless linear power spectrum """ return self.P_lin(k, z) * k**3 / (2 * np.pi**2) def W(self, k, R): """ Window function in k-space (Fourier transform of top hat window) Args: k: array of k in units [h/Mpc] z: array of R in units [Mpc/h] Returns: window function """ return 3 * (np.sin(k * R) - k * R * np.cos(k * R)) / (k * R)**3 def R_to_M(self, R): """ Average mass enclosed by a sphere of comoving radius R Args: R: array of comoving radius in units [Mpc/h] Returns: array of mass in units [Msun/h] """ return 4. / 3 * np.pi * R**3 * self.cosmo.mean_density(0) def M_to_R(self, M): """ Comoving radius of a sphere which encloses on average mass M Args: M: array of mass in units [Msun/h] Returns: array of comoving radius in units [Mpc/h] """ return (3 * M / (4 * np.pi * self.cosmo.mean_density(0)))**(1. / 3) def __func(self, k, R): # function to integrate to get sigma(M) return self.k**2 * self.P * self.W(k, R)**2 def __get_sigma_spline(self): # spline fit to sigma(R) at z=0 logR = np.arange(-2, 2, 0.01) sigma = np.zeros(len(logR)) R = 10**logR for i in range(len(R)): sigma[i] = simps(self.__func(self.k, R[i]), self.k) sigma = sigma / (2 * np.pi**2) sigma = np.sqrt(sigma) return splrep(logR, np.log10(sigma)) def sigmaR_z0(self, R): """ Returns sigma(R), the rms mass fluctuation in spheres of radius R, at redshift 0 Args: R: array of comoving distance in units [Mpc/h] Returns: array of sigma """ return 10**splev(np.log10(R), self.tck) def sigmaR(self, R, z): """ Returns sigma(R,z), the rms mass fluctuation in spheres of radius R, at redshift z Args: R: array of comoving distance in units [Mpc/h] z: array of redshift Returns: array of sigma """ return self.sigmaR_z0(R) * self.delta_c(0) / self.delta_c(z) def sigma_z0(self, M): """ Returns sigma(M), the rms mass fluctuation in spheres of mass M, at redshift 0 Args: M: array of mass in units [Msun/h] Returns: array of sigma """ R = self.M_to_R(M) return self.sigmaR_z0(R) def sigma(self, M, z): """ Returns sigma(M), the rms mass fluctuation in spheres of mass M, at redshift z Args: M: array of mass in units [Msun/h] z: array of redshift Returns: array of sigma """ return self.sigma_z0(M) * self.delta_c(0) / self.delta_c(z) def nu(self, M, z): """ Returns nu = delta_c(z=0) / (sigma(M,z=0) * D(z)) Args: M: array of mass in units [Msun/h] z: array of redshift Returns: array of nu """ return self.delta_c(z) / self.sigma_z0(M) def f_ST(self, nu): """ Returns Sheth-Tormen mass function Args: nu: array of nu Returns: array of mass function """ A = 0.216 q = 0.707 p = 0.3 x = q * nu**2 return A * (1. + 1. / x**p) * np.exp(-x / 2.) def mass_function(self, M, z): """ Returns number density of haloes predicted by the Sheth-Tormen mass function Args: M: array of mass in units [Msun/h] z: array of redshift Returns: array of number density in units [Mpc/h]^-3 """ nu = self.nu(M, z) f = self.f_ST(nu) return f * nu * -self.alpha(M,z) * np.log(10) * \ self.cosmo.mean_density(0) / M def b(self, nu, z): """ Returns Sheth-Tormen halo bias, where the values of the parameters have been modified to reproduce the halo bias measured from the OuterRim simulation, in which haloes are defined as friends-of-friends groups with linking length b=0.168 Args: nu: array of nu z: array of redshift Returns: array of halo bias """ # bias (peak background split) dc = self.delta_c(0) a = 0.707 * 1.15 p = 0.15 x = a * nu**2 A = (x - 1.) / dc B = 2 * p / (dc * (1. + x**p)) return 1. + A + B def bM(self, M, z): """ Returns Sheth-Tormen halo bias, as a function of mass, where the values of the parameters have been modified to reproduce the halo bias measured from the OuterRim simulation, in which haloes are defined as friends-of-friends groups with linking length b=0.168 Args: M: array of mass in units [Msun/h] z: array of redshift Returns: array of halo bias """ nu = self.nu(M, z) return self.b(nu, z) def __f_int1(self, M, z): #function to integrate when calculating b_eff nu = self.nu(M, z) x = self.b(nu, z) * self.f_ST(nu) / M return x def __f_int2(self, M, z): #function to integrate when calculating b_eff nu = self.nu(M, z) return self.f_ST(nu) / M def b_eff(self, Mmin, Mmax, z): """ Returns the effective bias of haloes in the mass range Mmin < M < Mmax at redshift z Args: Mmin: minimum halo mass in units [Msun/h] Mmax: maximum halo mass in units [Msun/h] z: redshift Returns: effective halo bias """ A = quad(self.__f_int1, Mmin, Mmax, args=z)[0] B = quad(self.__f_int2, Mmin, Mmax, args=z)[0] return A / B def R_nl(self, z): """ Returns the non-linear scale, defined as the value of R where sigma(R,z) = 1 Args: z: redshift Returns: non-linear scale in units [Mpc/h] """ def func(logM, z): return np.log10(self.sigma(10**logM, z))**2 M = 10**minimize(func, x0=12, args=(z, ))['x'] R = self.M_to_R(M) return R def var_f(self, Rnl, Lbox, z): """ Returns the expected variance of the the smoothed displacement field Args: Rnl: non-linear smoothing scale in units [Mpc/h] Lbox: simulation box size in units [Mpc/h] z: redshift Returns: variance of the displacement field """ def func(k, Rnl, z): return np.exp(-(k**2*Rnl**2)) * \ self.Delta2_lin(k,z) / k**2 kbox = 2 * np.pi / Lbox lnk = np.arange(np.log(kbox), 10, 0.001) k = np.exp(lnk) f = func(k, Rnl, z) return np.sum(f) * 0.001 def delta_c(self, z): """ Returns delta_c, the linear density threshold for collapse, at redshift z Args: z: redshift Returns: delta_c """ return 1.686 / self.cosmo.growth_factor(z)
def __init__(self, filename, h0, OmegaM): self.k, self.P = np.loadtxt(filename, unpack=True) self.cosmo = Cosmology(h0, OmegaM) self.tck = self.__get_sigma_spline() #spline fit to sigma(M,z=0)
class GAMA_KCorrection(KCorrection): """ Colour-dependent polynomial fit to the GAMA K-correction (Fig. 13 of Smith+17), used to convert between SDSS r-band Petrosian apparent magnitudes, and rest frame absolute manigutues at z_ref = 0.1 """ def __init__(self): # read file of parameters of polynomial fit to k-correction cmin, cmax, A, B, C, D, E, cmed = \ np.loadtxt(par.k_corr_file, unpack=True) self.z0 = 0.1 # reference redshift # Polynomial fit parameters self.__A_interpolator = self.__initialize_parameter_interpolator( A, cmed) self.__B_interpolator = self.__initialize_parameter_interpolator( B, cmed) self.__C_interpolator = self.__initialize_parameter_interpolator( C, cmed) self.__D_interpolator = self.__initialize_parameter_interpolator( D, cmed) self.__E = E[0] self.colour_min = np.min(cmed) self.colour_max = np.max(cmed) self.colour_med = cmed self.cosmo = Cosmology(par.h0, par.OmegaM, par.OmegaL) # Linear extrapolation self.__X_interpolator = lambda x: None self.__Y_interpolator = lambda x: None self.__X_interpolator, self.__Y_interpolator = \ self.__initialize_line_interpolators() def __initialize_parameter_interpolator(self, parameter, median_colour): # interpolated polynomial coefficient as a function of colour return RegularGridInterpolator((median_colour, ), parameter, bounds_error=False, fill_value=None) def __initialize_line_interpolators(self): # linear coefficients for z>0.5 X = np.zeros(7) Y = np.zeros(7) # find X, Y at each colour redshift = np.array([0.4, 0.5]) arr_ones = np.ones(len(redshift)) for i in range(7): k = self.k(redshift, arr_ones * self.colour_med[i]) X[i] = (k[1] - k[0]) / (redshift[1] - redshift[0]) Y[i] = k[0] - X[i] * redshift[0] X_interpolator = RegularGridInterpolator((self.colour_med, ), X, bounds_error=False, fill_value=None) Y_interpolator = RegularGridInterpolator((self.colour_med, ), Y, bounds_error=False, fill_value=None) return X_interpolator, Y_interpolator def __A(self, colour): # coefficient of the z**4 term colour_clipped = np.clip(colour, self.colour_min, self.colour_max) return self.__A_interpolator(colour_clipped) def __B(self, colour): # coefficient of the z**3 term colour_clipped = np.clip(colour, self.colour_min, self.colour_max) return self.__B_interpolator(colour_clipped) def __C(self, colour): # coefficient of the z**2 term colour_clipped = np.clip(colour, self.colour_min, self.colour_max) return self.__C_interpolator(colour_clipped) def __D(self, colour): # coefficient of the z**1 term colour_clipped = np.clip(colour, self.colour_min, self.colour_max) return self.__D_interpolator(colour_clipped) def __X(self, colour): colour_clipped = np.clip(colour, self.colour_min, self.colour_max) return self.__X_interpolator(colour_clipped) def __Y(self, colour): colour_clipped = np.clip(colour, self.colour_min, self.colour_max) return self.__Y_interpolator(colour_clipped) def k(self, redshift, colour): """ Polynomial fit to the GAMA K-correction for z<0.5 The K-correction is extrapolated linearly for z>0.5 Args: redshift: array of redshifts colour: array of ^0.1(g-r) colour Returns: array of K-corrections """ K = np.zeros(len(redshift)) idx = redshift <= 0.5 K[idx] = self.__A(colour[idx])*(redshift[idx]-self.z0)**4 + \ self.__B(colour[idx])*(redshift[idx]-self.z0)**3 + \ self.__C(colour[idx])*(redshift[idx]-self.z0)**2 + \ self.__D(colour[idx])*(redshift[idx]-self.z0) + self.__E idx = redshift > 0.5 K[idx] = self.__X(colour[idx]) * redshift[idx] + self.__Y(colour[idx]) return K def apparent_magnitude(self, absolute_magnitude, redshift, colour): """ Convert absolute magnitude to apparent magnitude Args: absolute_magnitude: array of absolute magnitudes (with h=1) redshift: array of redshifts colour: array of ^0.1(g-r) colour Returns: array of apparent magnitudes """ # Luminosity distance D_L = (1. + redshift) * self.cosmo.comoving_distance(redshift) return absolute_magnitude + 5*np.log10(D_L) + 25 + \ self.k(redshift,colour) def absolute_magnitude(self, apparent_magnitude, redshift, colour): """ Convert apparent magnitude to absolute magnitude Args: apparent_magnitude: array of apparent magnitudes redshift: array of redshifts colour: array of ^0.1(g-r) colour Returns: array of absolute magnitudes (with h=1) """ # Luminosity distance D_L = (1. + redshift) * self.cosmo.comoving_distance(redshift) return apparent_magnitude - 5*np.log10(D_L) - 25 - \ self.k(redshift,colour) def magnitude_faint(self, redshift): """ Convert faintest apparent magnitude (set in parameters.py) to faintest absolute magnitude Args: redshift: array of redshifts Returns: array of absolute magnitudes (with h=1) """ # convert faint apparent magnitude to absolute magnitude # for bluest and reddest galaxies arr_ones = np.ones(len(redshift)) abs_mag_blue = self.absolute_magnitude(arr_ones * par.mag_faint, redshift, arr_ones * 0) abs_mag_red = self.absolute_magnitude(arr_ones * par.mag_faint, redshift, arr_ones * 2) # find faintest absolute magnitude, add small amount to be safe mag_faint = np.maximum(abs_mag_red, abs_mag_blue) + 0.01 # avoid infinity mag_faint = np.minimum(mag_faint, -10) return mag_faint
# coding: utf-8 from cosmology import Cosmology import numpy as np import matplotlib.pyplot as plt c = Cosmology() z = np.linspace(0, 1, 10001) fig, ax = plt.subplots(1, 1, figsize=(8, 6)) ax.plot(c.z, c.r) ax.plot(z, c.z2r(z), '.') ax.set(xlabel='redshift $z$', xlim=[0, 1], ylabel='comoving distance $r$ [$h^{-1}$ Mpc]') fig.tight_layout() plt.show()