def __init__(self, vlim, sigma_v, Muv, Muv_err, z, fix_bg, fesc_bounds=[0.,1.], C_bounds=[1, 10.], sigma0=1., alpha_bounds=[-2.5,-1.], beta_bounds=[-3,-1], gamma_bg_bounds=[0.,20.], gamma_bg_rescale=1e-12, log_C=False, log_gamma_bg=False): """ Default gamma_bg is * 1e-12 s^-1, if log, it's not """ # input parameters self.vlim = vlim self.sigma_v = sigma_v self.Muv = Muv self.Muv_err = Muv_err self.z = z self.fix_bg = fix_bg self.gamma_bg_rescale = gamma_bg_rescale if self.fix_bg: self.ndim = 5 else: self.ndim = 6 # params bounds self.prior_bounds = {'fesc':fesc_bounds, 'C':C_bounds, 'alpha_s':alpha_bounds, 'beta':beta_bounds, 'gamma_bg':gamma_bg_bounds, 'sigma0':sigma0} self.R_obs = np.abs(self.vlim / Planck15.H(self.z)).to(u.Mpc) self.R_obs_err = np.abs(self.sigma_v / Planck15.H(self.z)).to(u.Mpc) # labels self.labels = [r'$f_\mathrm{esc}$', r'$C_\mathrm{HII}$', r'$\Delta$', r'$\alpha$', r'$\beta$', r'$\Gamma_\mathrm{bg} [10^{-12} \mathrm{s}^{-1}]$'] # Use log (gamma s^-1)? self.log_gamma_bg = log_gamma_bg if self.log_gamma_bg: self.labels[-1] = r'$\log_{10} \Gamma_\mathrm{bg} [\mathrm{s}^{-1}]$' # Use log C? self.log_C = log_C if self.log_C: self.prior_bounds['C'] = [np.log10(C_bounds[0]), np.log10(C_bounds[1])] self.labels[1] = r'$\log_{10} C_\mathrm{HII}$' print('Prior bounds:',self.prior_bounds) return
def hmp(self, z=0): """Generating halo mass profiles Parameters ---------- z : float Redshift of the snapshot """ rhocrit = Planck15.critical_density(z).to(units.Msun / units.kpc**3) \ / (Planck15.H(z) / 100) for i in range(len(self.params)): _input = self.params[i] halos = _input['rockstar'].binnedhalos[_input['bin']] _input['hmp'] = MyHMP( halos, _input['gadget'].data, float(_input['rockstar'].header['Particle_mass'][0])) rmin = _input['rockstar'].header['Softening_length'] / 2.0 rmax = 2 * np.max(halos['rvir']) _input['rockstar'].binnedhalos['mean_rvir'] = sum(halos['rvir']) \ / len(halos['rvir']) rbins = np.logspace(np.log10(rmin), np.log10(rmax), num=50, base=10) _input['hmp'].hmp(rbins, rhocrit.value)
def h_ringdown(m_final=100, a_final=0.69, q=1, chi_p=0, chi_m=0, inclination=0, dist=500, z=0, vkick=0, phi0=0, theta=0, phi=0, psi=0, df=0.1, fmin=5, fmax=2000, l=None, m=None): hp, hx, freqs = hp_hx_ringdown(m_final, a_final, q, chi_p, chi_m, inclination, dist, phi0, df, fmin, fmax, l, m) fp, fx = pattern_functions(theta, phi, psi) vkick = add_default_units(vkick, u.km / u.s) dist = add_default_units(dist, u.Mpc) if z != 0: fracD = 1 + (vkick / c.c * (1 - (1 + z)**2 / (dist * cosmo.H(z) / c.c))).decompose() else: fracD = 1 return (hp * fp + hx * fx) / fracD, freqs
def pg(u,k,z, zp,ap_perp,ap_para,fps8,gamma,b1s8,b2s8,s8,vp,Nshot): x = (cosmo.comoving_distance(z)/cosmo.comoving_distance(zp)).value-1 az_perp = ap_perp + (ap_para-ap_perp)*x az_para = ap_para + 2*(ap_para-ap_perp)*x b1 = b1s8/s8 + 0.29*((1+z)**2-(1+zp)**2) b2 = b2s8/s8 omega_ratio = ((1+z)/(1+zp))**3 * (az_para/ap_para)**2 * ((cosmo.H(zp)/cosmo.H(z)).value)**2 fz = fps8/s8*omega_ratio**gamma vz = (cosmo.H(zp)/cosmo.H(z)).value * az_para/ap_para * (1+z)/(1+zp) * vp bs2 = -4/7*(b1-1) b3nl = 32/315*(b1-1) pgdd = b1**2*pdd(k) + 2*b1*b2*pb2d(k) + 2*bs2*b1*pbs2d(k) + 2*b3nl*pb3nl(k) + b2**2*pb22(k) pgdv = b1*pdv(k) + b2*pb2v(k) + bs2*pbs2d(k) + b3nl*pb3nl(k) dfog = (1+(k*u*vz)**2/2)**(-2) par1 = b1**3 par2 = [] for m,n in itertools.product(range(3),range(3)): if A[m,n] is not None: par2.append(u**(2*m)*(fz/b1)**n*A[m,n](k)) AA = par1*np.sum(par2,axis=0) par1 = b1**4 par2 = [] for m,a,b in itertools.product(range(4),range(2),range(2)): if B[m,a,b] is not None: par2.append(u**(2*m)*(-fz/b1)**(a+b)*B[m,a,b](k)) BB = par1*np.sum(par2,axis=0) pgz = dfog * (pgdd + 2*fz*u**2*pgdv + fz**2*u**4*pvv(k) + AA + BB) return pgz
def optical_depth_Weinberg97(z, n_HI): """ Lya optical depth from https://ui.adsabs.harvard.edu/abs/1997ApJ...490..564W/abstract Eqn 3 for uniform IGM tau = πe^2/(m_e c) * f_alpha lambda_alpha * n_HI/H(z) """ tau = 1.34e-17*u.cm**3/u.s * Planck15.H(z).to(1./u.s) * n_HI return tau.value
def DZ_int(self,z=[0],cosmo=None): #linear growth factor.. full integral.. eq 63 in Lahav and suto if not cosmo: cosmo=self.cosmo def intf(z): return (1+z)/(cosmo.H(z).value)**3 j=0 Dz=np.zeros_like(z,dtype='float32') for i in z: Dz[j]=cosmo.H(i).value*scipy_int1d(intf,i,np.inf,epsrel=1.e-6,epsabs=1.e-6)[0] j=j+1 Dz*=(2.5*cosmo.Om0*cosmo.H0.value**2) return Dz/Dz[0]
def CHI(q, y, z): z = np.array([ z, ]).flatten() zi = np.mean(z) r = cosmo.comoving_distance(zi) * cosmo.h rnu = const.c.to('km/s') * (1 + zi)**2 / cosmo.H(zi) * cosmo.h k_para = y / rnu.value k_perp = q / r.value return Pk2D_HI(k_para, k_perp, zi)[0]
def Pk2D_N(k_para, k_perp, z, params, bcast=True, return_beam=False, max_beam=False): z = np.array(z).flatten() z0 = np.mean(z) rr = (cosmo.comoving_distance(z0) * cosmo.h).value rv = (const.c.to('km/s') * (1 + z0)**2. / cosmo.H(z0) * cosmo.h).value q = k_perp * rr y = k_para * rv freq0 = 1420. / (1. + z.max()) S = params['S_area'] S = S * (np.pi / 180.)**2. r0 = (cosmo.comoving_distance(z0) * cosmo.h).value rmin = (cosmo.comoving_distance(z.min()) * cosmo.h).value rmax = (cosmo.comoving_distance(z.max()) * cosmo.h).value dr = rmax - rmin Vbin = S * (r0**2) * dr #k_area = 2.* np.pi / (r0**2 * S)**0.5 # min k_perp _r = CN(q, y, freq0, params, bcast=bcast, return_beam=return_beam, max_beam=max_beam) if return_beam: pkn, B = _r #B = B * np.exp(0.5 * k_perp**2/k_area**2) pkn = pkn * Vbin return pkn, Vbin, B else: pkn = _r pkn = pkn * Vbin return pkn, Vbin
def writeDists(o): """ Writes bias and dn/dz files for redmagic like sample. Eli Rykoff says Density is ~constant comoving density 1.5e-3 h^3 Mpc^-3, sigma_z/(1+z) ~0.01, and bias is 2-2.5ish. """ zmin = 0.01 zmax = 1.2 Nz = 1000 rho_comoving = 1.5e-3 #Nz shaping zshape = 1.0 d = o.outpath fn = open(d + "/Nz.txt", 'w') fb = open(d + "/bz.txt", 'w') pi = np.pi for z in np.linspace(zmin, zmax, Nz): fb.write("%g %g\n" % (z, 2.2)) ## for density, need to convert Mpc/h into n/sqdeg/dz ## c over H(z) for Mpc/h units coHz = (const.c / co.H(z)).to(u.Mpc).value * co.h # radius in Mpc/h r = co.comoving_distance(z).to("Mpc").value * co.h #volume of 1sq * dz # 4pir^2 * (1deg/rad)**2 * dr/dz # hMpc^3 per dz per 1sqd vrat = r**2 * (pi / 180.)**2 * coHz dens = rho_comoving * vrat ## shape distribution to avoid sharep cut if (z > zshape): sup = (z - zshape) / (zmax - zshape) dens *= np.exp(-10 * sup**2) fn.write("%g %g\n" % (z, dens))
def comoving_distance_from_source_Mpc(z_2, z_1): """ COMOVING distance between z_1 and z_2 """ R_com = (z_1 - z_2) * (const.c / Planck15.H(z=z_1)).to(u.Mpc) return R_com
def dt_dz(z): return 1. / ((1. + z) * Planck15.H(z))
def z_at_proper_distance(R_p, z_1=7.): R_H = (const.c / Planck15.H(z=z_1)).to(u.Mpc) R_com = R_p * (1 + z_1) return z_1 - R_com / R_H
def load_peakpatch_catalogue(halo_info, filetype='.npz', saveHalos=False, saveFolder='/outputs/'): """ Load peak patch halo catalogue into halos class and cosmology into cosmo class Slightly modified to work with the lim functions, cosmo class split into separate function When save=True, the function will save the Mcen, Msat, cen_pos, sat_pos output to the saveFolder directory. Default filetype = '.npz' Can take filetype = '.h5' Returns ------- halos : class Contains all halo information (position, redshift, etc..) """ # These are the directories from when saveHalos=True. Mcen_file = saveFolder + 'Mcen.dat' Msat_file = saveFolder + 'Msat.dat' cen_pos_file = saveFolder + 'cen_pos.dat' sat_pos_file = saveFolder + 'sat_pos.dat' halos = empty_table() # creates empty class to put any halo info into if filetype=='.h5': # Martine's catalogues use these from astropy.cosmology import Planck15 as cosmo15 h = cosmo15.H(0).value/100 cen_x_fov = 0. # set zero for now cen_y_fov = 0. if saveHalos: print('Saving mass values...') mcen = halo_info['mass_cen'].value rm_cenmass = (mcen > 2e13/h) mcen = mcen[rm_cenmass] xcen = (halo_info['xpos_cen'].value)[rm_cenmass] ycen = (halo_info['ypos_cen'].value)[rm_cenmass] zcen = (halo_info['zpos_cen'].value)[rm_cenmass] with open(Mcen_file, 'w+') as mc: np.savetxt(mc, mcen) with open(cen_pos_file, 'w+') as cp: np.savetxt(cp, (xcen,ycen,zcen)) print('Saving position values...') msat = halo_info['mass_sat'].value rm_satmass = (msat > 2e13/h) msat = msat[rm_satmass] xsat = (halo_info['xpos_sat'].value)[rm_satmass] ysat = (halo_info['ypos_sat'].value)[rm_satmass] zsat = (halo_info['zpos_sat'].value)[rm_satmass] with open(Msat_file, 'w+') as ms: np.savetxt(ms, msat) with open(sat_pos_file, 'w+') as sp: np.savetxt(sp, (xsat,ysat,zsat)) else: try: print('Loading mass files... (takes 3 minutes)') mcen = np.loadtxt(Mcen_file) msat = np.loadtxt(Msat_file) print('Loading position files...') xcen, ycen, zcen = np.loadtxt(cen_pos_file)[0], np.loadtxt(cen_pos_file)[1], np.loadtxt(cen_pos_file)[2] xsat, ysat, zsat = np.loadtxt(sat_pos_file)[0], np.loadtxt(sat_pos_file)[1], np.loadtxt(sat_pos_file)[2] except IOError: print('Need to set saveHalo=True the first run in order to use saveHalo=False subsequently.') halos.Mcen = mcen halos.x_pos_cen = xcen halos.y_pos_cen = ycen halos.z_pos_cen = zcen halos.Msat = msat halos.x_pos_sat = xsat halos.y_pos_sat = ysat halos.z_pos_sat = zsat # both centrals and satellites together --- from here, it doesn't take too long halos.M = np.append(mcen, msat) halos.x_pos = np.append(xcen, xsat) halos.y_pos = np.append(ycen, ysat) halos.z_pos = np.append(zcen, zsat) halos.chi_cen = np.sqrt(halos.x_pos_cen**2+halos.y_pos_cen**2+halos.z_pos_cen**2) halos.chi_sat = np.sqrt(halos.x_pos_sat**2+halos.y_pos_sat**2+halos.z_pos_sat**2) halos.chi = np.append(halos.chi_cen, halos.chi_sat) # manually calculate redshift - taken straight from tools.py chi_to_redshift(chi, cosmo) zinterp = np.linspace(0,6.5,10000) dz = zinterp[1]-zinterp[0] chiinterp = np.cumsum(drdz(zinterp,cosmo15.h,cosmo15.Om0) * dz) chiinterp -= chiinterp[0] z_of_chi = scipy.interpolate.interp1d(chiinterp,zinterp) halos.redshift_cen = z_of_chi(halos.chi_cen) halos.redshift_sat = z_of_chi(halos.chi_sat) halos.redshift = z_of_chi(halos.chi) halos.nhalo_cen = len(halos.Mcen) halos.nhalo_sat = len(halos.Msat) halos.nhalo = len(halos.M) halos.ra_cen = np.arctan2(-halos.x_pos_cen,halos.z_pos_cen)*180./np.pi - cen_x_fov halos.ra_sat = np.arctan2(-halos.x_pos_sat,halos.z_pos_sat)*180./np.pi - cen_x_fov halos.ra = np.arctan2(-halos.x_pos,halos.z_pos)*180./np.pi - cen_x_fov halos.dec_cen = np.arcsin( halos.y_pos_cen/halos.chi_cen )*180./np.pi - cen_y_fov halos.dec_sat = np.arcsin( halos.y_pos_sat/halos.chi_sat )*180./np.pi - cen_y_fov halos.dec = np.arcsin( halos.y_pos/halos.chi )*180./np.pi - cen_y_fov # Using 'ns' and 'sigma8' the same as George's 'cosmo_header' params_dict = {'h': h, 'sigma8': 0.82, 'Omega_M': cosmo15.Om0, 'Omega_L': cosmo15.Ode0, 'Omega_B': cosmo15.Ob0, 'ns': 0.96} # George's 'cosmo_header', in case I need to manually set these values later: # params_dict = {'h': 0.7, 'sigma8': 0.82, 'Omega_M': 0.286, 'Omega_L': 0.714, 'Omega_B': 0.047, 'ns': 0.96} else: print('Loading .npz catalogues...') params_dict = halo_info['cosmo_header'][()] if debug.verbose: print("\thalo catalogue contains:\n\t\t", halo_info.files) #.npz version cen_x_fov = params_dict.get('cen_x_fov', 0.) #if the halo catalogue is not centered along the z axis cen_y_fov = params_dict.get('cen_y_fov', 0.) #if the halo catalogue is not centered along the z axis halos.M = halo_info['M'] # halo mass in Msun halos.x_pos = halo_info['x'] # halo x position in comoving Mpc halos.y_pos = halo_info['y'] # halo y position in comoving Mpc halos.z_pos = halo_info['z'] # halo z position in comoving Mpc halos.vx = halo_info['vx'] # halo x velocity in km/s halos.vy = halo_info['vy'] # halo y velocity in km/s halos.vz = halo_info['vz'] # halo z velocity in km/s halos.redshift = halo_info['zhalo'] # observed redshift incl velocities halos.zformation = halo_info['zform'] # formation redshift of halo halos.chi = np.sqrt(halos.x_pos**2+halos.y_pos**2+halos.z_pos**2) halos.nhalo = len(halos.M) halos.ra = np.arctan2(-halos.x_pos,halos.z_pos)*180./np.pi - cen_x_fov halos.dec = np.arcsin( halos.y_pos/halos.chi )*180./np.pi - cen_y_fov assert np.max(halos.M) < 1.e17, "Halos seem too massive" # assert np.max(halos.redshift) < 4., "need to change max redshift interpolation in tools.py" assert np.max(halos.redshift) < 6.5, "need to change max redshift interpolation in tools.py" # changed for George's z=4.77-6.21 sim data because of error in calling m.maps (May 17) - Clara if debug.verbose: print('\n\t%d halos loaded' % halos.nhalo) return halos
from cosmology import * from astropy.io import fits from astropy.cosmology import Planck15 as cosmo, z_at_value import astropy.units as u import os slice_width = 100 test = False h = cosmo.H(0).value/100 frac_cens = 0.5 def xyz_to_ang_z(x,y,z): chi = np.sqrt(x**2+y**2+z**2) # Mpc redshift = zofchi(chi) theta, phi = hp.vec2ang(np.column_stack((x,y,z))) # in radians return (theta,phi,redshift)
def intf(z): return (1+z)/(cosmo.H(z).value)**3
coord_fcl = [] df_fcl = [] df_fcl_r200 = [] BCG_vel = [] mean_vel = [] mean_vel_mass = [] iicc = 0 cluster_names = [] for ic, shalo in enumerate(clusters_list): file_name = shalo #if '_1_z' not in file_name: continue p1 = Cluster(file_path, file_name, tracer=tracers) setattr(p1, 'redshift', redshifts[ired]) hz = cosmo.H(p1.redshift).value / 100. nmem_cl = p1.tot_members200 nmem_cl_mass = len(p1.members_velocities[np.logical_and( p1.dist3d <= p1.R200, p1.M_stars_mem >= star_mass_lim), 0]) #nmem_cl_mass = len(p1.M_stars_mem[np.logical_and(p1.dist3d <= p1.R200, p1.M_stars_mem >= star_mass_lim)]) if nmem_cl_mass < ngal_lim: continue ## NON COMULATIVE if non_comulative: non_com_str = '_non_com' if np.log10(p1.M200 / cosmo.h * hz) < h_mass_lims[i_h_mass_lim] or np.log10( p1.M200 / cosmo.h * hz) >= h_mass_lims[i_h_mass_lim] + 0.2:
def sSFR_cut(z): tmp = 1/Planck15.H(z).decompose() return (1.0/(3*tmp.to(u.yr))).value
task_ID = int(os.environ['SLURM_ARRAY_TASK_ID']) print('Task ID =', task_ID) dims = 2048 # dimensions of density array verbose = False DEBUG = 2 # Calculate z for range of comoving distances z = np.zeros(3000) d_c = np.zeros(3000) H = np.zeros(3000) for d in range(1, 3000): d_c[d] = d z[d] = z_at_value(cosmo.comoving_distance, d * uni.Mpc) H[d] = cosmo.H(z[d]).value # create spine for quick lookup d2z = spl(d_c, z) z2H = spl(z, H, s=0) def read_header(snap): snapshot_fname = '/cosma6/data/dp004/dc-smit4/Daemmerung/Planck2013-Npart_2048_Box_3000-Fiducial/run1/snapdir_{0:03d}/Planck2013-L3000-N2048-Fiducial_{0:03d}.0'.format( snap) return readgadget.header(snapshot_fname) # read headers for all snapshots to get redshifts snaps = 24 zz = np.zeros(snaps)
#z1s, z2s, cthetas = z1s[fsel], z2s[fsel], cthetas[fsel] #snnames1, snnames2, dangles = snnames1[fsel], snnames2[fsel], dangles[fsel] #arr = arr.transpose()[fsel].transpose() #Cijint = CovMatCalculator(z1s, z2s, cthetas) #Cijint = np.genfromtxt('Cijintsavedlocaljustsome.txt', delimiter='|') Cijint = np.genfromtxt('CijIntegrals/Cijintsavedall.txt', delimiter='|') Cijint = Cijint / 2. / (np.pi**2. * 0.68**2.) Sij = 4.7152924252903468 * ((1. + z1s)**2.) * ( (1. + z2s)** 2.) * Cijint * dDzbydtauofz(z2s) * dDzbydtauofz(z1s) * MPctoKM**2. / ( cosmo.H(z1s) * cosmo.H(z2s) * cosmo.luminosity_distance(z1s) * cosmo.luminosity_distance(z2s)).value #Hui and Greene definition follows Cij = 4.7152924252903468 * ( 1. - (1 + z1s)**2. * SpeedOfLight / (cosmo.H(z1s) * cosmo.luminosity_distance(z1s)).value) * ( 1. - (1 + z2s)**2. * SpeedOfLight / (cosmo.H(z2s) * cosmo.luminosity_distance(z2s)).value ) * Cijint * MPctoKM**2. * dDzbydtauofz(z2s) * dDzbydtauofz( z1s) / SpeedOfLight**2. Copmeans, MWmeans, JLACov, CopEmeans, MWEmeans, CopSDs, MWSDs = arr[0], arr[ 1], arr[2], arr[3], arr[4], arr[5], arr[6] Copmeans = Copmeans * LinGrowthFactor(z1s) * LinGrowthFactor(
''' fig = plt.figure(figsize=(7,7)) axis = fig.add_subplot(1,1,1) axis.plot(T, saha(T), 'g', linewidth = 1.5) axis.set_xlabel('Temperature (K)', fontsize = 10) axis.set_ylabel('Saha Equation', fontsize = 10) axis.set_title('Saha Equation as a Function of Temperature', fontsize = 20) plt.show() ''' #Part 1b H_0 = (p15.H(0)).to('1/yr').value #def Friedman(a): # Or = 9.03 * 10**-5 # Om = 0.306 # Ol = 0.692 # FrEq = 1/(H_0*(Or*a**-2 + Om*a**-1 + Ol*a**2)**(1/2)) # return FrEq # #a = np.linspace(1e-3, 1e-4, 100) #t_space = np.array([]) ############################################################################### Or = 9.03e-5
def horizon_line(self, kperp, z): return kperp * Planck15.comoving_distance(z) * Planck15.H( z) / cnst.c / (1 + z)