def geometry(snapshot_fname, plane, x_min, x_max, y_min, y_max, z_min, z_max): # read snapshot head and obtain BoxSize head = readsnap.snapshot_header(snapshot_fname) BoxSize = head.boxsize / 1e3 #Mpc/h plane_dict = {'XY': [0, 1], 'XZ': [0, 2], 'YZ': [1, 2]} # check that the plane is square if plane == 'XY': length1 = x_max - x_min length2 = y_max - y_min depth = z_max - z_min offset1 = x_min offset2 = y_min elif plane == 'XZ': length1 = x_max - x_min length2 = z_max - z_min depth = y_max - y_min offset1 = x_min offset2 = z_min else: length1 = y_max - y_min length2 = z_max - z_min depth = x_max - x_min offset1 = y_min offset2 = z_min if length1 != length2: print 'Plane has to be a square!!!' sys.exit() BoxSize_slice = length1 return length1, offset1, length2, offset2, depth, BoxSize_slice
def PlotRhoVsTemp(base, num, arepo=0, BINS=200, Omegab=0.044, xmin=-3., xmax=7., ymin=2., ymax=8., format='.eps'): if arepo > 0: filename=base+'snap_arepo_'+str(num).zfill(3) else: filename=base+'snap_gadget_'+str(num).zfill(3) head=rs.snapshot_header(filename) mass=np.float64(rs.read_block(filename, "MASS", parttype=0, arepo=arepo)) rho=np.float64(rs.read_block(filename, "RHO ", parttype=0, arepo=arepo)) u=np.float64(rs.read_block(filename, "U ", parttype=0, arepo=arepo)) Nelec=np.float64(rs.read_block(filename, "NE ", parttype=0, arepo=arepo)) temp=co.GetTemp(u, Nelec, 5./3.) rho_b=Omegab*co.GetRhoCrit() rho/=rho_b print "z = ", head.redshift print "min/max of T [K] = ", min(temp), max(temp) print "min/max of rho/rho_b = ", min(rho), max(rho) rho=np.log10(rho) temp=np.log10(temp) if (xmin==0.) & (ymin==0.) & (xmax==0.) & (ymax==0.): print "range not specified -> adjusting min/max" xmin=min(rho) xmax=max(rho) ymin=min(temp) ymax=max(temp) Z,x,y=np.histogram2d(rho,temp, range=[[xmin,xmax],[ymin,ymax]], weights=mass, bins=BINS, normed=True) Z=np.log10(Z) Zmin=Z[Z>-np.inf].min() Zmax=Z.max() print "min/max of log10(histogram) = ", Zmin, Zmax fig = plt.figure(1, figsize=(10.0,10.0)) ax = fig.add_subplot(1,1,1) im=ax.imshow(Z.T, vmin=Zmin, vmax=Zmax, origin='lower',interpolation='nearest', extent=[xmin, xmax, ymin, ymax], cmap=cm.get_cmap('jet')) ax.contour(Z.T,origin='lower',extent=[xmin, xmax, ymin, ymax], colors='black', vmin=Zmin, vmax=Zmax) x0, x1 = ax.get_xlim() y0, y1 = ax.get_ylim() ax.set_aspect((x1-x0)/(y1-y0)) ax.set_xlabel(r'log $\rho/\rho_{b}$', fontsize=20) ax.set_ylabel('log T [K]', fontsize=20) plt.colorbar(im, shrink=0.5) if arepo > 0: plt.suptitle('Arepo z='+str(round(head.redshift,2))) plt.savefig('Rho_vs_T_arepo_'+str(num).zfill(3)+format) else: plt.suptitle('Gadget z='+str(round(head.redshift,2))) plt.savefig('Rho_vs_T_gagdet_'+str(num).zfill(3)+format) fig.clf()
def Pk_comp(snapshot_fname,ptype,dims,do_RSD,axis,cpus,folder_out): # read relevant paramaters on the header print 'Computing power spectrum...' head = readsnap.snapshot_header(snapshot_fname) BoxSize = head.boxsize/1e3 #Mpc/h Masses = head.massarr*1e10 #Msun/h Nall = head.nall; Ntotal = np.sum(Nall,dtype=np.int64) Omega_m = head.omega_m Omega_l = head.omega_l redshift = head.redshift Hubble = 100.0*np.sqrt(Omega_m*(1.0+redshift)**3+Omega_l) #km/s/(Mpc/h) z = '%.3f'%redshift # find output file name fout = folder_out+'/Pk_' + name_dict[str(ptype)] if do_RSD: fout += ('_RS_axis=' + str(axis) + '_z=' + z + '.dat') else: fout += ('_z=' + z + '.dat') # read the positions of the particles pos = readsnap.read_block(snapshot_fname,"POS ",parttype=ptype)/1e3 #Mpc/h print '%.3f < X [Mpc/h] < %.3f'%(np.min(pos[:,0]),np.max(pos[:,0])) print '%.3f < Y [Mpc/h] < %.3f'%(np.min(pos[:,1]),np.max(pos[:,1])) print '%.3f < Z [Mpc/h] < %.3f\n'%(np.min(pos[:,2]),np.max(pos[:,2])) # read the velocities of the particles if do_RSD: print 'moving particles to redshift-space...' vel = readsnap.read_block(snapshot_fname,"VEL ",parttype=ptype) #km/s RSL.pos_redshift_space(pos,vel,BoxSize,Hubble,redshift,axis) del vel; print 'done' # define delta array delta = np.zeros((dims,dims,dims),dtype=np.float32) # when dealing with all particles take into account their different masses if ptype==-1: if Nall[0]==0: #if not hydro M = np.zeros(Ntotal,dtype=np.float32) #define the mass array offset = 0 for ptype in [0,1,2,3,4,5]: M[offset:offset+Nall[ptype]] = Masses[ptype] offset += Nall[ptype] else: M = readsnap.read_block(snapshot_fname,"MASS",parttype=-1)*1e10 mean = np.sum(M,dtype=np.float64)/dims**3 MASL.MA(pos,delta,BoxSize,'CIC',M); del pos,M else: mean = len(pos)*1.0/dims**3 MASL.MA(pos,delta,BoxSize,'CIC'); del pos # compute the P(k) and save results to file delta /= mean; delta -= 1.0 Pk = PKL.Pk(delta,BoxSize,axis=axis,MAS='CIC',threads=cpus); del delta np.savetxt(fout,np.transpose([Pk.k3D, Pk.Pk[:,0], Pk.Pk[:,1], Pk.Pk[:,2], Pk.Nmodes3D]))
def getG3power(sim, kmax): if z == 99: snap = sim + "/output/ics" elif z == 49: snap = sim + "/output/snapdir_000/PART_000" elif z == 9: snap = sim + "/output/snapdir_001/PART_001" elif z == 4: snap = sim + "/output/snapdir_002/PART_002" elif z == 3: snap = sim + "/output/snapdir_003/PART_003" elif z == 2: snap = sim + "/output/snapdir_005/PART_005" else: print("Don't have data for that redshift") quit() head = readsnap.snapshot_header(snap) rho_crit = 2.77536627e11 BoxSize = head.boxsize / 1e3 #Mpc/h Nall = head.nall Masses = head.massarr * 1e10 #Msun/h Omega_m = head.omega_m Omega_l = head.omega_l redshift = head.redshift ## Pylian params grid = 512 ptypes = [1] MAS = 'CIC' do_RSD = False axis = 0 threads = 1 assert (z - redshift) < 0.001, "Redshift requested: %s, redshift found: %s" % ( z, redshift) Omega_cdm = Nall[1] * Masses[1] / BoxSize**3 / rho_crit Omega_b = Omega_m - Omega_cdm ## Calculate fractions f_b = Omega_b / (Omega_cdm + Omega_b) f_c = Omega_cdm / (Omega_cdm + Omega_b) ## CDM delta = MASL.density_field_gadget(snap, ptypes, grid, MAS, do_RSD, axis) delta /= np.mean(delta, dtype=np.float64) delta -= 1.0 print("Mean after normalising = %.2e" % np.mean(delta, dtype=np.float64)) Pk = PKL.Pk(delta, BoxSize, axis, MAS, threads) # Calculate power k_sim = Pk.k3D Pk_sim = Pk.Pk[:, 0] Nmodes1D = Pk.Nmodes1D return k_sim[np.where(k_sim < kmax)], Pk_sim[np.where( k_sim < kmax)], BoxSize
def __init__(self, snapshot): filename, fformat = fname_format(snapshot) if fformat=='hdf5': f = h5py.File(filename, 'r') self.time = f['Header'].attrs[u'Time'] self.redshift = f['Header'].attrs[u'Redshift'] self.npart = (f['Header'].attrs[u'NumPart_ThisFile']).astype(np.int64) self.nall = (f['Header'].attrs[u'NumPart_Total']).astype(np.int64) self.filenum = int(f['Header'].attrs[u'NumFilesPerSnapshot']) self.massarr = f['Header'].attrs[u'MassTable'] self.boxsize = f['Header'].attrs[u'BoxSize'] # check if it is a SWIFT snapshot if '/Cosmology' in f.keys(): self.omega_m = f['Cosmology'].attrs[u'Omega_m'] self.omega_l = f['Cosmology'].attrs[u'Omega_lambda'] self.hubble = f['Cosmology'].attrs[u'h'] # check if it is a Gadget-4 snapshot elif '/Parameters' in f.keys(): self.omega_m = f['Parameters'].attrs[u'Omega0'] self.omega_l = f['Parameters'].attrs[u'OmegaLambda'] self.hubble = f['Parameters'].attrs[u'HubbleParam'] #self.cooling = f['Parameters'].attrs[u'Flag_Cooling'] # if it is a traditional Gadget-1/2/3 snapshot else: self.omega_m = f['Header'].attrs[u'Omega0'] self.omega_l = f['Header'].attrs[u'OmegaLambda'] self.hubble = f['Header'].attrs[u'HubbleParam'] #self.cooling = f['Header'].attrs[u'Flag_Cooling'] self.format = 'hdf5' f.close() else: head = readsnap.snapshot_header(filename) self.time = head.time self.redshift = head.redshift self.boxsize = head.boxsize self.filenum = head.filenum self.omega_m = head.omega_m self.omega_l = head.omega_l self.hubble = head.hubble self.massarr = head.massarr self.npart = head.npart self.nall = head.nall self.cooling = head.cooling self.format = head.format # km/s/(Mpc/h) self.Hubble = 100.0*np.sqrt(self.omega_m*(1.0+self.redshift)**3+self.omega_l)
def __init__( self, snapnum, directory="./", dirbases=["snapdir_", ""], snapbases=["/snap_"], exts=[".0.hdf5", ".hdf5", ""], check_total_particle_number=False, ): self.directory = directory self.snapnum = snapnum self.check_total_particle_number = check_total_particle_number found_files = False for dirbase in dirbases: for snapbase in snapbases: for dirnum in ["%03.d" % int(snapnum), ""]: for ext in exts: try_file = (directory + dirbase + dirnum + snapbase + dirnum + ext) if os.path.exists(try_file): self.headername = try_file self.snapname = (directory + dirbase + dirnum + snapbase + dirnum) found_files = True if not found_files: print("Headerfiles of %s not found." % directory) sys.exit() else: print("Headername: " + self.headername) print("Sanpname: " + self.snapname) # --- use new routine only for hdf5 snapshots --- if self.headername[-4:] == "hdf5": self.hdf5 = True self.header = header(self) hn = hdf5_names(self) self.hdf5_name = hn.name # --- otherwise import readsnap and readsubf to read the old gadget format --- else: self.hdf5 = False rs = __import__("readsnap") readsubf = __import__("readsubf") self.header = rs.snapshot_header(self.headername) self.time = self.header.time self.const = constants(self) self.data = {} # --- Calculate the total number of particles by hand, if required --- if self.check_total_particle_number: self.get_tot_num_part()
def __init__(self, snapnum, directory="./", dirbases=["snapdir_", ""], snapbases=["/snap_"], exts=["", ".hdf5"]): self.directory = directory self.snapnum = snapnum found_files = False for dirbase in dirbases: for snapbase in snapbases: for dirnum in ["", str(snapnum).zfill(3)]: for ext in exts: try_file = directory + dirbase + dirnum + snapbase + str( snapnum).zfill(3) + ".0" + ext print("trying file " + try_file) if os.path.exists(try_file): self.headername = try_file self.snapname = directory + dirbase + dirnum + snapbase + str( snapnum).zfill(3) found_files = True if not found_files: print("Headerfiles not found." + directory) sys.exit() else: print("Headername: " + self.headername) print("Sanpname: " + self.snapname) #--- use new routine only for hdf5 snapshots --- if self.headername[-4:] == 'hdf5': self.hdf5 = True self.header = header(self) hn = hdf5_names(self) self.hdf5_name = hn.name #--- otherwise import readsnap and readsubf to read the old gadget format --- else: self.hdf5 = False rs = __import__('readsnap') readsubf = __import__('readsubf') self.header = rs.snapshot_header(self.headername) self.time = self.header.time self.const = constants(self) self.data = {}
def read_snapshot(snapshot, printOut=False): ptype = [1] #[1](CDM), [2](neutrinos) or [1,2](CDM+neutrinos) header = rs.snapshot_header(snapshot) # reads snapshot header coords = rs.read_block( snapshot, "POS " ) # reads mass for particles of type 5, using block names should work for both format 1 and 2 snapshots ids = rs.read_block( snapshot, "ID " ) # reads mass for particles of type 5, using block names should work for both format 1 and 2 snapshots if printOut == True: print("coordinates for", coords.size, "particles read") print(coords[0:10]) print("ids for", ids.size, "particles read") print(ids[0:10]) return [ids, coords]
def snapshot_redshifts(snapfile, snap_tot_num, zmax): """ Input: snapfile: snapshot directory snap_tot_num: total number of snapshots zmax: maximum redshift of lightcone Output: z_lcone: mean redshift between two snapshot redshifts """ z_sim = [] for i in range(snap_tot_num, -1, -1): header = readsnap.snapshot_header(snapfile % (i, i)) if header.redshift > zmax: break else: z_sim.append(header.redshift) z_lcone = [z_sim[i] + (z_sim[i+1] - z_sim[i])/2 for i in range(len(z_sim)-1)] z_lcone.append(zmax) z_lcone = [0] + z_lcone return z_lcone
def __init__(self, snapshot): filename, fformat = fname_format(snapshot) if fformat == 'hdf5': f = h5py.File(filename, 'r') self.time = f['Header'].attrs[u'Time'] self.redshift = f['Header'].attrs[u'Redshift'] self.boxsize = f['Header'].attrs[u'BoxSize'] self.filenum = f['Header'].attrs[u'NumFilesPerSnapshot'] self.omega_m = f['Header'].attrs[u'Omega0'] self.omega_l = f['Header'].attrs[u'OmegaLambda'] self.hubble = f['Header'].attrs[u'HubbleParam'] self.massarr = f['Header'].attrs[u'MassTable'] self.npart = f['Header'].attrs[u'NumPart_ThisFile'] self.nall = f['Header'].attrs[u'NumPart_Total'] self.cooling = f['Header'].attrs[u'Flag_Cooling'] self.format = 'hdf5' f.close() else: head = readsnap.snapshot_header(filename) self.time = head.time self.redshift = head.redshift self.boxsize = head.boxsize self.filenum = head.filenum self.omega_m = head.omega_m self.omega_l = head.omega_l self.hubble = head.hubble self.massarr = head.massarr self.npart = head.npart self.nall = head.nall self.cooling = head.cooling self.format = head.format # km/s/(Mpc/h) self.Hubble = 100.0 * np.sqrt(self.omega_m * (1.0 + self.redshift)**3 + self.omega_l)
def star_mass_dist(basename, num, arepo=1, bins=100, format=".eps"): filename=basename+str(num).zfill(3) head=rs.snapshot_header(filename) mass = rs.read_block(filename,"MASS", parttype=4,arepo=arepo) print mass meanmass=mass.mean() print "mean star mass = ", meanmass print "min/max of star mass = ", mass.min(),mass.max() fig = plt.figure(1, figsize=(10.0,10.0)) ax = fig.add_subplot(1,1,1) # the histogram of the data n, bins, patches = plt.hist(np.log10(mass/meanmass), bins, normed=1, facecolor='blue') ax.set_xlabel('log[m/<m>]') ax.set_ylabel('df / dlog[m/<m>]') plt.suptitle('z='+str(round(head.redshift,2))) plt.savefig("star_mass_dist_"+str(num).zfill(3)+format) fig.clf()
def __init__(self, snapshot): filename, fformat = fname_format(snapshot) if fformat=='hdf5': f = h5py.File(filename, 'r') self.time = f['Header'].attrs[u'Time'] self.redshift = f['Header'].attrs[u'Redshift'] self.boxsize = f['Header'].attrs[u'BoxSize'] self.filenum = f['Header'].attrs[u'NumFilesPerSnapshot'] self.omega_m = f['Header'].attrs[u'Omega0'] self.omega_l = f['Header'].attrs[u'OmegaLambda'] self.hubble = f['Header'].attrs[u'HubbleParam'] self.massarr = f['Header'].attrs[u'MassTable'] self.npart = f['Header'].attrs[u'NumPart_ThisFile'] self.nall = f['Header'].attrs[u'NumPart_Total'] self.cooling = f['Header'].attrs[u'Flag_Cooling'] self.format = 'hdf5' f.close() else: head = readsnap.snapshot_header(filename) self.time = head.time self.redshift = head.redshift self.boxsize = head.boxsize self.filenum = head.filenum self.omega_m = head.omega_m self.omega_l = head.omega_l self.hubble = head.hubble self.massarr = head.massarr self.npart = head.npart self.nall = head.nall self.cooling = head.cooling self.format = head.format # km/s/(Mpc/h) self.Hubble = 100.0*np.sqrt(self.omega_m*(1.0+self.redshift)**3+self.omega_l)
#################################### INPUT #################################### snapshot_fname = '../ics' bins = 100 #number of bins for the distribution # parameters for the FD distribution Mnu = 0.6 #eV h_planck = 6.582e-16 #eV*s kB = 8.617e-5 #eV/K c = 3e5 #km/s Tnu = 1.95 #K ############################################################################### ########## fraction from simulation ########### # read snapshot redshift and neutrino velocities z = readsnap.snapshot_header(snapshot_fname).redshift vel = readsnap.read_block(snapshot_fname, "VEL ", parttype=2) #km/s # compute velocity modulus V = np.sqrt(vel[:, 0]**2 + vel[:, 1]**2 + vel[:, 2]**2) del vel # define the velocity intervals, their mean value and their widths vel_min, vel_max = np.min(V), np.max(V) if vel_min == 0.0: vel_min = 1e-3 vel_intervals = np.logspace(np.log10(vel_min), np.log10(vel_max), bins + 1) dV = vel_intervals[1:] - vel_intervals[:-1] #km/s V_mean = 0.5 * (vel_intervals[1:] + vel_intervals[:-1]) #km/s # compute the franction of neutrinos within each velocity bin hist = (np.histogram(V, bins=vel_intervals)[0]) * 1.0 / len(V)
def HaloProfiles(basename, num, centre, r200, rmin=0.05, rmax=10.0, bins=50, arepo=1, gamma=5./3., format=".eps"): filename=basename+str(num).zfill(3) head=rs.snapshot_header(filename) mass_gas = rs.read_block(filename,"MASS", parttype=0,arepo=arepo).astype('float64') mass_DM = rs.read_block(filename,"MASS", parttype=1,arepo=arepo).astype('float64') pos_gas = rs.read_block(filename,"POS ", parttype=0,arepo=arepo).astype('float64') pos_DM = rs.read_block(filename,"POS ", parttype=1,arepo=arepo).astype('float64') u = rs.read_block(filename,"U ", parttype=0,arepo=arepo).astype('float64') rho = rs.read_block(filename,"RHO ", parttype=0,arepo=arepo).astype('float64') Nele = rs.read_block(filename,"NE ", parttype=0,arepo=arepo).astype('float64') print "Centre = ", centre print "R200 = ", r200 print "rmin/rmax = ", rmin, rmax x=pos_gas[:,0] - centre[0] y=pos_gas[:,1] - centre[1] z=pos_gas[:,2] - centre[2] r_gas=np.sqrt(x**2. + y**2. + z**2.) / r200 x=pos_DM[:,0] - centre[0] y=pos_DM[:,1] - centre[1] z=pos_DM[:,2] - centre[2] r_DM=np.sqrt(x**2. + y**2. + z**2.) / r200 rmin=np.log10(rmin) rmax=np.log10(rmax) dlog10=(rmax-rmin)/bins rho_DM_bin=np.zeros(bins) rho_gas_bin=np.zeros(bins) temp_bin=np.zeros(bins) entropy_bin=np.zeros(bins) rbinm=10.**((np.arange(bins)+0.5)*dlog10 + rmin) for n in range(0,bins): r1=10.**((n+0.)*dlog10 + rmin) r2=10.**((n+1.)*dlog10 + rmin) index_gas=((r_gas>r1) & (r_gas<r2)).nonzero() index_DM=((r_DM>r1) & (r_DM<r2)).nonzero() totmass_gas=mass_gas[index_gas].sum() totmass_DM=mass_DM[index_DM].sum() rho_gas_bin[n]=totmass_gas/(4.*np.pi/3.*(r2**3.-r1**3.)*r200**3.) rho_DM_bin[n]=totmass_DM/(4.*np.pi/3.*(r2**3.-r1**3.)*r200**3.) if (totmass_gas > 0.): entropy_bin[n]=np.average(co.GetEntropy(u[index_gas],rho[index_gas],gamma), weights=mass_gas[index_gas]) temp_bin[n]=np.average(co.GetTemp(u[index_gas],Nele[index_gas],gamma), weights=mass_gas[index_gas]) fig = plt.figure(1, figsize=(10.0,10.0)) ax = fig.add_subplot(2,2,1) ax.set_xlabel('$r/r_{200}$') ax.set_ylabel(r'$\rho_{DM}$ [$h^2$ M$_\odot$ Kpc$^{-3}$]') ax.loglog() ax.plot(rbinm, 10.0**10.0*rho_DM_bin) ax.set_xlim((10.0**rmin,10.0**rmax)) ax = fig.add_subplot(2,2,2) ax.set_xlabel('$r/r_{200}$') ax.set_ylabel(r'$\rho_{gas}$ [$h^2$ M$_\odot$ Kpc$^{-3}$]') ax.loglog() ax.plot(rbinm, 10.0**10.0*rho_gas_bin) ax.set_xlim((10.0**rmin,10.0**rmax)) ax = fig.add_subplot(2,2,3) ax.set_xlabel('$r/r_{200}$') ax.set_ylabel('$T_{gas}$ [K]') ax.loglog() ax.plot(rbinm, temp_bin) ax.set_xlim((10.0**rmin,10.0**rmax)) ax = fig.add_subplot(2,2,4) ax.set_xlabel('$r/r_{200}$') ax.set_ylabel('Entropy') ax.loglog() ax.plot(rbinm, entropy_bin) ax.set_xlim((10.0**rmin,10.0**rmax)) plt.savefig("HaloProfiles_"+str(num).zfill(3)+format)
def Pk_Gadget(snapshot_fname,dims,particle_type,do_RSD,axis,cpus, folder_out=None): # find folder to place output files. Default is current directory if folder_out is None: folder_out = os.getcwd() # for either one single species or all species use this routine if len(particle_type)==1: Pk_comp(snapshot_fname,particle_type[0],dims,do_RSD, axis,cpus,folder_out) return None # read snapshot head and obtain BoxSize, Omega_m and Omega_L print '\nREADING SNAPSHOTS PROPERTIES' head = readsnap.snapshot_header(snapshot_fname) BoxSize = head.boxsize/1e3 #Mpc/h Nall = head.nall Masses = head.massarr*1e10 #Msun/h Omega_m = head.omega_m Omega_l = head.omega_l redshift = head.redshift Hubble = 100.0*np.sqrt(Omega_m*(1.0+redshift)**3+Omega_l) #km/s/(Mpc/h) h = head.hubble z = '%.3f'%redshift dims3 = dims**3 # compute the values of Omega_cdm, Omega_nu, Omega_gas and Omega_s Omega_c = Masses[1]*Nall[1]/BoxSize**3/rho_crit Omega_n = Masses[2]*Nall[2]/BoxSize**3/rho_crit Omega_g, Omega_s = 0.0, 0.0 if Nall[0]>0: if Masses[0]>0: Omega_g = Masses[0]*Nall[0]/BoxSize**3/rho_crit Omega_s = Masses[4]*Nall[4]/BoxSize**3/rho_crit else: # mass in Msun/h mass = readsnap.read_block(snapshot_fname,"MASS",parttype=0)*1e10 Omega_g = np.sum(mass,dtype=np.float64)/BoxSize**3/rho_crit mass = readsnap.read_block(snapshot_fname,"MASS",parttype=4)*1e10 Omega_s = np.sum(mass,dtype=np.float64)/BoxSize**3/rho_crit del mass # some verbose print 'Omega_gas = ',Omega_g print 'Omega_cdm = ',Omega_c print 'Omega_nu = ',Omega_n print 'Omega_star = ',Omega_s print 'Omega_m = ',Omega_g + Omega_c + Omega_n + Omega_s print 'Omega_m snap = ',Omega_m # dictionary giving the value of Omega for each component Omega_dict = {0:Omega_g, 1:Omega_c, 2:Omega_n, 4:Omega_s} ##################################################################### # define the array containing the deltas delta = [[],[],[],[]] #array containing the gas, CDM, NU and stars deltas # dictionary among particle type and the index in the delta and Pk arrays # delta of stars (ptype=4) is delta[3] not delta[4] index_dict = {0:0, 1:1, 2:2, 4:3} # define suffix here if do_RSD: suffix = '_RS_axis=' + str(axis) + '_z=' + z + '.dat' else: suffix = '_z=' + z + '.dat' ##################################################################### # do a loop over all particle types and compute the deltas for ptype in particle_type: # read particle positions in #Mpc/h pos = readsnap.read_block(snapshot_fname,"POS ",parttype=ptype)/1e3 # move particle positions to redshift-space if do_RSD: vel = readsnap.read_block(snapshot_fname,"VEL ",parttype=ptype)#km/s RSL.pos_redshift_space(pos,vel,BoxSize,Hubble,redshift,axis) del vel # find the index of the particle type in the delta array index = index_dict[ptype] # compute mean number of particles per grid cell mean_number = len(pos)*1.0/dims3 # compute the deltas delta[index] = np.zeros((dims,dims,dims),dtype=np.float32) MASL.MA(pos,delta[index],BoxSize,'CIC'); del pos delta[index] /= mean_number; delta[index] -= 1.0 ##################################################################### ##################################################################### # if there are two or more particles compute auto- and cross-power spectra for i,ptype1 in enumerate(particle_type): for ptype2 in particle_type[i+1:]: # find the indexes of the particle types index1 = index_dict[ptype1]; index2 = index_dict[ptype2] # choose the name of the output files fout1 = '/Pk_' + name_dict[str(ptype1)] + suffix fout2 = '/Pk_' + name_dict[str(ptype2)] + suffix fout12 = '/Pk_' + name_dict[str(ptype1)+str(ptype2)] + suffix fout1 = folder_out + fout1 fout2 = folder_out + fout2 fout12 = folder_out + fout12 # some verbose print '\nComputing the auto- and cross-power spectra of types: '\ ,ptype1,'-',ptype2 print 'saving results in:'; print fout1,'\n',fout2,'\n',fout12 # This routine computes the auto- and cross-power spectra data = PKL.XPk([delta[index1],delta[index2]],BoxSize,axis=axis, MAS=['CIC','CIC'],threads=cpus) k = data.k3D; Nmodes = data.Nmodes3D # save power spectra results in the output files np.savetxt(fout12,np.transpose([k, data.XPk[:,0,0], data.XPk[:,1,0], data.XPk[:,2,0], Nmodes])) np.savetxt(fout1, np.transpose([k, data.Pk[:,0,0], data.Pk[:,1,0], data.Pk[:,2,0], Nmodes])) np.savetxt(fout2, np.transpose([k, data.Pk[:,0,1], data.Pk[:,1,1], data.Pk[:,2,1], Nmodes])) ##################################################################### ##################################################################### # compute the power spectrum of the sum of all components print '\ncomputing P(k) of all components' # define delta of all components delta_tot = np.zeros((dims,dims,dims),dtype=np.float32) Omega_tot = 0.0; fout = folder_out + '/Pk_' for ptype in particle_type: index = index_dict[ptype] delta_tot += (Omega_dict[ptype]*delta[index]) Omega_tot += Omega_dict[ptype] fout += name_dict[str(ptype)] + '+' delta_tot /= Omega_tot; del delta; fout = fout[:-1] #avoid '+' in the end # compute power spectrum data = PKL.Pk(delta_tot,BoxSize,axis=axis,MAS='CIC', threads=cpus); del delta_tot # write P(k) to output file np.savetxt(fout+suffix, np.transpose([data.k3D, data.Pk[:,0], data.Pk[:,1], data.Pk[:,2], data.Nmodes3D]))
# Setting cosmology for concentrations pdict = {'flat': True, 'H0': params.h0true, 'Om0': params.omega0, 'Ob0': params.omegabaryon,\ 'sigma8': cosmology.sigma8, 'ns': params.ns} colossus.addCosmology('myCosmo', pdict) colossus.setCosmology('myCosmo') # Load Catalog cat = catalog(params.pincatfile.format(0.0)) rhoc = cosmology.lcdm.critical_density(0.0).to("M_sun/Mpc^3").value rDelta = (3 * cat.Mass / 4 / np.pi / 200 / rhoc)**(1.0 / 3) # Getting particle positions and particle mass pos = rs.read_block( params.pintlessfile.replace("t_snapshot", r"{0:5.4f}").format(0.0), "POS ") mp = rs.snapshot_header( params.pintlessfile.replace("t_snapshot", r"{0:5.4f}").format(0.0)).massarr[1] * 1e10 # Getting the Index of the i-th passive object in catalog idx = np.argsort(cat.Mass)[-1] # Getting the first and last icdx of the particles inside the most massive halo idxp1 = np.sum(cat.Npart[:idx]) idxp2 = idxp1 + cat.Npart[idx] plt.scatter(pos[idxp1:idxp2][:, 0], pos[idxp1:idxp2][:, 1], s=0.1) plt.show() plt.scatter(pos[idxp1:idxp2][:, 0], pos[idxp1:idxp2][:, 2], s=0.1) plt.show()
def read_block(filename, block, parttype, physical_velocities=True, verbose=False): if parttype not in [0, 1, 2, 3, 4, 5]: print('Routine can only read parttypes in [0,1,2,3,4,5]') sys.exit() # find the format,swap, total number of particles and subfiles head = readsnap.snapshot_header(filename) files, format, swap = head.filenum, head.format, head.swap nall, time, redshift = head.nall, head.time, head.redshift del head if myrank == 0 and verbose: print('Reading snapshot with %d cores' % nprocs) print('Number of subfiles = %d' % files) # find the files each cpu reads subfiles = np.array_split(np.arange(files), nprocs)[myrank] # find the total number of particles to read Nall_local = np.int64(0) for i in subfiles: head = readsnap.snapshot_header(filename + '.%d' % i) Nall_local += head.npart[parttype] del head if verbose: print('core %03d reading %03d files: [%03d-%03d] %9d particles'\ %(myrank,len(subfiles),subfiles[0],subfiles[-1],Nall_local)) # check that all particles are read Nall = comm.reduce(Nall_local, op=MPI.SUM, root=0) if myrank == 0 and Nall != nall[parttype]: print('Read %d particles while expected %d' % (Nall, nall[parttype])) sys.exit() # find the data type if block == "POS ": dt = np.dtype((np.float32, 3)) block_num = 2 elif block == "VEL ": dt = np.dtype((np.float32, 3)) block_num = 3 elif block == "ID ": dt = np.uint32 block_num = 4 else: print('Block not found!') sys.exit() # define the data array if myrank == 0: data = np.empty(Nall, dtype=dt) else: data = np.empty(Nall_local, dtype=dt) # do a loop over all subfiles offset_array = 0 start = Time.time() for i in subfiles: # find subfile name and number of particles in it curfilename = filename + '.%d' % i head = readsnap.snapshot_header(curfilename) npart = head.npart particles = npart[parttype] offset_species = np.zeros(6, np.int64) allpartnum = np.int64(0) for j in range(6): offset_species[j] = allpartnum allpartnum += npart[j] # find the offset and the size of the block (for all particle types) offset_block, blocksize = readsnap.find_block(curfilename, format, swap, block, block_num) # if long IDs change dt to np.uint64 if i == subfiles[0] and block == "ID ": if blocksize == np.dtype(dt).itemsize * allpartnum * 2: dt = np.uint64 # read file f = open(curfilename, 'rb') f.seek(offset_block + offset_species[parttype] * np.dtype(dt).itemsize, os.SEEK_CUR) curdat = np.fromfile(f, dtype=dt, count=particles) f.close() if swap: curdat.byteswap(True) data[offset_array:offset_array + particles] = curdat offset_array += particles if verbose: print('%d: Time to read files = %.2f' % (myrank, Time.time() - start)) # slaves send master the particles read if myrank > 0: comm.send(Nall_local, dest=0, tag=1) #number of particles read comm.Send(data, dest=0, tag=2) #property read (pos,vel,ID..) return 0 #put 0 to avoid problems when reading pos and /1e3 #Mpc/h # master collect all information from slaves and return the array else: offset = Nall_local # do a loop over all slaves start = Time.time() for i in range(1, nprocs): npart = comm.recv(source=i, tag=1) comm.Recv(data[offset:offset + npart], source=i, tag=2) if verbose: print('Time to transfer files = %.2f' % (Time.time() - start)) offset += npart if physical_velocities and block == "VEL " and redshift != 0: data *= np.sqrt(time) return data
def read_block(filename, block, parttype, physical_velocities=True, verbose=False): if parttype not in [0,1,2,3,4,5]: print 'Routine can only read parttypes in [0,1,2,3,4,5,6]' sys.exit() # find the format,swap, total number of particles and subfiles head = readsnap.snapshot_header(filename) files, format, swap = head.filenum, head.format, head.swap nall, time, redshift = head.nall, head.time, head.redshift; del head if myrank==0 and verbose: print 'Reading snapshot with %d cores'%nprocs print 'Number of subfiles = %d'%files # find the files each cpu reads subfiles = np.array_split(np.arange(files),nprocs)[myrank] # find the total number of particles to read Nall_local = np.int64(0) for i in subfiles: head = readsnap.snapshot_header(filename+'.%d'%i) Nall_local += head.npart[parttype] del head if verbose: print 'core %03d reading %03d files: [%03d-%03d] %9d particles'\ %(myrank,len(subfiles),subfiles[0],subfiles[-1],Nall_local) # check that all particles are read Nall = comm.reduce(Nall_local, op=MPI.SUM, root=0) if myrank==0 and Nall!=nall[parttype]: print 'Read %d particles while expected %d'%(Nall,nall[parttype]) sys.exit() # find the data type if block=="POS ": dt = np.dtype((np.float32,3)) block_num = 2 elif block=="VEL ": dt = np.dtype((np.float32,3)) block_num = 3 elif block=="ID ": dt = np.uint32 block_num = 4 else: print 'Block not found!'; sys.exit() # define the data array if myrank==0: data = np.empty(Nall, dtype=dt) else: data = np.empty(Nall_local, dtype=dt) # do a loop over all subfiles offset_array = 0; start = Time.time() for i in subfiles: # find subfile name and number of particles in it curfilename = filename+'.%d'%i head = readsnap.snapshot_header(curfilename) npart = head.npart particles = npart[parttype] offset_species = np.zeros(6,np.int64) allpartnum = np.int64(0) for j in xrange(6): offset_species[j] = allpartnum allpartnum += npart[j] # find the offset and the size of the block (for all particle types) offset_block,blocksize = readsnap.find_block(curfilename,format,swap, block,block_num) # if long IDs change dt to np.uint64 if i==subfiles[0] and block=="ID ": if blocksize==np.dtype(dt).itemsize*allpartnum*2: dt = np.uint64 # read file f = open(curfilename, 'rb') f.seek(offset_block + offset_species[parttype]*np.dtype(dt).itemsize, os.SEEK_CUR) curdat = np.fromfile(f, dtype=dt, count=particles) f.close() if swap: curdat.byteswap(True) data[offset_array:offset_array+particles] = curdat offset_array += particles if verbose: print '%d: Time to read files = %.2f'%(myrank,Time.time()-start) # slaves send master the particles read if myrank>0: comm.send(Nall_local, dest=0, tag=1) #number of particles read comm.Send(data, dest=0, tag=2) #property read (pos,vel,ID..) return 0 #put 0 to avoid problems when reading pos and /1e3 #Mpc/h # master collect all information from slaves and return the array else: offset = Nall_local # do a loop over all slaves start = Time.time() for i in xrange(1,nprocs): npart = comm.recv(source=i, tag=1) comm.Recv(data[offset:offset+npart], source=i, tag=2) if verbose: print 'Time to transfer files = %.2f'%(Time.time()-start) offset += npart if physical_velocities and block=="VEL " and redshift!=0: data *= np.sqrt(time) return data
# density field parameters grid = 768 MAS = 'PCS' # void finder parameters Radii = np.array( [5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41], dtype=np.float32) threshold = -0.7 threads1 = 16 threads2 = 4 void_field = True ############################################################################## # read snapshot head and obtain BoxSize, Omega_m and Omega_L head = readsnap.snapshot_header(snapshot) BoxSize = head.boxsize / 1e3 #Mpc/h Radii = Radii * BoxSize / grid # read particle positions pos = readsnap.read_block(snapshot, "POS ", parttype=1) / 1e3 #Mpc/h # compute density field delta = np.zeros((grid, grid, grid), dtype=np.float32) MASL.MA(pos, delta, BoxSize, MAS) delta /= np.mean(delta, dtype=np.float64) delta -= 1.0 # find the void V = VL.void_finder(delta,
def compute_Pk(snapshot_fname,dims,do_RSD,axis,hydro): # read snapshot head and obtain BoxSize, Omega_m and Omega_L print '\nREADING SNAPSHOTS PROPERTIES' head = readsnap.snapshot_header(snapshot_fname) BoxSize = head.boxsize/1e3 #Mpc/h Nall = head.nall Masses = head.massarr*1e10 #Msun/h Omega_m = head.omega_m Omega_l = head.omega_l redshift = head.redshift Hubble = 100.0*np.sqrt(Omega_m*(1.0+redshift)**3+Omega_l) #h*km/s/Mpc h = head.hubble z = '%.3f'%redshift f_out = 'Pk_m_z='+z+'.dat' # compute the values of Omega_CDM and Omega_B Omega_cdm = Nall[1]*Masses[1]/BoxSize**3/rho_crit Omega_nu = Nall[2]*Masses[2]/BoxSize**3/rho_crit Omega_b = Omega_m-Omega_cdm-Omega_nu print '\nOmega_CDM = %.4f\nOmega_B = %0.4f\nOmega_NU = %.4f'\ %(Omega_cdm,Omega_b,Omega_nu) print 'Omega_M = %.4f'%(Omega_m) # read the positions of all the particles pos = readsnap.read_block(snapshot_fname,"POS ",parttype=-1)/1e3 #Mpc/h print '%.3f < X [Mpc/h] < %.3f'%(np.min(pos[:,0]),np.max(pos[:,0])) print '%.3f < Y [Mpc/h] < %.3f'%(np.min(pos[:,1]),np.max(pos[:,1])) print '%.3f < Z [Mpc/h] < %.3f\n'%(np.min(pos[:,2]),np.max(pos[:,2])) if do_RSD: print 'moving particles to redshift-space' # read the velocities of all the particles vel = readsnap.read_block(snapshot_fname,"VEL ",parttype=-1) #km/s RSL.pos_redshift_space(pos,vel,BoxSize,Hubble,redshift,axis); del vel # read the masses of all the particles if not(hydro): Ntotal = np.sum(Nall,dtype=np.int64) #compute the number of particles M = np.zeros(Ntotal,dtype=np.float32) #define the mass array offset = 0 for ptype in [0,1,2,3,4,5]: M[offset:offset+Nall[ptype]] = Masses[ptype]; offset += Nall[ptype] else: M = readsnap.read_block(snapshot_fname,"MASS",parttype=-1)*1e10 #Msun/h print '%.3e < M [Msun/h] < %.3e'%(np.min(M),np.max(M)) print 'Omega_M = %.4f\n'%(np.sum(M,dtype=np.float64)/rho_crit/BoxSize**3) # compute the mean mass per grid cell mean_M = np.sum(M,dtype=np.float64)/dims**3 # compute the mass within each grid cell delta = np.zeros(dims**3,dtype=np.float32) CIC.CIC_serial(pos,dims,BoxSize,delta,M); del pos print '%.6e should be equal to \n%.6e\n'\ %(np.sum(M,dtype=np.float64),np.sum(delta,dtype=np.float64)); del M # compute the density constrast within each grid cell delta/=mean_M; delta-=1.0 print '%.3e < delta < %.3e\n'%(np.min(delta),np.max(delta)) # compute the P(k) Pk = PSL.power_spectrum_given_delta(delta,dims,BoxSize) # write P(k) to output file np.savetxt(f_out,np.transpose([Pk[0],Pk[1]]))
def hod(snapshot_fname,groups_fname,groups_number,min_mass,max_mass, fiducial_density,M1,alpha,mass_criteria,verbose=False): thres=1e-3 #controls the max relative error to accept a galaxy density #read the header and obtain the boxsize head=readsnap.snapshot_header(snapshot_fname) BoxSize=head.boxsize #BoxSize in kpc/h #read positions and IDs of DM particles: sort the IDs array DM_pos=readsnap.read_block(snapshot_fname,"POS ",parttype=-1) #kpc/h DM_ids=readsnap.read_block(snapshot_fname,"ID ",parttype=-1)-1 sorted_ids=DM_ids.argsort(axis=0) #the particle whose ID is N is located in the position sorted_ids[N] #i.e. DM_ids[sorted_ids[N]]=N #the position of the particle whose ID is N would be: #DM_pos[sorted_ids[N]] #read the IDs of the particles belonging to the CDM halos halos_ID=readsubf.subf_ids(groups_fname,groups_number,0,0, long_ids=True,read_all=True) IDs=halos_ID.SubIDs-1 del halos_ID #read CDM halos information halos=readsubf.subfind_catalog(groups_fname,groups_number, group_veldisp=True,masstab=True, long_ids=True,swap=False) if mass_criteria=='t200': halos_mass=halos.group_m_tophat200*1e10 #masses in Msun/h halos_radius=halos.group_r_tophat200 #radius in kpc/h elif mass_criteria=='m200': halos_mass=halos.group_m_mean200*1e10 #masses in Msun/h halos_radius=halos.group_r_mean200 #radius in kpc/h elif mass_criteria=='c200': halos_mass=halos.group_m_crit200*1e10 #masses in Msun/h halos_radius=halos.group_r_crit200 #radius in kpc/h else: print 'bad mass_criteria' sys.exit() halos_pos=halos.group_pos #positions in kpc/h halos_len=halos.group_len halos_offset=halos.group_offset halos_indexes=np.where((halos_mass>min_mass) & (halos_mass<max_mass))[0] del halos if verbose: print ' ' print 'total halos found=',halos_pos.shape[0] print 'halos number density=',len(halos_pos)/(BoxSize*1e-3)**3 #keep only the halos in the given mass range halo_mass=halos_mass[halos_indexes] halo_pos=halos_pos[halos_indexes] halo_radius=halos_radius[halos_indexes] halo_len=halos_len[halos_indexes] halo_offset=halos_offset[halos_indexes] del halos_indexes ##### COMPUTE Mmin GIVEN M1 & alpha ##### i=0; max_iterations=20 #maximum number of iterations Mmin1=min_mass; Mmin2=max_mass while (i<max_iterations): Mmin=0.5*(Mmin1+Mmin2) #estimation of the HOD parameter Mmin total_galaxies=0 inside=np.where(halo_mass>Mmin)[0] #take all galaxies with M>Mmin mass=halo_mass[inside] #only halos with M>Mmin have central/satellites total_galaxies=mass.shape[0]+np.sum((mass/M1)**alpha) mean_density=total_galaxies*1.0/(BoxSize*1e-3)**3 #galaxies/(Mpc/h)^3 if (np.absolute((mean_density-fiducial_density)/fiducial_density)<thres): i=max_iterations elif (mean_density>fiducial_density): Mmin1=Mmin else: Mmin2=Mmin i+=1 if verbose: print ' ' print 'Mmin=',Mmin print 'average number of galaxies=',total_galaxies print 'average galaxy density=',mean_density ######################################### #just halos with M>Mmin; the rest do not host central/satellite galaxies inside=np.where(halo_mass>Mmin)[0] halo_mass=halo_mass[inside] halo_pos=halo_pos[inside] halo_radius=halo_radius[inside] halo_len=halo_len[inside] halo_offset=halo_offset[inside] del inside #compute number of satellites in each halo using the Poisson distribution N_mean_sat=(halo_mass/M1)**alpha #mean number of satellites N_sat=np.empty(len(N_mean_sat),dtype=np.int32) for i in range(len(N_sat)): N_sat[i]=np.random.poisson(N_mean_sat[i]) N_tot=np.sum(N_sat)+len(halo_mass) #total number of galaxies in the catalogue if verbose: print ' ' print np.min(halo_mass),'< M_halo <',np.max(halo_mass) print 'total number of galaxies=',N_tot print 'galaxy number density=',N_tot/(BoxSize*1e-3)**3 #put satellites following the distribution of dark matter in groups if verbose: print ' ' print 'Creating mock catalogue ...', pos_galaxies=np.empty((N_tot,3),dtype=np.float32) #index: variable that go through halos (may be several galaxies in a halo) #i: variable that go through all (central/satellites) galaxies #count: find number of galaxies that lie beyond its host halo virial radius index=0; count=0; i=0 while (index<halo_mass.shape[0]): position=halo_pos[index] #position of the DM halo radius=halo_radius[index] #radius of the DM halo #save the position of the central galaxy pos_galaxies[i]=position; i+=1 #if halo contains satellites, save their positions Nsat=N_sat[index] if Nsat>0: offset=halo_offset[index] length=halo_len[index] idss=sorted_ids[IDs[offset:offset+length]] #compute the distances to the halo center keeping those with R<Rvir pos=DM_pos[idss] #positions of the particles belonging to the halo posc=pos-position #this is to populate correctly halos closer to box boundaries if np.any((position+radius>BoxSize) + (position-radius<0.0)): inside=np.where(posc[:,0]>BoxSize/2.0)[0] posc[inside,0]-=BoxSize inside=np.where(posc[:,0]<-BoxSize/2.0)[0] posc[inside,0]+=BoxSize inside=np.where(posc[:,1]>BoxSize/2.0)[0] posc[inside,1]-=BoxSize inside=np.where(posc[:,1]<-BoxSize/2.0)[0] posc[inside,1]+=BoxSize inside=np.where(posc[:,2]>BoxSize/2.0)[0] posc[inside,2]-=BoxSize inside=np.where(posc[:,2]<-BoxSize/2.0)[0] posc[inside,2]+=BoxSize radii=np.sqrt(posc[:,0]**2+posc[:,1]**2+posc[:,2]**2) inside=np.where(radii<radius)[0] selected=random.sample(inside,Nsat) pos=pos[selected] #aditional, not esential check. Can be comment out posc=pos-position if np.any((posc>BoxSize/2.0) + (posc<-BoxSize/2.0)): inside=np.where(posc[:,0]>BoxSize/2.0)[0] posc[inside,0]-=BoxSize inside=np.where(posc[:,0]<-BoxSize/2.0)[0] posc[inside,0]+=BoxSize inside=np.where(posc[:,1]>BoxSize/2.0)[0] posc[inside,1]-=BoxSize inside=np.where(posc[:,1]<-BoxSize/2.0)[0] posc[inside,1]+=BoxSize inside=np.where(posc[:,2]>BoxSize/2.0)[0] posc[inside,2]-=BoxSize inside=np.where(posc[:,2]<-BoxSize/2.0)[0] posc[inside,2]+=BoxSize r_max=np.max(np.sqrt(posc[:,0]**2+posc[:,1]**2+posc[:,2]**2)) if r_max>radius: #check no particles beyond Rv selected print position print radius print pos count+=1 for j in range(Nsat): pos_galaxies[i]=pos[j]; i+=1 index+=1 if verbose: print 'done' #some final checks if i!=N_tot: print 'some galaxies missing:' print 'register',i,'galaxies out of',N_tot if count>0: print 'error:',count,'particles beyond the virial radius selected' return pos_galaxies
def new_block(snapshot_fname, out_fname, data): print '\n** Appending a new block to ', snapshot_fname, '\n' print '(data given should be sorted in IDs order)' print 'reading snapshot properties . . ' head = readsnap.snapshot_header(snapshot_fname) Nall = head.nall filenum = head.filenum swap = head.swap format = head.format del head print 'number of particles = %d' % Nall[1] print 'number of subfiles in the snapshot = %d\n' % filenum ################### ASSUMPTIONS ################### ## DATA HAS TO BE SORTED IN IDs ORDER! ## # snaps IDs are unsigned double integers dt = np.uint64 # sims w/ only 1 particle type (DM) add_offset = np.int32(0) # the data is an array with len of particles # i.e. a value for each particle if len(data) != Nall[1]: print '\nDATA DOES NOT HAVE RIGHT LENGTH !!\n' sys.exit() # the data type is FLOAT if not isinstance(data[0], (np.float32, np.float64)): print '\nDATA MUST BE FLOAT !!\n' sys.exit() # the machine is INTEL, i.e. little-endian # (the appended data has to have same endianess # as the rest of the snapshot) if swap: endns = '>' # to write w/ big-endian else: endns = '<' # to write w/ little-endian ################################################### # checking size of data to append # i.e. 4 or 8 bytes? S = data.itemsize if S == 8: data_type = 'd' elif S == 4: data_type = 'f' else: print '\nCHECK DATA TYPE!!\n' sys.exit() ## now looping on the subfiles of the snapshot for i in range(filenum): curfilename = snapshot_fname + '.' + str(i) outputfname = out_fname + '.' + str(i) print 'modifyng ', curfilename ## this is just to copy the snapshot subfile with open(outputfname, "wb") as newfile, open(curfilename, "rb") as snap: newfile.write(snap.read()) newfile.close() head = readsnap.snapshot_header(curfilename) npart = head.npart npart = npart[1] print 'which contains ', npart, ' particles' ## read the IDs of SUB file offset, blocksize = readsnap.find_block(curfilename, format, swap, "ID ", 4) f = open(curfilename, 'rb') f.seek(offset + add_offset * np.dtype(dt).itemsize, os.SEEK_CUR) subIDs = np.fromfile(f, dtype=dt, count=npart) # read data f.close() if swap: subIDs.byteswap(True) ## indexes go as ID+1 sub_data = data[subIDs - 1] ## now we append the new data block_field = endns + 'I' # 4-bytes integer block_data = endns + data_type # i.e. either '<d' or '<f' print '.. writing the new snapshot subfile ..\n' file = open(outputfname, 'ab') file.write(struct.pack(block_field, int(npart * S))) for j in range(npart): file.write(struct.pack(block_data, sub_data[j])) file.write(struct.pack(block_field, int(npart * S))) file.close() del npart, head, subIDs, sub_data print '\nNew snapshot created!\n'
dims=1024 #if enviroment='HALOS' select here the mass range mass_interval=False #if all halos are wanted set mass_interval=False min_mass=1e10 #Msun/h max_mass=1e11 #Msun/h f_out='Pk_HI_Dave_filaments_60Mpc_z=6.dat' ############################################################################### dims3=dims**3 #read snapshot head and obtain BoxSize, Omega_m and Omega_L print '\nREADING SNAPSHOTS PROPERTIES' head=readsnap.snapshot_header(snapshot_fname) BoxSize=head.boxsize/1e3 #Mpc/h Nall=head.nall Masses=head.massarr*1e10 #Msun/h Omega_m=head.omega_m Omega_l=head.omega_l redshift=head.redshift Hubble=100.0*np.sqrt(Omega_m*(1.0+redshift)**3+Omega_l) #h*km/s/Mpc h=head.hubble #split the particle IDs among CDM, gas and stars and also among enviroment indexes=HIL.particle_indexes(snapshot_fname,groups_fname,groups_number, long_ids_flag,SFR_flag,mass_interval,min_mass, max_mass) #find the total number of particles in the simulation
zmax = 1. # highest redshift alpha = 0.522 # apex angle observerpos = [0, 0, 0] coneaxis = [1, 0, 0] # unit vector lc_number = 1 ########################################################################### # Iterate through Simulations for sim in range(len(sim_dir)): logging.info('Create a Light-cone for: %s; with: %s' % (sim_name[sim], hf_name)) snapfile = sim_dir[sim] + 'snapdir_%03d/snap_%03d' # Cosmological Parameters snap_tot_num = 45 header = readsnap.snapshot_header(snapfile % (snap_tot_num, snap_tot_num)) cosmo = LambdaCDM(H0=header.hubble * 100, Om0=header.omega_m, Ode0=header.omega_l) # Load Subhalo properties for z=0 box = LC(hf_dir[sim], sim_dir[sim], snap_tot_num, hf_name) #Redshift Steps of snapshots; past to present z_lcone = snapshot_redshifts(snapfile, snap_tot_num, zmax) # Comoving distance between z_lcone CoDi = Dc(z_lcone, box.unitlength, cosmo) # Interpolation fct. between comoving dist. and redshift reddistfunc = interp1d(CoDi, z_lcone, kind='cubic') CoDi = CoDi[1:] print(CoDi)
def density_field_2D(snapshot_fname, x_min, x_max, y_min, y_max, z_min, z_max, dims, ptypes, plane, MAS, save_density_field): plane_dict = {'XY': [0, 1], 'XZ': [0, 2], 'YZ': [1, 2]} # read snapshot head and obtain BoxSize, filenum... head = readsnap.snapshot_header(snapshot_fname) BoxSize = head.boxsize / 1e3 #Mpc/h Nall = head.nall Masses = head.massarr * 1e10 #Msun/h filenum = head.filenum redshift = head.redshift # find the geometric values of the density field square len_x, off_x, len_y, off_y, depth, BoxSize_slice = \ geometry(snapshot_fname, plane, x_min, x_max, y_min, y_max, z_min, z_max) # compute the mean density in the box if len(ptypes) == 1 and Masses[ptypes[0]] != 0.0: single_specie = True else: single_specie = False # define the density array overdensity = np.zeros((dims, dims), dtype=np.float32) # do a loop over all subfiles in the snapshot total_mass, mass_slice = 0.0, 0.0 renormalize_2D = False for i in xrange(filenum): # find the name of the subfile snap = snapshot_fname + '.%d' % i # in the last snapshot we renormalize the field if i == filenum - 1: renormalize_2D = True # do a loop over for ptype in ptypes: # read the positions of the particles in Mpc/h pos = readsnap.read_block(snap, "POS ", parttype=ptype) / 1e3 if single_specie: total_mass += len(pos) # keep only with the particles in the slice indexes = np.where((pos[:, 0] > x_min) & (pos[:, 0] < x_max) & (pos[:, 1] > y_min) & (pos[:, 1] < y_max) & (pos[:, 2] > z_min) & (pos[:, 2] < z_max)) pos = pos[indexes] # renormalize positions pos[:, 0] -= x_min pos[:, 1] -= y_min pos[:, 2] -= z_min # project particle positions into a 2D plane pos = pos[:, plane_dict[plane]] # read the masses of the particles in Msun/h if not (single_specie): mass = readsnap.read_block(snap, "MASS", parttype=ptype) * 1e10 total_mass += np.sum(mass, dtype=np.float64) mass = mass[indexes] MASL.MA(pos, overdensity, BoxSize_slice, MAS=MAS, W=mass, renormalize_2D=renormalize_2D) else: mass_slice += len(pos) MASL.MA(pos, overdensity, BoxSize_slice, MAS=MAS, W=None, renormalize_2D=renormalize_2D) print 'Expected mass = %.7e' % mass_slice print 'Computed mass = %.7e' % np.sum(overdensity, dtype=np.float64) # compute mean density in the whole box mass_density = total_mass * 1.0 / BoxSize**3 #(Msun/h)/(Mpc/h)^3 or #/(Mpc/h)^3 print 'mass density = %.5e' % mass_density # compute the volume of each cell in the density field slice V_cell = BoxSize_slice**2 * depth * 1.0 / dims**2 #(Mpc/h)^3 # compute the mean mass in each cell of the slice mean_mass = mass_density * V_cell #Msun/h or # # compute overdensities overdensity /= mean_mass print np.min(overdensity), '< rho/<rho> <', np.max(overdensity) # in our convention overdensity(x,y), while for matplotlib is # overdensity(y,x), so we need to transpose the field overdensity = np.transpose(overdensity) # save density field to file f_df = density_field_name(snapshot_fname, x_min, x_max, y_min, y_max, z_min, z_max, dims, ptypes, plane, MAS) if save_density_field: np.save(f_df, overdensity) return overdensity
def hod(snapshot_fname, groups_fname, groups_number, min_mass, max_mass, fiducial_density, M1, alpha, mass_criteria, verbose=False): thres = 1e-3 #controls the max relative error to accept a galaxy density #read the header and obtain the boxsize head = readsnap.snapshot_header(snapshot_fname) BoxSize = head.boxsize #BoxSize in kpc/h #read positions and IDs of DM particles: sort the IDs array DM_pos = readsnap.read_block(snapshot_fname, "POS ", parttype=-1) #kpc/h DM_ids = readsnap.read_block(snapshot_fname, "ID ", parttype=-1) - 1 sorted_ids = DM_ids.argsort(axis=0) #the particle whose ID is N is located in the position sorted_ids[N] #i.e. DM_ids[sorted_ids[N]]=N #the position of the particle whose ID is N would be: #DM_pos[sorted_ids[N]] #read the IDs of the particles belonging to the CDM halos halos_ID = readsubf.subf_ids(groups_fname, groups_number, 0, 0, long_ids=True, read_all=True) IDs = halos_ID.SubIDs - 1 del halos_ID #read CDM halos information halos = readsubf.subfind_catalog(groups_fname, groups_number, group_veldisp=True, masstab=True, long_ids=True, swap=False) if mass_criteria == 't200': halos_mass = halos.group_m_tophat200 * 1e10 #masses in Msun/h halos_radius = halos.group_r_tophat200 #radius in kpc/h elif mass_criteria == 'm200': halos_mass = halos.group_m_mean200 * 1e10 #masses in Msun/h halos_radius = halos.group_r_mean200 #radius in kpc/h elif mass_criteria == 'c200': halos_mass = halos.group_m_crit200 * 1e10 #masses in Msun/h halos_radius = halos.group_r_crit200 #radius in kpc/h else: print('bad mass_criteria') sys.exit() halos_pos = halos.group_pos #positions in kpc/h halos_len = halos.group_len halos_offset = halos.group_offset halos_indexes = np.where((halos_mass > min_mass) & (halos_mass < max_mass))[0] del halos if verbose: print(' ') print('total halos found=', halos_pos.shape[0]) print('halos number density=', len(halos_pos) / (BoxSize * 1e-3)**3) #keep only the halos in the given mass range halo_mass = halos_mass[halos_indexes] halo_pos = halos_pos[halos_indexes] halo_radius = halos_radius[halos_indexes] halo_len = halos_len[halos_indexes] halo_offset = halos_offset[halos_indexes] del halos_indexes ##### COMPUTE Mmin GIVEN M1 & alpha ##### i = 0 max_iterations = 20 #maximum number of iterations Mmin1 = min_mass Mmin2 = max_mass while (i < max_iterations): Mmin = 0.5 * (Mmin1 + Mmin2) #estimation of the HOD parameter Mmin total_galaxies = 0 inside = np.where(halo_mass > Mmin)[0] #take all galaxies with M>Mmin mass = halo_mass[ inside] #only halos with M>Mmin have central/satellites total_galaxies = mass.shape[0] + np.sum((mass / M1)**alpha) mean_density = total_galaxies * 1.0 / (BoxSize * 1e-3)**3 #galaxies/(Mpc/h)^3 if (np.absolute( (mean_density - fiducial_density) / fiducial_density) < thres): i = max_iterations elif (mean_density > fiducial_density): Mmin1 = Mmin else: Mmin2 = Mmin i += 1 if verbose: print(' ') print('Mmin=', Mmin) print('average number of galaxies=', total_galaxies) print('average galaxy density=', mean_density) ######################################### #just halos with M>Mmin; the rest do not host central/satellite galaxies inside = np.where(halo_mass > Mmin)[0] halo_mass = halo_mass[inside] halo_pos = halo_pos[inside] halo_radius = halo_radius[inside] halo_len = halo_len[inside] halo_offset = halo_offset[inside] del inside #compute number of satellites in each halo using the Poisson distribution N_mean_sat = (halo_mass / M1)**alpha #mean number of satellites N_sat = np.empty(len(N_mean_sat), dtype=np.int32) for i in range(len(N_sat)): N_sat[i] = np.random.poisson(N_mean_sat[i]) N_tot = np.sum(N_sat) + len( halo_mass) #total number of galaxies in the catalogue if verbose: print(' ') print(np.min(halo_mass), '< M_halo <', np.max(halo_mass)) print('total number of galaxies=', N_tot) print('galaxy number density=', N_tot / (BoxSize * 1e-3)**3) #put satellites following the distribution of dark matter in groups if verbose: print(' ') print('Creating mock catalogue ...', ) pos_galaxies = np.empty((N_tot, 3), dtype=np.float32) #index: variable that go through halos (may be several galaxies in a halo) #i: variable that go through all (central/satellites) galaxies #count: find number of galaxies that lie beyond its host halo virial radius index = 0 count = 0 i = 0 while (index < halo_mass.shape[0]): position = halo_pos[index] #position of the DM halo radius = halo_radius[index] #radius of the DM halo #save the position of the central galaxy pos_galaxies[i] = position i += 1 #if halo contains satellites, save their positions Nsat = N_sat[index] if Nsat > 0: offset = halo_offset[index] length = halo_len[index] idss = sorted_ids[IDs[offset:offset + length]] #compute the distances to the halo center keeping those with R<Rvir pos = DM_pos[ idss] #positions of the particles belonging to the halo posc = pos - position #this is to populate correctly halos closer to box boundaries if np.any((position + radius > BoxSize) + (position - radius < 0.0)): inside = np.where(posc[:, 0] > BoxSize / 2.0)[0] posc[inside, 0] -= BoxSize inside = np.where(posc[:, 0] < -BoxSize / 2.0)[0] posc[inside, 0] += BoxSize inside = np.where(posc[:, 1] > BoxSize / 2.0)[0] posc[inside, 1] -= BoxSize inside = np.where(posc[:, 1] < -BoxSize / 2.0)[0] posc[inside, 1] += BoxSize inside = np.where(posc[:, 2] > BoxSize / 2.0)[0] posc[inside, 2] -= BoxSize inside = np.where(posc[:, 2] < -BoxSize / 2.0)[0] posc[inside, 2] += BoxSize radii = np.sqrt(posc[:, 0]**2 + posc[:, 1]**2 + posc[:, 2]**2) inside = np.where(radii < radius)[0] selected = random.sample(inside, Nsat) pos = pos[selected] #aditional, not esential check. Can be comment out posc = pos - position if np.any((posc > BoxSize / 2.0) + (posc < -BoxSize / 2.0)): inside = np.where(posc[:, 0] > BoxSize / 2.0)[0] posc[inside, 0] -= BoxSize inside = np.where(posc[:, 0] < -BoxSize / 2.0)[0] posc[inside, 0] += BoxSize inside = np.where(posc[:, 1] > BoxSize / 2.0)[0] posc[inside, 1] -= BoxSize inside = np.where(posc[:, 1] < -BoxSize / 2.0)[0] posc[inside, 1] += BoxSize inside = np.where(posc[:, 2] > BoxSize / 2.0)[0] posc[inside, 2] -= BoxSize inside = np.where(posc[:, 2] < -BoxSize / 2.0)[0] posc[inside, 2] += BoxSize r_max = np.max( np.sqrt(posc[:, 0]**2 + posc[:, 1]**2 + posc[:, 2]**2)) if r_max > radius: #check no particles beyond Rv selected print(position) print(radius) print(pos) count += 1 for j in range(Nsat): pos_galaxies[i] = pos[j] i += 1 index += 1 if verbose: print('done') #some final checks if i != N_tot: print('some galaxies missing:') print('register', i, 'galaxies out of', N_tot) if count > 0: print('error:', count, 'particles beyond the virial radius selected') return pos_galaxies
def illustris_HI_assignment(snapshot_fname, groups_fname, groups_number, Np_halo=100, long_ids_flag=True): print '\n. . reading the snapshot header . .' #read snapshot header and obtain BoxSize, redshift and h head = readsnap.snapshot_header(snapshot_fname) BoxSize = head.boxsize / 1e3 #Mpc/h Nall = head.nall redshift = head.redshift mass_DMparticle = head.massarr[1] * 1e10 #Msun/h h = head.hubble del head #find the total number of particles in the simulation Ntotal = np.sum(Nall, dtype=np.int64) print 'Total number of particles in the simulation: %d' % Ntotal #read FoF halos information halos = readfof.FoF_catalog(groups_fname, groups_number, long_ids=long_ids_flag, swap=False) pos_FoF = halos.GroupPos / 1e3 #Mpc/h M_FoF = halos.GroupMass * 1e10 #Msun/h ID_FoF = halos.GroupIDs - 1 #normalize IDs Len = halos.GroupLen #number of particles in the halo Offset = halos.GroupOffset #offset of the halo in the ID array del halos #some verbose print 'Number of FoF halos:', len(pos_FoF), len(M_FoF) print '%f < X [Mpc/h] < %f' % (np.min(pos_FoF[:, 0]), np.max(pos_FoF[:, 0])) print '%f < Y [Mpc/h] < %f' % (np.min(pos_FoF[:, 1]), np.max(pos_FoF[:, 1])) print '%f < Z [Mpc/h] < %f' % (np.min(pos_FoF[:, 2]), np.max(pos_FoF[:, 2])) print '%e < M [Msun/h] < %e\n' % (np.min(M_FoF), np.max(M_FoF)) del pos_FoF #compute the total mass in halos from the halo catalogue print 'Total contributing mass from the catalogue = %e Msun/h'\ %(np.sum(M_FoF,dtype=np.float64)) print '. . considering halos with at least ' + str( Np_halo) + ' particles . . ' # cutting catalogue to halos with at least 100 particles mass_100p = mass_DMparticle * Np_halo indeces = np.where(M_FoF > mass_100p)[0] M_FoF = M_FoF[indeces] del indeces #compute the total mass in halos from the halo catalogue print 'Total contributing mass from the catalogue = %e Msun/h'\ %(np.sum(M_FoF,dtype=np.float64)) print 'Number of FoF halos:', len(M_FoF), '\n' print '%e < M [Msun/h] < %e' % (np.min(M_FoF), np.max(M_FoF)) print str(Np_halo) + '* the DM particle mass = %e [Msun/h]\n' % ( mass_DMparticle * Np_halo) # compute the values of M_HI(M_halo) function # see eq.13 of Villaescusa-Navarro et al. 2018 print '\nParameters for M_HI(M_halo) function:' print ' M_0 (z=%2.1f) = %2.2e Msun/h' % (redshift, M0_illustris(redshift)) print ' M_min (z=%2.1f) = %2.2e Msun/h' % (redshift, Mmin_illustris(redshift)) print ' alpha (z=%2.1f) = %1.2f\n' % (redshift, alpha_illustris(redshift)) #define the IDs array if long_ids_flag: IDs = np.empty(len(ID_FoF), dtype=np.uint64) else: IDs = np.empty(len(ID_FoF), dtype=np.uint32) #loop over the halos containing HI and assign the HI to the particles M_HI = np.zeros(Ntotal, dtype=np.float32) No_gas_halos = 0 IDs_offset = 0 for index in range(len(M_FoF)): #select the IDs of all particles belonging to the halo indexes = ID_FoF[Offset[index]:Offset[index] + Len[index]] #fill the IDs array IDs[IDs_offset:IDs_offset + len(indexes)] = indexes IDs_offset += len(indexes) #compute the total HI mass within the dark matter halo M_HI_halo = MHI_illustris(M_FoF[index], redshift) #if there are gas particles assign the HI to them Num_gas = len(indexes) if Num_gas > 0: M_HI[indexes] += (M_HI_halo * 1.0 / Num_gas) else: No_gas_halos += 1 print '\nNumber of halos with no gas particles=', No_gas_halos #just keep the IDs of the particles to which HI has been assigned IDs = IDs[0:IDs_offset] #compute the value of OmegaHI OmegaHI = np.sum(M_HI, dtype=np.float64) / BoxSize**3 / rho_crit print '\nOmega_HI (halos) = %e\n' % (OmegaHI) return OmegaHI, IDs, M_HI
def getG3power(sim, kmax): ## Get desired redshift if z == 99: snap = sim + "/output/ics" elif z == 49: snap = sim + "/output/snapdir_000/PART_000" elif z == 9: snap = sim + "/output/snapdir_001/PART_001" elif z == 4: snap = sim + "/output/snapdir_002/PART_002" elif z == 3: snap = sim + "/output/snapdir_003/PART_003" elif z == 2: snap = sim + "/output/snapdir_005/PART_005" else: print("Don't have data for that redshift") quit() head = readsnap.snapshot_header(snap) rho_crit = 2.77536627e11 BoxSize = head.boxsize / 1e3 #Mpc/h Nall = head.nall Masses = head.massarr * 1e10 #Msun/h Omega_m = head.omega_m Omega_l = head.omega_l redshift = head.redshift ## Pylian params grid = 256 ptypes = [1] MAS = 'CIC' do_RSD = False axis = 0 threads = 1 assert (z - redshift) < 0.001, "Redshift requested: %s, redshift found: %s" % ( z, redshift) Omega_cdm = Nall[1] * Masses[1] / BoxSize**3 / rho_crit Omega_b = Omega_m - Omega_cdm ## Calculate fractions f_b = Omega_b / (Omega_cdm + Omega_b) f_c = Omega_cdm / (Omega_cdm + Omega_b) ## CDM delta = MASL.density_field_gadget(snap, ptypes, grid, MAS, do_RSD, axis) delta /= np.mean(delta, dtype=np.float64) delta -= 1.0 print("Mean after normalising = %.2e" % np.mean(delta, dtype=np.float64)) Pk = PKL.Pk(delta, BoxSize, axis, MAS, threads) # Calculate power k_sim = Pk.k3D Pk_sim = Pk.Pk[:, 0] Nmodes1D = Pk.Nmodes1D ## Baryons deltaby = MASL.density_field_gadget(snap, [0], grid, MAS, do_RSD, axis) deltaby /= np.mean(deltaby, dtype=np.float64) deltaby -= 1.0 print("Mean after normalising = %.2e" % np.mean(delta, dtype=np.float64)) Pkby = PKL.Pk(deltaby, BoxSize, axis, MAS, threads) # Calculate power k_simby = Pkby.k3D Pk_simby = Pkby.Pk[:, 0] Nmodes1D = Pk.Nmodes1D ## Make sure we can find total matter assert (np.mean(k_simby - k_sim) ) == 0.0, "k-arrays not equal, can't find total matter power" Pk_av = Pk_sim * f_c**2 + Pk_simby * f_b**2 + 2 * f_c * f_b * np.sqrt( Pk_sim * Pk_simby) return k_sim[np.where(k_sim < kmax)], Pk_simby[np.where( k_sim < kmax)], Pk_sim[np.where(k_sim < kmax)], Pk_av[np.where( k_sim < kmax)], BoxSize
#################################### INPUT #################################### snapshot_fname = '../ics' bins = 100 #number of bins for the distribution # parameters for the FD distribution Mnu = 0.6 #eV h_planck = 6.582e-16 #eV*s kB = 8.617e-5 #eV/K c = 3e5 #km/s Tnu = 1.95 #K ############################################################################### ########## fraction from simulation ########### # read snapshot redshift and neutrino velocities z = readsnap.snapshot_header(snapshot_fname).redshift vel = readsnap.read_block(snapshot_fname,"VEL ",parttype=2) #km/s # compute velocity modulus V = np.sqrt(vel[:,0]**2 + vel[:,1]**2 + vel[:,2]**2); del vel # define the velocity intervals, their mean value and their widths vel_min, vel_max = np.min(V),np.max(V) if vel_min==0.0: vel_min = 1e-3 vel_intervals = np.logspace(np.log10(vel_min),np.log10(vel_max),bins+1) dV = vel_intervals[1:] - vel_intervals[:-1] #km/s V_mean = 0.5*(vel_intervals[1:] + vel_intervals[:-1]) #km/s # compute the franction of neutrinos within each velocity bin hist = (np.histogram(V,bins=vel_intervals)[0])*1.0/len(V) ###############################################
def compute_Pk(snapshot_fname, dims, do_RSD, axis, hydro): # read snapshot head and obtain BoxSize, Omega_m and Omega_L print '\nREADING SNAPSHOTS PROPERTIES' head = readsnap.snapshot_header(snapshot_fname) BoxSize = head.boxsize / 1e3 #Mpc/h Nall = head.nall Masses = head.massarr * 1e10 #Msun/h Omega_m = head.omega_m Omega_l = head.omega_l redshift = head.redshift Hubble = 100.0 * np.sqrt(Omega_m * (1.0 + redshift)**3 + Omega_l) #h*km/s/Mpc h = head.hubble z = '%.3f' % redshift f_out = 'Pk_m_z=' + z + '.dat' # compute the values of Omega_CDM and Omega_B Omega_cdm = Nall[1] * Masses[1] / BoxSize**3 / rho_crit Omega_nu = Nall[2] * Masses[2] / BoxSize**3 / rho_crit Omega_b = Omega_m - Omega_cdm - Omega_nu print '\nOmega_CDM = %.4f\nOmega_B = %0.4f\nOmega_NU = %.4f'\ %(Omega_cdm,Omega_b,Omega_nu) print 'Omega_M = %.4f' % (Omega_m) # read the positions of all the particles pos = readsnap.read_block(snapshot_fname, "POS ", parttype=-1) / 1e3 #Mpc/h print '%.3f < X [Mpc/h] < %.3f' % (np.min(pos[:, 0]), np.max(pos[:, 0])) print '%.3f < Y [Mpc/h] < %.3f' % (np.min(pos[:, 1]), np.max(pos[:, 1])) print '%.3f < Z [Mpc/h] < %.3f\n' % (np.min(pos[:, 2]), np.max(pos[:, 2])) if do_RSD: print 'moving particles to redshift-space' # read the velocities of all the particles vel = readsnap.read_block(snapshot_fname, "VEL ", parttype=-1) #km/s RSL.pos_redshift_space(pos, vel, BoxSize, Hubble, redshift, axis) del vel # read the masses of all the particles if not (hydro): Ntotal = np.sum(Nall, dtype=np.int64) #compute the number of particles M = np.zeros(Ntotal, dtype=np.float32) #define the mass array offset = 0 for ptype in [0, 1, 2, 3, 4, 5]: M[offset:offset + Nall[ptype]] = Masses[ptype] offset += Nall[ptype] else: M = readsnap.read_block(snapshot_fname, "MASS", parttype=-1) * 1e10 #Msun/h print '%.3e < M [Msun/h] < %.3e' % (np.min(M), np.max(M)) print 'Omega_M = %.4f\n' % (np.sum(M, dtype=np.float64) / rho_crit / BoxSize**3) # compute the mean mass per grid cell mean_M = np.sum(M, dtype=np.float64) / dims**3 # compute the mass within each grid cell delta = np.zeros(dims**3, dtype=np.float32) CIC.CIC_serial(pos, dims, BoxSize, delta, M) del pos print '%.6e should be equal to \n%.6e\n'\ %(np.sum(M,dtype=np.float64),np.sum(delta,dtype=np.float64)) del M # compute the density constrast within each grid cell delta /= mean_M delta -= 1.0 print '%.3e < delta < %.3e\n' % (np.min(delta), np.max(delta)) # compute the P(k) Pk = PSL.power_spectrum_given_delta(delta, dims, BoxSize) # write P(k) to output file np.savetxt(f_out, np.transpose([Pk[0], Pk[1]]))
# density field parameters grid = 768 MAS = 'PCS' # void finder parameters Radii = np.array([5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41], dtype=np.float32) threshold = -0.7 threads1 = 16 threads2 = 4 void_field = True ############################################################################## # read snapshot head and obtain BoxSize, Omega_m and Omega_L head = readsnap.snapshot_header(snapshot) BoxSize = head.boxsize/1e3 #Mpc/h Radii = Radii*BoxSize/grid # read particle positions pos = readsnap.read_block(snapshot,"POS ",parttype=1)/1e3 #Mpc/h # compute density field delta = np.zeros((grid, grid, grid), dtype=np.float32) MASL.MA(pos, delta, BoxSize, MAS) delta /= np.mean(delta, dtype=np.float64); delta -= 1.0 # find the void V = VL.void_finder(delta, BoxSize, threshold, Radii, threads1, threads2, void_field=void_field)