def get_sfr_z_pdf(z_max, binsize): z = np.arange(0.0, z_max, binsize) z_dz = np.arange(0.0 + binsize, z_max + binsize, binsize) v_z = cosmo.comoving_volume(z) v_z_dz = cosmo.comoving_volume(z_dz) v_dz = v_z_dz - v_z norm_v_dz = v_dz / np.nanmax(v_dz) sfr_z = lsstt.sims.calculate_SFR(z) sfr_norm = sfr_z / np.nanmax(sfr_z) volumetric_rate = norm_v_dz * sfr_norm normed_volumetric_rate = volumetric_rate / np.nanmax(volumetric_rate) return InterpolatedUnivariateSpline(z, normed_volumetric_rate)
def test_four_volume(self): self.assertAlmostEqual( Planck15.comoving_volume(2.3).value / 1e9, redshift.total_four_volume(lamb=1, analysis_time=1, max_redshift=2.3), 4, )
def measure_sfrd(stacked_object, area_deg=1.62, tsfrd=False, cosmo=cosmo): if area_deg == 1.62: print 'defaulting to uVista/COSMOS area of 1.62deg2' area_sr = area_deg * (3.1415926535 / 180.)**2 sfrd = np.zeros(np.shape(stacked_object.simstack_nuInu_array)) for i in range(stacked_object.nz): zn = stacked_object.z_nodes[i:i+2] z_suf = '{:.2f}'.format(zn[0])+'-'+'{:.2f}'.format(zn[1]) vol = cosmo.comoving_volume(zn[1]) - cosmo.comoving_volume(zn[0]) for iwv in range(stacked_object.nw): for j in range(stacked_object.nm): mn = stacked_object.m_nodes[j:j+2] m_suf = '{:.2f}'.format(mn[0])+'-'+'{:.2f}'.format(mn[1]) for p in range(stacked_object.npops): arg = clean_args('z_'+z_suf+'__m_'+m_suf+'_'+stacked_object.pops[p]) ng = len(stacked_object.bin_ids[arg]) sfr = conv_lir_to_sfr * stacked_object.simstack_flux_array[iwv,i,j,p] sfrd[iwv,i,j,p] += float(ng) / area_sr * sfr if tsfrd == True: return np.sum(np.sum(np.sum(sfrd,axis=1),axis=1),axis=1) else: return sfrd
def measure_sfrd(stacked_object, area_deg=1.62, tsfrd=False, cosmo=cosmo): if area_deg == 1.62: print 'defaulting to uVista/COSMOS area of 1.62deg2' area_sr = area_deg * (3.1415926535 / 180.)**2 sfrd = np.zeros(np.shape(stacked_object.simstack_nuInu_array)) for i in range(stacked_object.nz): zn = stacked_object.z_nodes[i:i + 2] z_suf = '{:.2f}'.format(zn[0]) + '-' + '{:.2f}'.format(zn[1]) vol = cosmo.comoving_volume(zn[1]) - cosmo.comoving_volume(zn[0]) for iwv in range(stacked_object.nw): for j in range(stacked_object.nm): mn = stacked_object.m_nodes[j:j + 2] m_suf = '{:.2f}'.format(mn[0]) + '-' + '{:.2f}'.format(mn[1]) for p in range(stacked_object.npops): arg = clean_args('z_' + z_suf + '__m_' + m_suf + '_' + stacked_object.pops[p]) ng = len(stacked_object.bin_ids[arg]) sfr = conv_lir_to_sfr * stacked_object.simstack_flux_array[ iwv, i, j, p] sfrd[iwv, i, j, p] += float(ng) / area_sr * sfr if tsfrd == True: return np.sum(np.sum(np.sum(sfrd, axis=1), axis=1), axis=1) else: return sfrd
def zint(mass, zmin, zmax, nstep=1000): z = np.linspace(zmin, zmax, nstep) integral = 0 if mass > 100: #Shitty check if mass was given as just the exponant mass = np.log(mass) for i in range(len(z) - 1): ztemp = (z[i + 1] + z[i]) / 2 print(i) integrand = lambda m: mass_function.massFunction( m, ztemp, mdef='500m', model='tinker08', q_out='dndlnM') integrated_density = log_int(integrand, mass, 20.5) #Comoving volume computed over full sky i.e. 4pi steradians. Scale accordingly comov_vol = Planck15.comoving_volume(ztemp).value integral += integrated_density * comov_vol * (z[i + 1] - z[i]) return integral
def test_limiting_case_easy(): """ This tests that the number of objects sampled by the `PowerLawRates` is equal to the number expected for a simple case with a rate given by 3.0e-5 * (h/0.7)**3, when 3.0e-5 is passed as the argument. """ rng = np.random.RandomState(1) pl = PowerLawRates(rng, sky_area=None, zlower=1.0e-8, zhigher=1.2, num_bins=200, sky_fraction=1., zbin_edges=None, alpha_rate=3.0e-5, survey_duration=1.0, cosmo=cosmo, beta_rate=1.0) vol = cosmo.comoving_volume(z=1.2).value np.testing.assert_allclose(vol * 3.0e-5 * (cosmo.h / 0.7)**3, pl.z_sample_sizes.sum(), rtol=0.001)
def schechter_LF(z, lambdaemitted, alpha, Lstar0, betaL, phistar0, betaphi, zpaper, param, fluxscale, em, filter, style=""): print("alpha = ", alpha) print("z = ", z) test = numpy.arange(30, 55, 0.01) L = (10**test) #I have two different parametrizations for Lstar and phistar; the first one is from Comparat et al 2016, and the second one is from Sobral et al 2015 if param == "first": Lstar = fluxscale * Lstar0 * ((1 + z)**betaL) print("Lstar = ", Lstar) phistar = phistar0 * ((1 + z)**betaphi) print("phistar = ", phistar) if param == "second": Lstar = 10**(0.45 * z + Lstar0) print("Lstar = ", Lstar) phistar = 10**(-0.38 * (z**2) + z + phistar0) print("phistar = ", phistar) if param == "third": answersLya = lineqLya(z=z) Lstar = answersLya[ 0] #this is linearly parametrized from Ciardullo+ 2012 print("Lstar = ", Lstar) phistar = answersLya[ 1] #this is linearly parametrized from Ciardullo+ 2012 print("phistar = ", phistar) phi = phistar * ((L / Lstar)**(alpha + 1)) * (numpy.e**(-L / Lstar)) print( "Note: Each paper uses a slightly different convention; I decided to consolidate them with the following:" ) print("using the LF equation with the alpha+1 exponent as follows: ") print("phi = phistar*((L/Lstar)**(alpha+1))*(numpy.e**(-L/Lstar))") #this deletes parts of the arrays that are so small python counts them as zero; otherwise, I would not be able to take the logarithm of the array L = L[numpy.where(phi != 0)] phi = phi[numpy.where(phi != 0)] testarray = test[numpy.where(phi != 0)] log10L = numpy.log10(L) log10phi = numpy.log10(phi) #the following calculates values I use in and plug into the lumlim function if filter == "uband": #ABmag is the coadded depth for a 5 sigma magnitude limit in this filter ABmag = 26.1 lambdalow = 305.30 #in nm lambdahigh = 408.60 #in nm if filter == "gband": #ABmag is the coadded depth for a 5 sigma magnitude limit in this filter ABmag = 27.4 lambdalow = 386.30 #in nm lambdahigh = 567.00 #in nm if filter == "rband": #ABmag is the coadded depth for a 5 sigma magnitude limit in this filter ABmag = 27.5 lambdalow = 536.90 #in nm lambdahigh = 706.00 #in nm if filter == "iband": #ABmag is the coadded depth for a 5 sigma magnitude limit in this filter ABmag = 26.8 lambdalow = 675.90 #in nm lambdahigh = 833.00 #in nm if filter == "zband": #ABmag is the coadded depth for a 5 sigma magnitude limit in this filter ABmag = 26.1 lambdalow = 802.90 #in nm lambdahigh = 938.60 #in nm if filter == "yband": #ABmag is the coadded depth for a 5 sigma magnitude limit in this filter ABmag = 24.9 lambdalow = 908.30 #in nm lambdahigh = 1099.60 #in nm #uses previously defined function to get median transmission wavelenth lambdaarray = filter_int(filter=filter) lambdacenter = lambdaarray[0] #lambdaemitted = #will be one of the three emission lines #uses nm #these are redshifts filterendlow = (lambdalow / lambdaemitted) - 1 filterendhigh = (lambdahigh / lambdaemitted) - 1 filtercenter = (lambdacenter / lambdaemitted) - 1 #I don't think I used the following at all #deltafilter = filterendhigh-filterendlow #print("for",em,"deltafilter =",deltafilter) #finds luminosity limit in center of z band center = lumlim(z=filtercenter, em=em, filter=filter) #sets up an array that I use to plot lumarray = numpy.full(15, numpy.log10(center)) yarray = numpy.arange(-10, 5, 1) figure(1) plot(log10L, log10phi, style, label=zpaper) plot(lumarray, yarray, style + "--") xlim(40, 45) ylim(-7, 0) legend(loc="upper right") #LaTeX is used with $ signs in the titles below xlabel("$\log_{10}(L [ergs/s])$") ylabel("$\log_{10}(\phi [\t{Mpc}^{-3}])$") title("Schechter Luminosity Function, " + filter) print("z = ", z, " and alpha = ", alpha, " are plotted, ") #saves image pyplot.savefig('/home/lanaeid/Desktop/fig1' + filter + '.png', bbox_inches='tight') print( "now the number density is calculated by integrating the LF using cumtrapz:" ) #cumptrapz integrates the opposite way than I need to integrate, so I flip it twice in the process phiflip = phi[::-1] phiflipint = scipy.integrate.cumtrapz(phiflip, x=testarray) num_dens = phiflipint[::-1] Lmin = numpy.delete(L, (len(L) - 1)) #shifted_Lmin = Lmin*fluxscale log10Lmin = numpy.log10(Lmin) #log10shifted_Lmin = numpy.log10(shifted_Lmin) figure(2) plot(log10Lmin, num_dens, style, label=zpaper) plot(lumarray, yarray, style + "--") legend(loc="upper right") xlim(40, 44) ylim(0, 0.03) #LaTeX is used with $ signs in the titles below xlabel("$\log_{10}(L_{min} [ergs/s])$") ylabel("$\log_{10}(\phi [\t{Mpc}^{-3}])$") title("Number Density, " + filter) #saves image pyplot.savefig('/home/lanaeid/Desktop/fig2' + filter + '.png', bbox_inches='tight') #the following finds the comoving number density above a certain detection limit (shot noise limit), #which I calculated in the previous part of the code (also shown below), where I saved the variable named center #runs through the LF code for chosen emission line #then gets number density above the luminosity limit using the center value #first, I have to shorten the phi array to contain only values above the luminosity limit #EDIT HERE #first define array of 100 evenly spaced wavelengths #use these to get an array of redshifts with which to get the comoving volume, for each of them #basically getting the thing I found below but for everything across the FWHM #uses astropy.cosmology.Planck15 to find comoving volume in shell between redshifts at each end of the z filter comovingvolmin = cosmo.comoving_volume(filterendlow) #units are in Mpc^3 comovingvolmax = cosmo.comoving_volume(filterendhigh) #units are in Mpc^3 comovingvol = comovingvolmax - comovingvolmin comovingvol = comovingvol.value print("comovingvol =", comovingvol, "Mpc^3") #shortens the array to be above the luminosity limit, then integrates to get comoving number density philim = phi[numpy.where(L > center)] testarraydos = test[numpy.where(L > center)] comovingphi = scipy.integrate.trapz(philim, x=testarraydos) print("comovingphi =", comovingphi, "Mpc^-3") #units? #finds total number of galaxies and areal number density totalnumgalaxies = comovingphi * comovingvol arealphi = totalnumgalaxies / (4 * numpy.pi) print("arealphi =", arealphi, "steradian^-1") show()
def schechter_LF(z,lambdaemitted,alpha,Lstar0,betaL,phistar0,betaphi,zpaper,param,fluxscale,em,style = ""): print("alpha = ", alpha) print("z = ", z) test = numpy.arange(30,55,0.01) L = (10**test) #I have two different parametrizations for Lstar and phistar; the first one is from Comparat et al 2016, and the second one is from Sobral et al 2015 if param == "first": Lstar = fluxscale*Lstar0*((1+z)**betaL) print("Lstar = ", Lstar) phistar = phistar0*((1+z)**betaphi) print("phistar = ", phistar) if param == "second": Lstar = 10**(0.45*z + Lstar0) print("Lstar = ", Lstar) phistar = 10**(-0.38*(z**2) + z + phistar0) print("phistar = ", phistar) if param == "third": #THIS NEEDS TO BE FIXED answersLya = lineqLya(z) Lstar = answersLya[0] #this is linearly parametrized from Ciardullo+ 2012 print("Lstar = ",Lstar) phistar = answersLya[1] #this is linearly parametrized from Ciardullo+ 2012 print("phistar = ",phistar) phi = phistar*((L/Lstar)**(alpha+1))*(numpy.e**(-L/Lstar)) print("Note: Each paper uses a slightly different convention; I decided to consolidate them with the following:") print("using the LF equation with the alpha+1 exponent as follows: ") print("phi = phistar*((L/Lstar)**(alpha+1))*(numpy.e**(-L/Lstar))") #this deletes parts of the arrays that are so small python counts them as zero; otherwise, I would not be able to take the logarithm of the array L = L[numpy.where(phi!=0)] phi = phi[numpy.where(phi!=0)] testarray = test[numpy.where(phi!=0)] log10L = numpy.log10(L) log10phi = numpy.log10(phi) #the following calculates values I use in and plug into the lumlim function lambdalow = 818.95 #in nm lambdahigh = 921.15 #in nm lambdacenter = (lambdalow+lambdahigh)/2 #in nm #NO THIS IS NOT CORRECT, FIX THIS #lambdaemitted = #will be one of the three emission lines #in nm zendlow = (lambdalow/lambdaemitted)-1 zendhigh = (lambdahigh/lambdaemitted)-1 zcenter = (lambdacenter/lambdaemitted)-1 deltaz = zendhigh-zendlow print("for",em,"deltaz =",deltaz) #finds luminosity limit in center of z band center = lumlim(z = zcenter,em = em) #why did I have it reprint out: print("luminosity limit for the center of the z band with a 5 sigma detection limit is",center,"erg/s") ? lumarray = numpy.full(15,numpy.log10(center)) yarray = numpy.arange(-10,5,1) figure(1) plot(log10L,log10phi,style,label = zpaper) plot(lumarray,yarray,style+"--") xlim(40,45) ylim(-7,0) legend(loc = "upper right") #LaTeX is used with $ signs in the titles below xlabel("$\log_{10}(L [ergs/s])$") ylabel("$\log_{10}(\phi [\t{Mpc}^{-3}])$") title("Schechter Luminosity Function") #emline+ print("z = ", z, " and alpha = ", alpha, " are plotted, ") #saves image #plot.savefig('/home/Desktop/fig1.png',bbox_inches = 'tight') print("now the number density is calculated by integrating the LF using cumtrapz:") #cumptrapz integrates the opposite way than I need to integrate, so I flip it twice in the process phiflip = phi[::-1] phiflipint = scipy.integrate.cumtrapz(phiflip,x=testarray) num_dens = phiflipint[::-1] Lmin = numpy.delete(L,(len(L)-1)) #shifted_Lmin = Lmin*fluxscale log10Lmin = numpy.log10(Lmin) #log10shifted_Lmin = numpy.log10(shifted_Lmin) figure(2) plot(log10Lmin,num_dens,style,label = zpaper) #show() plot(lumarray,yarray,style+"--") #show() legend(loc = "upper right") xlim(40,44) ylim(0,0.03) #LaTeX is used with $ signs in the titles below xlabel("$\log_{10}(L_{min} [ergs/s])$") ylabel("$\log_{10}(\phi [\t{Mpc}^{-3}])$") title("Number Density") #emline+ #saves image #plot.savefig('/home/Desktop/fig2.png',bbox_inches = 'tight') #the following finds the comoving number density above a certain detection limit (shot noise limit), #which I calculated in the previous part of the code (also shown below), where I saved the variable named center #runs through the LF code for chosen emission line #then gets number density above the luminosity limit using the center value #first, I have to shorten the phi array to contain only values above the luminosity limit #uses astropy.cosmology.Planck15 to find comoving volume in shell between redshifts at each end of the z filter comovingvolmin = cosmo.comoving_volume(zendlow) #units are in Mpc^3 comovingvolmax = cosmo.comoving_volume(zendhigh) #units are in Mpc^3 comovingvol = comovingvolmax-comovingvolmin comovingvol = comovingvol.value print("comovingvol =",comovingvol,"Mpc^3") #shortens the array to be above the luminosity limit, then integrates to get comoving number density philim = phi[numpy.where(L>center)] testarraydos = test[numpy.where(L>center)] comovingphi = scipy.integrate.trapz(philim,x=testarraydos) print("comovingphi =",comovingphi,"Mpc^-3") #units? #finds total number of galaxies and areal number density totalnumgalaxies = comovingphi*comovingvol arealphi = totalnumgalaxies/(4*numpy.pi) print("arealphi =",arealphi,"steradian^-1")
import time import matplotlib.pyplot as plt names = ['z', 'm1', 'm2'] data = np.genfromtxt( '../../../simulation/data_ready_june_snap_lim_1.txt', names=True, dtype=None) z_coal = data['redshift'] dz = 0.001 zs_i = np.arange(0.0, 8.0+dz, dz) zs_i_plus_1 = zs_i + dz zs = zs_i + dz/2. # TODO: check units dVc_dz = (cosmo.comoving_volume(zs_i_plus_1).value - cosmo.comoving_volume(zs_i).value)/dz dz_dt = dz/(cosmo.age(zs_i_plus_1).value*1e9 - cosmo.age(zs_i).value*1e9) weights = np.abs(np.interp(z_coal, zs, dz_dt*dVc_dz/(1+zs))) kde = KDEResample( np.asarray([data['redshift'], data['mass_new_prev_in'], data['mass_new_prev_out']]).T, weights, names) kde.make_kernel() st = time.time() gc = GenerateCatalog(0.8, 100.0, kde, num_catalogs=100000) cats = gc.make_catalogs() print(time.time() - st) plt.hist(