def vc(z): ''' dv/dz to impose uniformity in redshift ''' cosmo = {'omega_M_0':0.3, 'omega_lambda_0':0.7, 'omega_k_0':0.0, 'h':1.0} return cd.comoving_volume(z,**cosmo)
def tot_num_src(redshift_evolution, cosmology, zmax, density): integrand = lambda z: redshift_evolution(z) * \ diff_comoving_volume(z, **cosmology) norm = 4 * np.pi * scipy.integrate.quad(integrand, 0, zmax)[0] area = 4 * np.pi * scipy.integrate.quad(integrand, 0, 0.01)[0] vlocal = comoving_volume(0.01, **cosmology) Ntotal = density * vlocal / (area / norm) return Ntotal, norm
def test_figure5(): """Plot Hogg fig. 5: The dimensionless comoving volume element (1/DH)^3(dVC/dz). The three curves are for the three world models, (omega_M, omega_lambda) = (1, 0), solid; (0.05, 0), dotted; and (0.2, 0.8), dashed. """ z = numpy.arange(0, 5.05, 0.05) cosmo = {} cosmo['omega_M_0'] = numpy.array([[1.0], [0.05], [0.2]]) cosmo['omega_lambda_0'] = numpy.array([[0.0], [0.0], [0.8]]) cosmo['h'] = 0.5 cd.set_omega_k_0(cosmo) linestyle = ['-', ':', '--'] dh = cd.hubble_distance_z(0, **cosmo) dVc = cd.diff_comoving_volume(z, **cosmo) dVc_normed = dVc / (dh**3.) Vc = cd.comoving_volume(z, **cosmo) dz = z[1:] - z[:-1] dVc_numerical = (Vc[:, 1:] - Vc[:, :-1]) / dz / (4. * numpy.pi) dVc_numerical_normed = dVc_numerical / (dh**3.) pylab.figure(figsize=(6, 6)) for i in range(len(linestyle)): pylab.plot(z, dVc_normed[i], ls=linestyle[i], lw=2.) pylab.plot(z[:-1], dVc_numerical_normed[i], ls=linestyle[i], c='k', alpha=0.1) pylab.xlim(0, 5) pylab.ylim(0, 1.1) pylab.xlabel("redshift z") pylab.ylabel(r"comoving volume element $[1/D_H^3]$ $dV_c/dz/d\Omega$") pylab.title("compare to " + inspect.stack()[0][3].replace('test_', '') + " (astro-ph/9905116v4)")
def test_figure5(): """Plot Hogg fig. 5: The dimensionless comoving volume element (1/DH)^3(dVC/dz). The three curves are for the three world models, (omega_M, omega_lambda) = (1, 0), solid; (0.05, 0), dotted; and (0.2, 0.8), dashed. """ z = numpy.arange(0, 5.05, 0.05) cosmo = {} cosmo['omega_M_0'] = numpy.array([[1.0],[0.05],[0.2]]) cosmo['omega_lambda_0'] = numpy.array([[0.0],[0.0],[0.8]]) cosmo['h'] = 0.5 cd.set_omega_k_0(cosmo) linestyle = ['-', ':', '--'] dh = cd.hubble_distance_z(0, **cosmo) dVc = cd.diff_comoving_volume(z, **cosmo) dVc_normed = dVc/(dh**3.) Vc = cd.comoving_volume(z, **cosmo) dz = z[1:] - z[:-1] dVc_numerical = (Vc[:,1:] - Vc[:,:-1])/dz/(4. * numpy.pi) dVc_numerical_normed = dVc_numerical/(dh**3.) pylab.figure(figsize=(6,6)) for i in range(len(linestyle)): pylab.plot(z, dVc_normed[i], ls=linestyle[i], lw=2.) pylab.plot(z[:-1], dVc_numerical_normed[i], ls=linestyle[i], c='k', alpha=0.1) pylab.xlim(0,5) pylab.ylim(0,1.1) pylab.xlabel("redshift z") pylab.ylabel(r"comoving volume element $[1/D_H^3]$ $dV_c/dz/d\Omega$") pylab.title("compare to " + inspect.stack()[0][3].replace('test_', '') + " (astro-ph/9905116v4)")
O_l, O_m, O_r, O_k, h = 0.7, 0.3, 0.0, 0.0, 0.7 # Cosmological parameters cosmo = {'omega_k_0': O_k, 'omega_M_0': O_m, 'omega_lambda_0': O_l, 'h': h} Dist = [] for i in range(0, no_zsteps): for j in range(0, no_Lsteps): # Define params zmin = zstart + i * zstep zmax = zstart + (i + 1) * zstep z = zmin + 0.5 * (zmax - zmin) # Effective z to draw LF from Lmin = Lstart * Lmult**(j) Lmax = Lstart * Lmult**(j + 1) # Compute comoving volume in Mpc-3 dV = (comoving_volume(zmax, **cosmo) - comoving_volume(zmin, **cosmo)) * (Tel_Area / 41253.) # Mpc3 # Get Phi in Mpc-3 alpha, logLStar, logPhiStar = LF_Data.retrieve_LF(z, line) LStar, PhiStar = 10.**(logLStar), 10.**(logPhiStar) n = scipy.integrate.quad( lambda L: schechterL(L, PhiStar, alpha, LStar), Lmin, Lmax)[0] # Number = number density * volume N = n * dV # Compute flux DL = luminosity_distance(z, **cosmo) # In MPc DL = DL * (10**6. * pc) * 10**2. # in cm
zbins=[zbin1,zbin2,zbin3,zbin4,zbin5,zbin6,zbin7,zbin8,zbin9,zbin10] area=(max(rag)-min(rag))*(max(decg)-min(decg)) #calculate background density in each bin sum_gals=[] volume=[] globaldensity=[] for i in range(0,len(zbins)): unique_id=unique_galid[np.where((zgtemp>zmin+(i*step))&(zgtemp<=zmin+(i+1)*step))] sumg=unique_id.size sum_gals.append(sumg) vol=cd.comoving_volume(zmin+((i+1)*step),**cosmo)-cd.comoving_volume(zmin+(i*step),**cosmo) vol=vol*(4*np.pi/41253)*area volume.append(vol) den=sumg/vol globaldensity.append(den) ###########CALCULATING NGALS PER CLUSTER############# print print 'matching galaxies within test radii' #get cluster centers etc. central_ra=rac central_dec=decc central_z=z cluster_id=cid
def find_horizon_range(m1, m2, network, asdfile, pwfile, approx=ls.IMRPhenomD): fmin = 1. fref = 1. df = 1e-2 ra, dec, psi, iota = genfromtxt('../data/horizon_coord_' + pwfile + '.txt', unpack=True) psdinterp_dict = {} minimum_freq = zeros(size(network)) maximum_freq = zeros(size(network)) for detector in range(0, size(network)): input_freq, strain = loadtxt(asdfile[detector], unpack=True, usecols=[0, 1]) minimum_freq[detector] = maximum(min(input_freq), fmin) maximum_freq[detector] = minimum(max(input_freq), 5000.) psdinterp_dict[network[detector]] = interp1d(input_freq, strain**2) #initial guess of horizon redshift and luminosity distance z0 = 0.1 input_dist = cd.luminosity_distance(z0, **cosmo) hplus_tilda, hcross_tilda, freqs = get_htildas((1. + z0) * m1, (1. + z0) * m2, input_dist, iota=iota, fmin=fmin, fref=fref, df=df, approx=approx) fsel = list() psd_interp = list() for detector in range(0, size(network)): fsel.append( logical_and(freqs > minimum_freq[detector], freqs < maximum_freq[detector])) psd_interp.append(psdinterp_dict[network[detector]]( freqs[fsel[detector]])) input_snr = compute_horizonSNR(hplus_tilda, hcross_tilda, network, ra, dec, psi, psd_interp, fsel, df) input_redshift = z0 guess_snr = 0 njump = 0 #evaluate the horizon recursively while abs( guess_snr - snr_th ) > snr_th * 0.001 and njump < 10: #require the error within 0.1% try: guess_redshift, guess_dist = horizon_dist_eval( input_dist, input_snr, input_redshift) #horizon guess based on the old SNR hplus_tilda, hcross_tilda, freqs = get_htildas( (1. + guess_redshift) * m1, (1. + guess_redshift) * m2, guess_dist, iota=iota, fmin=fmin, fref=fref, df=df, approx=approx) except: njump = 10 print "Will try interpolation." fsel = list() psd_interp = list() for detector in range(0, size(network)): fsel.append( logical_and(freqs > minimum_freq[detector], freqs < maximum_freq[detector])) psd_interp.append(psdinterp_dict[network[detector]]( freqs[fsel[detector]])) guess_snr = compute_horizonSNR(hplus_tilda, hcross_tilda, network, ra, dec, psi, psd_interp, fsel, df) #calculate the new SNR input_snr = guess_snr input_redshift = guess_redshift input_dist = guess_dist njump += 1 horizon_redshift = guess_redshift #at high redshift the recursive jumps lead to too big a jump for each step, and the recursive loop converge slowly. #so I interpolate the z-SNR curve directly. if njump >= 10: print "Recursive search for the horizon failed. Interpolation instead." try: interp_z = linspace(0.001, 100, 200) interp_snr = zeros(size(interp_z)) for i in range(0, size(interp_z)): hplus_tilda, hcross_tilda, freqs = get_htildas( (1. + interp_z[i]) * m1, (1. + interp_z[i]) * m2, cd.luminosity_distance(interp_z[i], **cosmo), iota=iota, fmin=fmin, fref=fref, df=df, approx=approx) fsel = list() psd_interp = list() for detector in range(0, size(network)): fsel.append( logical_and(freqs > minimum_freq[detector], freqs < maximum_freq[detector])) psd_interp.append(psdinterp_dict[network[detector]]( freqs[fsel[detector]])) interp_snr[i] = compute_horizonSNR(hplus_tilda, hcross_tilda, network, ra, dec, psi, psd_interp, fsel, df) interpolate_snr = interp1d(interp_snr[::-1], interp_z[::-1]) horizon_redshift = interpolate_snr(snr_th) except RuntimeError: #If the sources lie outside the given interpolating redshift the sources can not be observe, so I cut down the interpolation range. print "some of the SNR at the interpolated redshifts cannot be calculated." interpolate_snr = interp1d(interp_snr[::-1], interp_z[::-1]) horizon_redshift = interpolate_snr(snr_th) except ValueError: #horizon outside the interpolated redshifts. Can potentially modify the interpolation range, but we basically can not observe the type of source or the source has to be catastrophically close. print "Horizon further than z=100 or less than z=0.001. Need to modify the interpolated redshift range." return #sampled universal antenna power pattern for code sped up w_sample, P_sample = genfromtxt('../data/pw_' + pwfile + '.txt', unpack=True) P = interp1d(w_sample, P_sample, bounds_error=False, fill_value=0.0) n_zstep = 200 z, dz = linspace(horizon_redshift, 0, n_zstep, endpoint=False, retstep=True) dz = abs(dz) unit_volume = zeros(size(z)) compensate_detect_frac = zeros(size(z)) for i in range(0, size(z)): hplus_tilda, hcross_tilda, freqs = get_htildas( (1. + z[i]) * m1, (1. + z[i]) * m2, cd.luminosity_distance(z[i], **cosmo), iota=iota, fmin=fmin, fref=fref, df=df, approx=approx) for detector in range(0, size(network)): fsel.append( logical_and(freqs > minimum_freq[detector], freqs < maximum_freq[detector])) psd_interp.append(psdinterp_dict[network[detector]]( freqs[fsel[detector]])) optsnr_z = compute_horizonSNR(hplus_tilda, hcross_tilda, network, ra, dec, psi, psd_interp, fsel, df) w = snr_th / optsnr_z compensate_detect_frac[i] = P(w) unit_volume[i] = (cd.comoving_volume(z[i] + dz / 2., **cosmo) - cd.comoving_volume(z[i] - dz / 2., **cosmo)) / ( 1. + z[i]) * P(w) #Find out the redshift at which we detect 50%/90% of the sources at the redshift z_reach50 = max(z[where(compensate_detect_frac >= 0.5)]) z_reach90 = max(z[where(compensate_detect_frac >= 0.1)]) vol_sum = sum(unit_volume) #Find out the redshifts that 50%/90% of the sources lie within assuming constant-comoving-rate density z50 = max(z[where(cumsum(unit_volume) >= 0.5 * vol_sum)]) z90 = max(z[where(cumsum(unit_volume) >= 0.1 * vol_sum)]) #Find out the redshifts that 50%/90% of the sources lie within assuming star formation rate sfr_vol_sum = sum(unit_volume * sfr(z)) sfr_z50 = max(z[where(cumsum(unit_volume * sfr(z)) >= 0.5 * sfr_vol_sum)]) sfr_z90 = max(z[where(cumsum(unit_volume * sfr(z)) >= 0.1 * sfr_vol_sum)]) #average redshift z_mean = sum(unit_volume * z) / vol_sum sfr_z_mean = sum(unit_volume * sfr(z) * z) / sfr_vol_sum return (3. * vol_sum / 4. / pi)**( 1. / 3. ), z_reach50, z_reach90, horizon_redshift, vol_sum / 1E9, z50, z90, sfr_z50, sfr_z90, z_mean, sfr_z_mean
O_l,O_m,O_r,O_k,h = 0.7,0.3,0.0,0.0,0.7 # Cosmological parameters cosmo = {'omega_k_0': O_k, 'omega_M_0' : O_m, 'omega_lambda_0' : O_l, 'h' : h} Dist = [] for i in range(0,no_zsteps): for j in range(0,no_Lsteps): # Define params zmin = zstart + i*zstep zmax = zstart + (i+1)*zstep z = zmin + 0.5*(zmax-zmin) # Effective z to draw LF from Lmin = Lstart * Lmult**(j) Lmax = Lstart * Lmult**(j+1) # Compute comoving volume in Mpc-3 dV = ( comoving_volume(zmax,**cosmo) - comoving_volume(zmin,**cosmo) ) * (Tel_Area / 41253.) # Mpc3 # Get Phi in Mpc-3 alpha,logLStar,logPhiStar = LF_Data.retrieve_LF(z,line) LStar,PhiStar = 10.**(logLStar),10.**(logPhiStar) n = scipy.integrate.quad(lambda L: schechterL(L,PhiStar, alpha, LStar),Lmin, Lmax)[0] # Number = number density * volume N = n * dV # Compute flux DL = luminosity_distance(z, **cosmo) # In MPc DL = DL * (10**6. * pc) * 10**2. # in cm F = Lmin / (4 * math.pi * DL**2.) # ergs/s/cm2
#!/opt/local/bin/python
def volwmag(z, mumin=1, mumax=100, parameter_file='../"Debugging Things"/vp_lensmodels.lis'): if (len(sys.argv)>1): lensmodels = sys.argv[1] else: lensmodels=parameter_file print lensmodels if not (os.path.isfile(lensmodels)): print 'missing startup file' sys.exit() clist = asciitable.read(lensmodels, names=['alias', 'clusterdir', 'deflxfile', 'deflyfile', 'zcluster', 'zmodel']) # the grid of magnifications mu = np.linspace(1, 100, 100) mspacing = mumax-mumin + 1 magref = np.linspace(mumin, mumax, mspacing) TotalVolarrayWithSeg = np.zeros(mu.shape) TotalVolarray = np.zeros(mu.shape) PartialVolarray = np.zeros((mu.size, clist.size)) TotalSPVolArray = np.zeros(clist.shape) # target source redshift for rescaling model deflection maps ztarget = z # Plot stuff fig=plt.figure() MFig=fig.add_subplot(111) MFig.set_xlabel('Magnification [$\mu$]') MFig.set_ylabel('Effective Volume (>$\mu$) [Mpc$^3$]') MFig.set_xlim(0.2, 100) MFig.set_ylim(1.0, 2e5) MFig.set_xscale('log') MFig.set_yscale('log') # annotations -- check that these make sense MFig.text(30, 2e4, 'z=[9,10]', size=13) ytext = 1e5 outdata = open('volumedata_a1689.dat','w') for ii in np.arange(clist.size): alias = clist['alias'][ii] clusterdir = clist['clusterdir'][ii] deflxfile = clist['deflxfile'][ii] deflyfile = clist['deflyfile'][ii] zcluster = clist['zcluster'][ii] zmodel = clist['zmodel'][ii] # note that the model redshifts are in names of Adi's files # cosmic SFR per year are for rest frame times rescale = \ (cdad(ztarget, zcluster, **cosmo) /cdad(ztarget, **cosmo)) * \ (cdad(zmodel, **cosmo) / cdad(zmodel, zcluster, **cosmo)) # read in Adi's deflections axlist = pyfits.open('../{}/{}'.format(clusterdir, deflxfile)) aylist = pyfits.open('../{}/{}'.format(clusterdir, deflyfile)) ax, ay = rescale*axlist[0].data, rescale*aylist[0].data # read in segmentation map try: segfile = pyfits.open('../{}/{}'.format(clusterdir, segfile)) segmap=segfile[0].data segflag = 1 except: segflag = 0 segmap=ax*0.0 # do some initializations etc Unity = np.zeros(ax.shape)+1.0 header = axlist[0].header try: cdelt1, cdelt2 = header['CDELT1'], header['CDELT2'] header['CDELT1'], header['CDELT2'] = cdelt1, cdelt2 pxsc = np.abs(cdelt1)*3600.0 # in arcseconds per linear pixel dimension except: cd1_1, cd2_2 = header['CD1_1'], header['CD2_2'] pxsc = np.abs(cd1_1)*3600.0 # in arcseconds per linear pixel dimension # Calculate the magnification from Jacobian. Note that it first calculates the gradient with respect to the 'y' then with respect to the 'x' axis axy, axx = np.gradient(ax) ayy, ayx = np.gradient(ay) Jxx = Unity -axx Jxy = -axy Jyx = -ayx Jyy = Unity -ayy Mu = Unity / (Jxx*Jyy - Jxy*Jyx) AbsMu = np.abs(Mu) # define the total wfc3ir outline mask regionfile = '../{}/{}_acs_wfc3ir_outline.reg'.format(clusterdir, clusterdir) rwcs=pyregion.open(regionfile) rcoo=pyregion.open(regionfile).as_imagecoord(header) maskboo=rwcs.get_mask(hdu=axlist[0]) # diff_comoving_volume is differential comoving volume per unit redshift per unit solid angle, in units of Mpc**3 ster**-1. So convert this to a volume per (unlensed) pixel, for a source plane at ztarget. VolPix = (pxsc/206265.0)**2 * (cd.comoving_volume(ztarget+1, **cosmo) - cd.comoving_volume(ztarget, **cosmo)) # The PixMap is now the Mpc**3 volume that each pixel corresponds to in the target source plane. PixMap = VolPix / AbsMu # Now calculate the source-plane volume for each of the lower-limit magnifications. TotalSPVol = np.sum(PixMap[((AbsMu>0) & (maskboo))]) TotalSPVolArray[ii] = TotalSPVol VolarrayWithSeg = np.zeros(mu.shape) Volarray = np.zeros(mu.shape) for jj in np.arange(mu.size): # VolarrayWithSeg[jj] = np.sum( PixMap[((AbsMu>mu[jj]) & (rmask==1.0) & (segmap==0) )] ) # Volarray[jj] = np.sum( PixMap[((AbsMu>mu[jj]) & (rmask==1.0))] ) VolarrayWithSeg[jj] = np.sum( PixMap[((AbsMu>mu[jj]) & (maskboo) & (segmap==0) )] ) Volarray[jj] = np.sum( PixMap[((AbsMu>mu[jj]) & (maskboo))] ) TotalVolarrayWithSeg += VolarrayWithSeg TotalVolarray += Volarray PartialVolarray[:,ii] = VolarrayWithSeg s=si.UnivariateSpline(np.log10(mu),np.log10(VolarrayWithSeg),s=5) # need to write the mu, Volarray data to a file.... MFig.plot(mu,Volarray,label=alias) MFig.plot(mu,VolarrayWithSeg,'--') MFig.legend(loc=3,prop={'size':8}) # called 'PartialMVolArray' because it doesn't give the total volume over all the clusters, but rather the volume in each individual cluster for that particular magnification and above. PartialMVolArray = np.zeros((magref.size, clist.size)) for x in np.arange(len(PartialVolarray[0])): sx = si.UnivariateSpline(np.log10(mu), np.log10(PartialVolarray[:,x]), s=5) partialvol = (np.asarray(10**sx(np.log10(magref)))) PartialMVolArray[:,x] = partialvol # no error checking here yet... sws = si.UnivariateSpline(np.log10(mu),np.log10(TotalVolarrayWithSeg),s=5) s = si.UnivariateSpline(np.log10(mu),np.log10(TotalVolarray),s=5) volwithseg = (np.asarray(10**sws(np.log10(magref)))).reshape(len(magref), 1) volnoseg = (np.asarray(10**s(np.log10(magref)))).reshape(len(magref),1) magref = (np.asarray(magref)).reshape(len(magref),1) MVolArray = np.hstack((magref, volnoseg, volwithseg)) PartialMVolArray = np.c_[magref, PartialMVolArray] return PartialMVolArray