def get_DM_data(self): self.full_DM_mass = np.zeros(0) self.full_DM_pos = np.zeros([0,3]) self.full_DM_rho = np.zeros(0) DM_mass_512 = 7.33*10.**6./self.hubble DM_mass_256 = 5.86*10.**7./self.hubble DM_mass_128 = 4.69*10.**8./self.hubble for fnum in xrange(0,500): try: f=hdfsim.get_file(self.snap_num,self.snap_dir,fnum) except IOError: break bar=f["PartType1"] pos = AU.PhysicalPosition(np.array(bar["Coordinates"],dtype=np.float64),self.redshift,hubble=self.hubble) rho = AU.PhysicalDensity(np.array(bar["SubfindDensity"],dtype=np.float64),self.redshift,hubble=self.hubble) if self.res == 512: mass = np.ones_like(rho)*DM_mass_512 elif self.res == 256: mass = np.ones_like(rho)*DM_mass_256 elif self.res == 128: mass = np.ones_like(rho)*DM_mass_128 self.full_DM_mass = np.append(self.full_DM_mass,mass) self.full_DM_pos = np.append(self.full_DM_pos,pos,axis=0) self.full_DM_rho = np.append(self.full_DM_rho,rho) del bar f.close() del mass del pos del rho
def __init__(self,num, base, numlos, redmin, redmax, res = 5., cdir = None, savefile="nr_dla_spectra.hdf5", savedir=None, reload_file=True): #Get a sample of DLAs from the savefile dlas = spectra.Spectra(num, base, None, None, res, cdir, savefile="grid_spectra_DLA.hdf5",savedir=savedir) dla_cofm = dlas.cofm dla_axis = dlas.axis self.redmin = redmin self.redmax = redmax f = hdfsim.get_file(num, base, 0) self.OmegaM = f["Header"].attrs["Omega0"] self.box = f["Header"].attrs["BoxSize"] self.hubble = f["Header"].attrs["HubbleParam"] self.atime = f["Header"].attrs["Time"] f.close() self.NumLos = numlos #Sightlines at random positions #Re-seed for repeatability np.random.seed(23) select = np.random.randint(0,dlas.NumLos,numlos) cofm = np.concatenate((dla_cofm[select], dla_cofm[select])) axis = np.concatenate((dla_axis[select], dla_axis[select])) #Add a small perturbation to the sightline cofm axx = set([0,1,2]) rands = self.get_weighted_perp(numlos) for i in np.arange(0,numlos): ax = axx - set([axis[numlos+i]]) cofm[numlos+i, list(ax)] += rands[i,:] spectra.Spectra.__init__(self,num, base, cofm, axis, res, cdir, savefile=savefile,savedir=savedir,reload_file=reload_file) self.age = {}
def get_temp_overden_mass(num, base, snap_file=0): """Extract from a file the temperature, rho/rho_c and mass for each particle. Outputs: (templog, rho/rho_c, mass) """ f = hdfsim.get_file(num, base, snap_file) head = f["Header"].attrs npart = head["NumPart_ThisFile"] redshift = head["Redshift"] atime = head["Time"] h100 = head["HubbleParam"] if npart[0] == 0: print "No gas particles!\n" return # Baryon density parameter omegab0 = 0.0449 # Scaling factors and constants Xh = 0.76 # Hydrogen fraction G = 6.672e-11 # N m^2 kg^-2 kB = 1.3806e-23 # J K^-1 Mpc = 3.0856e22 # m kpc = 3.0856e19 # m Msun = 1.989e30 # kg mH = 1.672e-27 # kg H0 = 1.e5 / Mpc # 100 km s^-1 Mpc^-1 in SI units gamma = 5.0 / 3.0 rscale = (kpc * atime) / h100 # convert length to m #vscale = atime**0.5 # convert velocity to km s^-1 mscale = (1e10 * Msun) / h100 # convert mass to kg dscale = mscale / (rscale**3.0) # convert density to kg m^-3 escale = 1e6 # convert energy/unit mass to J kg^-1 bar = f["PartType0"] #u=escale*np.array(bar['InternalEnergy'],dtype=np.float64) # J kg^-1 met = np.array(bar['GFM_Metallicity'], dtype=np.float64) / 0.02 #solar ind2 = np.where(met < 1e-12) met[ind2] = 1e-12 rho = dscale * np.array(bar['Density'], dtype=np.float64) # kg m^-3, ,physical mass = np.array(bar['Masses'], dtype=np.float64) #1e10 Msun #nelec=np.array(bar['ElectronAbundance'],dtype=np.float64) #nH0=np.array(bar['NeutralHydrogenAbundance'],dtype=np.float64) f.close() # Convert to physical SI units. Only energy and density considered here. ## Mean molecular weight #mu = 1.0 / ((Xh * (0.75 + nelec)) + 0.25) #templog=np.log10(mu/kB * (gamma-1) * u * mH) ##### Critical matter/energy density at z=0.0 rhoc = 3 * (H0 * h100)**2 / (8. * math.pi * G) # kg m^-3 ##### Mean hydrogen density of the Universe nHc = rhoc / mH * omegab0 * Xh * (1. + redshift)**3.0 ### Hydrogen density as a fraction of the mean hydrogen density overden = np.log10(rho * Xh / mH / nHc) return (np.log10(met), overden, mass)
def omega_gas(self): """Compute Omega_gas, the sum of the hydrogen mass, divided by the critical density. """ mass = 0. kpchincm = 1. / (1 + self.redshift) self.protonmass = 1.67262178e-24 for files in np.arange(0, 500): try: ff = hdfsim.get_file(self.num, self.base, files) except IOError: break bar = ff["PartType0"] nH = self.gas.get_code_rhoH(bar) pvol = 4. / 3. * math.pi * (hsml.get_smooth_length(bar) * kpchincm)**3 #Total mass of H in g ind = np.where(nH < 0.1) mass += np.sum(nH[ind] * pvol[ind]) * protonmass #mass += np.sum(nH*pvol)*protonmass #Total volume of the box in comoving cm^3 volume = (self.box)**3 #Total mass of HI * m_p / r_c omega_g = mass / volume / self.rho_crit() return omega_g
def get_temp_overden_mass(num,base,snap_file=0): """Extract from a file the temperature, rho/rho_c and mass for each particle. Outputs: (templog, rho/rho_c, mass) """ f=hdfsim.get_file(num,base,snap_file) head=f["Header"].attrs npart=head["NumPart_ThisFile"] redshift=head["Redshift"] atime=head["Time"] h100=head["HubbleParam"] if npart[0] == 0 : print "No gas particles!\n" return # Baryon density parameter omegab0 = 0.0449 # Scaling factors and constants Xh = 0.76 # Hydrogen fraction G = 6.672e-11 # N m^2 kg^-2 kB = 1.3806e-23 # J K^-1 Mpc = 3.0856e22 # m kpc = 3.0856e19 # m Msun = 1.989e30 # kg mH = 1.672e-27 # kg H0 = 1.e5/Mpc # 100 km s^-1 Mpc^-1 in SI units gamma = 5.0/3.0 rscale = (kpc * atime)/h100 # convert length to m #vscale = atime**0.5 # convert velocity to km s^-1 mscale = (1e10 * Msun)/h100 # convert mass to kg dscale = mscale / (rscale**3.0) # convert density to kg m^-3 escale = 1e6 # convert energy/unit mass to J kg^-1 bar = f["PartType0"] #u=escale*np.array(bar['InternalEnergy'],dtype=np.float64) # J kg^-1 met = np.array(bar['GFM_Metallicity'], dtype=np.float64)/0.02 #solar ind2 = np.where(met < 1e-12) met[ind2] = 1e-12 rho=dscale*np.array(bar['Density'],dtype=np.float64) # kg m^-3, ,physical mass=np.array(bar['Masses'],dtype=np.float64) #1e10 Msun #nelec=np.array(bar['ElectronAbundance'],dtype=np.float64) #nH0=np.array(bar['NeutralHydrogenAbundance'],dtype=np.float64) f.close() # Convert to physical SI units. Only energy and density considered here. ## Mean molecular weight #mu = 1.0 / ((Xh * (0.75 + nelec)) + 0.25) #templog=np.log10(mu/kB * (gamma-1) * u * mH) ##### Critical matter/energy density at z=0.0 rhoc = 3 * (H0*h100)**2 / (8. * math.pi * G) # kg m^-3 ##### Mean hydrogen density of the Universe nHc = rhoc /mH * omegab0 *Xh * (1.+redshift)**3.0 ### Hydrogen density as a fraction of the mean hydrogen density overden = np.log10(rho*Xh/mH / nHc) return (np.log10(met),overden,mass)
def get_gas_data(self): self.full_gas_mass = np.zeros(0) self.full_gas_met = np.zeros(0) self.full_gas_pos = np.zeros([0,3]) self.full_gas_CIV_massfrac = np.zeros(0) self.full_gas_OVI_massfrac = np.zeros(0) for fnum in xrange(0,500): try: f=hdfsim.get_file(self.snap_num,self.snap_dir,fnum) except IOError: break bar=f["PartType0"] mass = AU.PhysicalMass(np.array(bar["Masses"],dtype=np.float64)) pos = AU.PhysicalPosition(np.array(bar["Coordinates"],dtype=np.float64),self.redshift,hubble=self.hubble) met = np.array(bar['GFM_Metallicity'],dtype=np.float64) metals = np.array(bar['GFM_Metals'],dtype=np.float64) rho_Hatoms = AU.PhysicalDensity(np.array(bar["Density"],dtype=np.float64),self.redshift,hubble=self.hubble)*(0.76/AU.ProtonMass) u=np.array(bar['InternalEnergy'],dtype=np.float64) nelec=np.array(bar['ElectronAbundance'],dtype=np.float64) T = AU.GetTemp(u, nelec, gamma = 5.0/3.0) T_cut = np.logical_and(np.log10(T) >= 3.,np.log10(T) <= 8.6) rho_cut = np.logical_and(np.log10(rho_Hatoms) >= -7.,np.log10(rho_Hatoms) <= 4.) cloudy_cut = np.logical_and(T_cut,rho_cut) mass = mass[cloudy_cut] pos = pos[cloudy_cut] met = met[cloudy_cut] metals = metals[cloudy_cut] rho_Hatoms = rho_Hatoms[cloudy_cut] T = T[cloudy_cut] CIV_massfrac = metals[:,2]*self.tab.ion("C",4,rho_Hatoms,T) OVI_massfrac = metals[:,4]*self.tab.ion("O",6,rho_Hatoms,T) del metals del rho_Hatoms del u del nelec del T self.full_gas_mass = np.append(self.full_gas_mass,mass) self.full_gas_pos = np.append(self.full_gas_pos,pos,axis=0) self.full_gas_met = np.append(self.full_gas_met,met) self.full_gas_CIV_massfrac = np.append(self.full_gas_CIV_massfrac,CIV_massfrac) self.full_gas_OVI_massfrac = np.append(self.full_gas_OVI_massfrac,OVI_massfrac) del bar f.close() del mass del pos del met del CIV_massfrac del OVI_massfrac
def __init__(self, num, base): """Plot various things with the cold gas fraction""" ff = hdfsim.get_file(num, base,0) self.redshift = ff["Header"].attrs["Redshift"] self.box = ff["Header"].attrs["BoxSize"] self.hubble = ff["Header"].attrs["HubbleParam"] ff.close() self.gas=cold_gas.RahmatiRT(self.redshift, self.hubble) #self.yaj=cold_gas.YajimaRT(self.redshift, self.hubble) self.num = num self.base = base
def load_header(self): """Load the header and halo data from a snapshot set""" #Simulation parameters f=hdfsim.get_file(self.snapnum,self.snap_dir,0) self.redshift=f["Header"].attrs["Redshift"] self.hubble=f["Header"].attrs["HubbleParam"] self.box=f["Header"].attrs["BoxSize"] self.npart=f["Header"].attrs["NumPart_Total"]+2**32*f["Header"].attrs["NumPart_Total_HighWord"] self.omegam=f["Header"].attrs["Omega0"] self.omegal=f["Header"].attrs["OmegaLambda"] f.close()
def __init__(self, num, base): """Plot various things with the cold gas fraction""" ff = hdfsim.get_file(num, base, 0) self.redshift = ff["Header"].attrs["Redshift"] self.box = ff["Header"].attrs["BoxSize"] self.hubble = ff["Header"].attrs["HubbleParam"] ff.close() self.gas = cold_gas.RahmatiRT(self.redshift, self.hubble) #self.yaj=cold_gas.YajimaRT(self.redshift, self.hubble) self.num = num self.base = base
def setup_test(molec, sim): """Setup the test case with a simulation""" name = myname.get_name(sim) f = hdfsim.get_file(3, name, 0) redshift = f["Header"].attrs["Redshift"] hubble = f["Header"].attrs["HubbleParam"] bar = f["PartType0"] cold = cold_gas.RahmatiRT(redshift, hubble, molec=molec) return (cold, bar)
def setup_test(molec,sim): """Setup the test case with a simulation""" name = myname.get_name(sim) f=hdfsim.get_file(3,name,0) redshift=f["Header"].attrs["Redshift"] hubble=f["Header"].attrs["HubbleParam"] bar = f["PartType0"] cold = cold_gas.RahmatiRT(redshift, hubble, molec=molec) return (cold, bar)
def __init__(self,snap_dir,snap_num,savename,res=512,met_vs_overdens=False): self.snap_dir = snap_dir self.snap_num = snap_num self.res = res self.savename = savename # Get basic parameters of snapshot f=hdfsim.get_file(self.snap_num,self.snap_dir,0) self.redshift=f["Header"].attrs["Redshift"] self.hubble=f["Header"].attrs["HubbleParam"] self.box=AU.PhysicalPosition(f["Header"].attrs["BoxSize"],self.redshift,hubble=self.hubble) self.omegam=f["Header"].attrs["Omega0"] print "redshift: ",self.redshift f.close() print "Getting DM quantities" ts = time.time() self.get_DM_data() self.calc_DM_meandens() print "time to get DM quantities: ",time.time()-ts ts = time.time() self.DM_tree = cKDTree(self.full_DM_pos,leafsize=10) print "time to make tree: ",time.time()-ts ts = time.time() self.tab = cc.CloudyTable(self.redshift) self.get_gas_data() print "time to get gas quantities: ",time.time()-ts # Find closest DM particle to each gas cell ts = time.time() [d,i] = self.DM_tree.query(self.full_gas_pos, k=1) print "time to get closest DM particles: ",time.time()-ts print "i ",i full_gas_DMrho = self.full_DM_rho[i] self.full_gas_overdens = (full_gas_DMrho - self.DM_mean_rho)/self.DM_mean_rho # this part saves total mass with overdens < different ranges #if not met_vs_overdens: #print "saving..." self.calc_od_mass() self.bin_od_met() savez_name = savebase + self.savename+"_od.npz" print "saving to ",savez_name np.savez(savez_name,overdens_binmin=self.overdens_binmin,overdens_binmax=self.overdens_binmax,met_mean=self.met_mean,met_sigma=self.met_sigma,od_arr=self.od_arr,mass_arr=self.mass_arr,met_arr=self.met_arr,CIV_arr=self.CIV_arr,OVI_arr=self.OVI_arr,DM_mass_total=self.DM_mass_total)
def get_temp_overden_volume(num, base, snap_file=0): """Extract from a file the cell radius, rho/rho_c and mass for each particle. Outputs: (radius, rho/rho_c, mass) """ f = hdfsim.get_file(num, base, snap_file) head = f["Header"].attrs npart = head["NumPart_ThisFile"] redshift = head["Redshift"] atime = head["Time"] h100 = head["HubbleParam"] if npart[0] == 0: print "No gas particles!\n" return # Baryon density parameter omegab0 = 0.0449 # Scaling factors and constants Xh = 0.76 # Hydrogen fraction G = 6.672e-11 # N m^2 kg^-2 Mpc = 3.0856e22 # m kpc = 3.0856e19 # m Msun = 1.989e30 # kg mH = 1.672e-27 # kg H0 = 1.e5 / Mpc # 100 km s^-1 Mpc^-1 in SI units rscale = (kpc * atime) / h100 # convert length to m mscale = (1e10 * Msun) / h100 # convert mass to kg dscale = mscale / (rscale**3.0) # convert density to kg m^-3 bar = f["PartType0"] rho = dscale * np.array(bar['Density'], dtype=np.float64) # kg m^-3, ,physical mass = np.array(bar['Masses'], dtype=np.float64) #nH0=np.array(bar['NeutralHydrogenAbundance'],dtype=np.float64) f.close() # Convert to physical SI units. Only energy and density considered here. ##### Critical matter/energy density at z=0.0 rhoc = 3 * (H0 * h100)**2 / (8. * math.pi * G) # kg m^-3 ##### Mean hydrogen density of the Universe nHc = rhoc / mH * omegab0 * Xh * (1. + redshift)**3.0 ### Hydrogen density as a fraction of the mean hydrogen density overden = np.log10(rho * Xh / mH / nHc) volume = dscale * mass / rho rad = (3 * volume / (4 * math.pi))**(1 / 3.) return (rad, overden, mass)
def get_temp_overden_volume(num,base,snap_file=0): """Extract from a file the cell radius, rho/rho_c and mass for each particle. Outputs: (radius, rho/rho_c, mass) """ f=hdfsim.get_file(num,base,snap_file) head=f["Header"].attrs npart=head["NumPart_ThisFile"] redshift=head["Redshift"] atime=head["Time"] h100=head["HubbleParam"] if npart[0] == 0 : print "No gas particles!\n" return # Baryon density parameter omegab0 = 0.0449 # Scaling factors and constants Xh = 0.76 # Hydrogen fraction G = 6.672e-11 # N m^2 kg^-2 Mpc = 3.0856e22 # m kpc = 3.0856e19 # m Msun = 1.989e30 # kg mH = 1.672e-27 # kg H0 = 1.e5/Mpc # 100 km s^-1 Mpc^-1 in SI units rscale = (kpc * atime)/h100 # convert length to m mscale = (1e10 * Msun)/h100 # convert mass to kg dscale = mscale / (rscale**3.0) # convert density to kg m^-3 bar = f["PartType0"] rho=dscale*np.array(bar['Density'],dtype=np.float64) # kg m^-3, ,physical mass=np.array(bar['Masses'],dtype=np.float64) #nH0=np.array(bar['NeutralHydrogenAbundance'],dtype=np.float64) f.close() # Convert to physical SI units. Only energy and density considered here. ##### Critical matter/energy density at z=0.0 rhoc = 3 * (H0*h100)**2 / (8. * math.pi * G) # kg m^-3 ##### Mean hydrogen density of the Universe nHc = rhoc /mH * omegab0 *Xh * (1.+redshift)**3.0 ### Hydrogen density as a fraction of the mean hydrogen density overden = np.log10(rho*Xh/mH / nHc) volume=dscale*mass/rho rad=(3*volume/(4*math.pi))**(1/3.) return (rad,overden,mass)
def plot_neutral_frac(self,files=0): """Plot the neutral fraction from both code and annalytic approx""" ff = hdfsim.get_file(self.num, self.base,files) bar = ff["PartType0"] nH = self.gas.get_code_rhoH(bar) nH0_code = self.gas.code_neutral_fraction(bar) nH0_rah = self.gas.get_reproc_HI(bar) bin_edges = 10**np.arange(-6,3,0.5) (cen,nH0_code_bin) = self.binned_nH(bin_edges, nH,nH0_code) #(cen,nH0_yaj_bin) = self.binned_nH(bin_edges, nH,nH0_yaj) (cen,nH0_rah_bin) = self.binned_nH(bin_edges, nH,nH0_rah) ff.close() plt.loglog(cen, nH0_code_bin, color="red", label="Arepo") plt.loglog(cen, nH0_rah_bin,color="blue", label="Rahmati fit")
def plot_neutral_frac(self, files=0): """Plot the neutral fraction from both code and annalytic approx""" ff = hdfsim.get_file(self.num, self.base, files) bar = ff["PartType0"] nH = self.gas.get_code_rhoH(bar) nH0_code = self.gas.code_neutral_fraction(bar) nH0_rah = self.gas.get_reproc_HI(bar) bin_edges = 10**np.arange(-6, 3, 0.5) (cen, nH0_code_bin) = self.binned_nH(bin_edges, nH, nH0_code) #(cen,nH0_yaj_bin) = self.binned_nH(bin_edges, nH,nH0_yaj) (cen, nH0_rah_bin) = self.binned_nH(bin_edges, nH, nH0_rah) ff.close() plt.loglog(cen, nH0_code_bin, color="red", label="Arepo") plt.loglog(cen, nH0_rah_bin, color="blue", label="Rahmati fit")
def set_nHI_grid(self): """Set up the grid around each halo where the velocity HI is calculated. """ star=cold_gas.RahmatiRT(self.redshift, self.hubble) self.once=True #This is the real HI grid nHI_grid=np.array([np.zeros([self.ngrid[i],self.ngrid[i]]) for i in xrange(0,self.nhalo)]) #Now grid the HI for each halo for fnum in xrange(0,500): try: f=hdfsim.get_file(self.snapnum,self.snap_dir,fnum) except IOError: break print "Starting file ",fnum bar=f["PartType0"] ipos=np.array(bar["Coordinates"],dtype=np.float64) smooth = hsml.get_smooth_length(bar) # Velocity in cm/s vel = np.array(bar["Velocities"],dtype=np.float64)*self.UnitVelocity_in_cm_per_s #We will weight by neutral mass per cell irhoH0 = star.get_reproc_rhoHI(bar) irho=np.array(bar["Density"],dtype=np.float64)*(self.UnitMass_in_g/self.UnitLength_in_cm**3)*self.hubble**2 #HI * Cell Mass, internal units mass = np.array(bar["Masses"],dtype=np.float64)*irhoH0/irho f.close() #Perform the grid interpolation #sub_gas_grid is x velocity #sub_nHI_grid is y velocity [self.sub_gridize_single_file(ii,ipos,smooth,vel[:,1]*mass,self.sub_gas_grid,vel[:,2]*mass,self.sub_nHI_grid,mass) for ii in xrange(0,self.nhalo)] #Find the HI density also, so that we can discard #velocities in cells that are not DLAs. [self.sub_gridize_single_file(ii,ipos,smooth,irhoH0,nHI_grid,np.zeros(np.size(irhoH0)),nHI_grid) for ii in xrange(0,self.nhalo)] #Explicitly delete some things. del ipos del irhoH0 del irho del smooth del mass del vel #No /= in list comprehensions... :| #Average over z for i in xrange(0,self.nhalo): self.sub_gas_grid[i]/=self.sub_radii[i] self.sub_nHI_grid[i]/=self.sub_radii[i] ind = np.where(nHI_grid[i] < 10**20.3) self.sub_nHI_grid[i][ind] = 0 self.sub_gas_grid[i][ind] = 0 return
def __init__(self,num, base, numlos=5000, res = 1., seed=23,cdir = None, dla=True, savefile="grid_spectra_DLA.hdf5", savedir=None, gridfile="boxhi_grid_H2.hdf5"): #Load halos to push lines through them f = hdfsim.get_file(num, base, 0) self.box = f["Header"].attrs["BoxSize"] f.close() if savedir == None: savedir = path.join(base,"snapdir_"+str(num).rjust(3,'0')) gridfile = path.join(savedir,gridfile) self.NumLos = numlos #All through y axis axis = np.ones(self.NumLos) #Load grid positions self.dlaind = self._load_dla_index(gridfile, dla) self.dlaval = self._load_dla_val(gridfile, dla) #Re-seed for repeatability np.random.seed(seed) cofm = self.get_cofm() vw_spectra.VWSpectra.__init__(self,num, base, cofm, axis, res, cdir, savefile=savefile,savedir=savedir, reload_file=True)
def omega_gas(self): """Compute Omega_gas, the sum of the hydrogen mass, divided by the critical density. """ mass = 0. kpchincm = 1./(1+self.redshift) self.protonmass=1.67262178e-24 for files in np.arange(0,500): try: ff = hdfsim.get_file(self.num, self.base,files) except IOError: break bar = ff["PartType0"] nH = self.gas.get_code_rhoH(bar) pvol = 4./3.*math.pi*(hsml.get_smooth_length(bar)*kpchincm)**3 #Total mass of H in g ind = np.where(nH < 0.1) mass += np.sum(nH[ind]*pvol[ind])*protonmass #mass += np.sum(nH*pvol)*protonmass #Total volume of the box in comoving cm^3 volume = (self.box)**3 #Total mass of HI * m_p / r_c omega_g=mass/volume/self.rho_crit() return omega_g
def get_gas_data(self): """ Get data we will be working with. """ # In this case, extract and aggregate data from all subfiles self.full_gas_mass = np.zeros(0) self.full_gas_pos = np.zeros([0,3]) self.full_gas_metals = np.zeros([0,9]) self.full_gas_metallicity = np.zeros(0) self.full_gas_vel = np.zeros([0,3]) self.full_gas_rho = np.zeros(0) self.full_gas_T = np.zeros(0) self.full_gas_hsml = np.zeros(0) self.full_gas_nelec = np.zeros(0) for fnum in xrange(0,500): try: f=hdfsim.get_file(self.snapnum,self.snap_dir,fnum) except IOError: break bar=f["PartType0"] # Extract gas data in physical units mass = AU.PhysicalMass(np.array(bar["Masses"],dtype=np.float64)) pos = AU.PhysicalPosition(np.array(bar["Coordinates"],dtype=np.float64),self.redshift,hubble=self.hubble) metals = np.array(bar['GFM_Metals'],dtype=np.float64) metallicity = np.array(bar['GFM_Metallicity'],dtype=np.float64) vel = AU.PeculiarVelocity(np.array(bar["Velocities"],dtype=np.float64),self.redshift) rho = AU.PhysicalDensity(np.array(bar["Density"],dtype=np.float64),self.redshift,hubble=self.hubble) #hsml = AU.PhysicalPosition(np.array(bar["SubfindHsml"],dtype=np.float64),self.redshift,hubble=self.hubble) # PROBLEM: this is much bigger than the hsml you get from taking the volume vol = AU.PhysicalVolume(np.array(bar["Volume"],dtype=np.float64),self.redshift,hubble=self.hubble) hsml = (3.*vol/4./np.pi)**(0.33333333) del vol u=np.array(bar['InternalEnergy'],dtype=np.float64) nelec=np.array(bar['ElectronAbundance'],dtype=np.float64) T = AU.GetTemp(u, nelec, gamma = 5.0/3.0) del u self.full_gas_mass = np.append(self.full_gas_mass,mass) self.full_gas_pos = np.append(self.full_gas_pos,pos,axis=0) self.full_gas_metals = np.append(self.full_gas_metals,metals,axis=0) self.full_gas_metallicity = np.append(self.full_gas_metallicity,metallicity) self.full_gas_vel = np.append(self.full_gas_vel,vel,axis=0) self.full_gas_rho = np.append(self.full_gas_rho,rho) self.full_gas_T = np.append(self.full_gas_T,T) self.full_gas_hsml = np.append(self.full_gas_hsml,hsml) self.full_gas_nelec = np.append(self.full_gas_nelec,nelec) del bar f.close() self.ngas = np.size(self.full_gas_mass) del mass del pos del metals del metallicity del vel del rho del T del hsml del nelec return
def generate_particle_haloflags(snap_dir,snapnum,cat): """ RETURNS: Array of flags for each particle, based on what halo the particle is bound to. Flag values: -2 if bound to some subhalo which is NOT a group main halo -1 if NOT bound to any subhalo N >= 0 if bound to the group main halo of group N INPUT: Subfind catalog """ # Get list of main halo ids: main_halo_ids = np.array(cat.GroupFirstSub) n_all_groups = np.float64(cat.ngroups) n_all_subs = np.float64(cat.nsubs) grp_ids = np.arange(n_all_groups) # Construct offset/length tables: [GroupOffset, HaloOffset] = constructtables(cat) GroupLenType = cat.GroupLenType SubhaloLenType = cat.SubhaloLenType totNGasCounted = 0. full_gas_flag = np.zeros(0) for fnum in xrange(0,500): try: f=hdfsim.get_file(snapnum,snap_dir,fnum) except IOError: break # This is crude, but I open the snapshot file to calculate how many gas particles are in it. bar=f["PartType0"] mass = np.array(bar["Masses"],dtype=np.float64) ngas = np.size(mass) del bar f.close() flag = np.ones(ngas) * -1 tempOffset = HaloOffset[:,0]-totNGasCounted tempLen = SubhaloLenType[:,0] for halo_num in np.arange(n_all_subs): if tempOffset[halo_num] <= 0: minindex = np.max([tempOffset[halo_num],0]) maxindex = np.max([tempOffset[halo_num]+tempLen[halo_num],0]) elif tempOffset[halo_num] > 0: minindex = np.min([tempOffset[halo_num],ngas-1]) maxindex = np.min([tempOffset[halo_num]+tempLen[halo_num],ngas-1]) # Index for this halo, for this partial file: index = np.int32(np.arange(minindex,maxindex)) # Check whether this is a main halo. If so, flag as N_group. If not, flag as -2 if halo_num in main_halo_ids: flag[index] = grp_ids[np.where(main_halo_ids == halo_num)][0] else: flag[index] = -2 full_gas_flag = np.append(full_gas_flag,flag) totNGasCounted += ngas return full_gas_flag
snapnum = 68 halonum = 1 cat = readsubfHDF5.subfind_catalog(base,snapnum,long_ids=True) GasFuzzOffset = cat.GroupFuzzOffsetType[:,0] start = GasFuzzOffset[halonum] end = GasFuzzOffset[halonum+1]-1 totngas = 0 for fnum in xrange(0,500): try: f=hdfsim.get_file(snapnum,base,fnum) except IOError: break NumPart_ThisFile = f["Header"].attrs["NumPart_ThisFile"][0] if totngas < start and totngas+NumPart_ThisFile > start: newstart = start - totngas newend = end - totngas bar=f["PartType0"] # Mass, Position, Metallicity of gas: #mass = np.array(bar["Masses"],dtype=np.float64) pos = np.array(bar["Coordinates"][newstart:newend],dtype=np.float64) #metallicity = np.array(bar['GFM_Metallicity'],dtype=np.float64)
def __init__(self,snap_dir,snapnum,savefile,group_min_mass=0,group_max_mass=10e16,rmin_pkpc=300,Rvir_min=1,load_savefile=False,BH_dat=True,fuzz_implemented=False): """ Initiate class Parameters: snap_dir - directory of snapshots snapnum - snapshot number savefile - where to save calculation output """ # Initiate variables self.snap_dir = snap_dir self.snapnum = snapnum self.savefile = savefile self.group_min_mass = group_min_mass self.group_max_mass = group_max_mass self.rmin_pkpc = rmin_pkpc self.Rvir_min = Rvir_min self.BH_dat = BH_dat #self.load_savefile = load_savefile #self.fuzz_implemented = fuzz_implemented if load_savefile: pass #self.load_savefile() else: ts = time.time() # Get basic parameters of snapshot f=hdfsim.get_file(snapnum,snap_dir,0) self.redshift=f["Header"].attrs["Redshift"] self.hubble=f["Header"].attrs["HubbleParam"] self.box=AU.PhysicalPosition(f["Header"].attrs["BoxSize"],self.redshift,hubble=self.hubble) self.omegam=f["Header"].attrs["Omega0"] self.omegal=f["Header"].attrs["OmegaLambda"] print "redshift: ",self.redshift f.close() # Other useful things: self.rho_barycrit = 0.0456*AU.GetRhoCrit0(hubble=self.hubble) self.tab = cc.CloudyTable(self.redshift) self.Hz = AU.CalcH_kms_over_Mpc(self.redshift, OmegaM=self.omegam, OmegaL=self.omegal, hubble=self.hubble) # Get group mass data so we can make a mass cut self.cat = readsubfHDF5.subfind_catalog(self.snap_dir,self.snapnum,long_ids=True) self.n_all_groups = np.float64(self.cat.ngroups) self.n_all_subs = np.float64(self.cat.nsubs) self.grp_ids = np.arange(self.n_all_groups) self.grp_mass = AU.PhysicalMass(np.array(self.cat.Group_M_Crit200),hubble=self.hubble) print "Total # of groups in snapshot: ",self.n_all_groups # Impose minimum halo mass cut and get additional group data: mass_select = np.logical_and(self.grp_mass > self.group_min_mass,self.grp_mass < self.group_max_mass) self.grp_ids = self.grp_ids[mass_select] self.grp_mass = self.grp_mass[mass_select] self.grp_pos = AU.PhysicalPosition(np.array(self.cat.GroupPos[mass_select]),self.redshift,hubble=self.hubble) self.grp_Rvir = AU.PhysicalPosition(np.array(self.cat.Group_R_Crit200[mass_select]),self.redshift,hubble=self.hubble) self.grp_vel = AU.PeculiarVelocity(np.array(self.cat.GroupVel[mass_select]),self.redshift) if self.BH_dat: self.grp_BHmass = AU.PhysicalMass(np.array(self.cat.GroupBHMass[mass_select]),hubble=self.hubble) self.grp_BHMdot = np.array(self.cat.GroupBHMdot[mass_select]) self.n_selected_groups = np.float64(np.size(self.grp_mass)) print "# of selected groups: ",self.n_selected_groups # Construct group/halo tables (assumes subfind-ordered snapshot) self.GroupOffset, self.HaloOffset = subfind_tables.constructtables(self.cat) self.GroupLenType = self.cat.GroupLenType self.SubhaloLenType = self.cat.SubhaloLenType print "Time for preamble: {}".format(time.time()-ts) # Get gas positions, masses, and metallicities for this subfile ts = time.time() self.get_gas_data() print "# of gas cells: ",self.ngas print "Time to get gas data: {}".format(time.time()-ts) # Generate kdtree for particle positions: self.gas_kdtree = cKDTree(self.full_gas_pos,leafsize=10) # Generate particle flag ts = time.time() self.full_gas_flag = subfind_tables.generate_particle_haloflags(self.snap_dir,self.snapnum,self.cat) print "Time to generate flags: {}".format(time.time()-ts) # Calculate background mass-weighted metallicity ts = time.time() self.metal_bg = self.calc_background_metallicity() print "background metallicity: ",self.metal_bg print "Time to calculate metal bg: {}".format(time.time()-ts) # Calculate enrichment radius for all groups self.extract_CGM_allhalos() self.save_data()