Example #1
0
def readsnapshot(snapshot, PATH='snapshotdata/snapdir_'):
    """ A program to read in gadget-2 snapshot data with filename 62.5_dm_XXX.k .

    :param snapshot: The number of the snapshot as a string (e.g. '001').
    :param PATH: The filepath to the snapshot data directory.

    :return: A list for each variable in the snapshot data no longer split
    into files, along with the relevant header data.
    """

    # Read in the header data and assign to variables
    head = readheader(PATH + snapshot + '/62.5_dm_' + snapshot, 'header')
    npart = head.get('npartTotal')[1]  # number of particles in snapshot
    z = head.get('redshift')  # redshift of snapshot
    t = head.get('time')  # time of snapshot (age)
    h = head.get('h')
    boxsize = head.get('boxsize')  # size of simulation box
    rhocrit = head.get('rhocrit')  # critical density at time t

    # Read in the snapshot data and assign to variable for returning
    pos = readsnap(PATH + snapshot + '/62.5_dm_' + snapshot, 'pos', 1)
    vel = readsnap(PATH + snapshot + '/62.5_dm_' + snapshot, 'vel', 1)
    pid = readsnap(PATH + snapshot + '/62.5_dm_' + snapshot, 'pid', 1)
    pmass = readsnap(PATH + snapshot + '/62.5_dm_' + snapshot, 'mass', 1)[0]

    return pid, pos, vel, npart, z, t, boxsize, rhocrit, pmass, h
Example #2
0
def snapHeader(basePath, snapNum, chunkNum=None):
    """
    Return snapshot header
    """

    if chunkNum is None:
        chunkNum = 0

    fname = snapPath(basePath, snapNum, chunkNum)
    header = pyg.readheader(fname, 'header')
    return header
Example #3
0
def down_sample(outpath, dmpath, DSF):
    #Create the directories to put the down-sampling output
    os.system("mkdir -p %s" % outpath + "/down_sampled_dm/")

    print "Down sampling on file: %s" % dmpath
    print "\tDSF = %d" % DSF

    Ndm = pgr.readheader(dmpath, "dmcount")
    Nds = Ndm / DSF

    DSpath = outpath + "/down_sampled_dm/down_sampled_dm_DSF%d" % DSF
    if os.path.exists(DSpath): print "Down sampled DM catalog already exists."
    else:
def get_starsnhalos(pathname,hnum,res,ver,snap_ind,xcen,ycen,zcen,rvir): #Simple function to get 2D scatter plots of star particles with circles to denote rvir of halos at z=0
  global conv
  for i in np.arange(8):
    fname = '/nobackup/afitts/Gadget-2.0.7/production/mfm%s%s_giz%s_raw_output/snapdir_184/snapshot_184.%d.hdf5'%(hnum,res,ver,i)
    bsize = pg.readheader(fname, 'boxsize')
    if bsize > 25: #mfm007 is in kpc while everything else (even gizdm007) is in Mpc. This standardizes all that.
      kfix = 1
    else:
      kfix = 1000
    a = h5py.File(fname,'r')
    if i == 0:
      pos = a['PartType4']['Coordinates']
      masstot = a['PartType4']['Masses']
    else:
      pos = np.vstack((pos,a['PartType4']['Coordinates']))
      masstot = np.concatenate((masstot,a['PartType4']['Masses']),0) 
  xtot = pos[:,0]/h* kfix
  ytot = pos[:,1]/h* kfix
  ztot = pos[:,2]/h* kfix
  for w in np.arange(16):
    temph = glob.glob(pathname+'analysis/ahf_snap%03d/ahf.snap_%03d.%04d.z*.*.AHF_halos'%(snap_ind,snap_ind,w))
    temph = str(temph).strip('[]').replace("'","")
    halo = np.loadtxt(temph,usecols=(0,3,5,6,7,11,64,63))
    for k in np.arange(len(halo)):
      halodiff = np.sqrt((xcen-halo[k,2]/h)**2+(ycen-halo[k,3]/h)**2+(zcen-halo[k,4]/h)**2)
      try:
       if halo[k,5] > 5 and halo[k,7]>10 and halodiff>20 and halodiff<100 or halodiff==0:# and halodiff<rvir or halodiff==0:
        ans = np.vstack((ans,(halo[k,1],halo[k,6])))
        x = np.append(x,halo[k,2]/h)
        y = np.append(y,halo[k,3]/h)
        z = np.append(z,halo[k,4]/h)
        rad = np.append(rad,halo[k,5]/h)
        bobob += halo[k,6]
	print halo[k,0], halo[k,1],halo[k,6]
      except:
       if halo[k,5] > 5 and halo[k,7]>10 and halodiff>20 and halodiff<100 or halodiff==0:#and halodiff<rvir or halodiff ==0:
        ans = np.array([[halo[k,1],halo[k,6]]])
        x = np.array([halo[k,2]])/h
        y = np.array([halo[k,3]])/h
        z = np.array([halo[k,4]])/h
        rad = np.array([halo[k,5]])/h
        bobob = halo[k,6]
	print halo[k,0], halo[k,1],halo[k,6]

  return xtot,ytot,ztot,x,y,z,rad 
def stellar_age(pathname,snum,main_part): #Add stellar creation time
  h0 = 71
  om_l = 0.734
  om_m = 0.266
  conv = 3.085677581e+19
  age = pg.readsnap(pathname+'snapdir_%03d/snapshot_%03d'%(snum,snum),'age','star')
  test = pg.readheader(pathname+'snapdir_%03d/snapshot_%03d'%(snum,snum),'time')
  print age[age>test]
  for i in np.arange(len(age)):
    age[i] = scipy.integrate.quad(_a_dot_recip, 0,age[i], (h0, om_m, om_l))[0]*conv
  test = scipy.integrate.quad(_a_dot_recip, 0,test, (h0, om_m, om_l))[0]*conv
  #age = np.array([age]) #So that we can easily take the transpose of age to concatenate with mass_progen
  pid = pg.readsnap(pathname+'snapdir_%03d/snapshot_%03d'%(snum,snum),'pid','star')
  bob = age[np.in1d(pid, main_part[:,0].astype('int'))]
  main_part[np.argsort(main_part[:,0].astype('int')),11] = bob[np.argsort(pid[np.in1d(pid, main_part[:,0].astype('int'))])]/3600/24/365/1e9
  #print main_part[np.argsort(main_part[:,0].astype('int')),0],main_part[np.argsort(main_part[:,0].astype('int')),11]
  #main_part[np.argsort(main_part[np.in1d(main_part[:,0].astype('int'),bob[:,0].astype('int')),0])= bob[np.argsort(bob[np.in1d(bob[:,0].astype('int'),bob[:,0].astype('int')),0])

  return main_part
 def find_simulation_properties(self):
     """
     This finds the attributes of the simulation such as
     side length, number of DM paticles, number of DM JK files,
     the redshift, the hubble constant.
     TODO: figure out the cosmology.
     """
     print "Reading the snapshot header."
     import pygadgetreader as pgr
     header = pgr.readheader(self.dm_files,"header")
     self.pgrheader = header
     self.particle_mass = max(header['massTable'])
     self.side_length = header['boxsize']
     self.dm_count = header['ndm']
     self.ndm_jks = header['nfiles']
     self.ndm_ndivs = int(round(self.ndm_jks**(1./3.)))
     self.redshift = header['redshift']
     self.hubble_const = header['h']
     print "\tSnapshot header read. Simulation properties saved."
     return
Example #7
0
import numpy as np
from matplotlib import rc
import pylab as plt
import sys
import struct
import pygadgetreader as pg
import random


def getRad(array):
    return pow(pow(array[0], 2) + pow(array[1], 2) + pow(array[2], 2), 0.5)


filename = "original_nfw"

nparts = pg.readheader(filename, "dmcount")
dmmass = pg.readsnap(filename, "mass", 'dm')[0]

bins = [0 + i / 5.0 for i in range(20)]

pos = pg.readsnap(filename, "pos", "dm")
vel = pg.readsnap(filename, "vel", "dm")

radii = []
vels = []
for i in range(nparts):
    radii.append(getRad(pos[i]))
    vels.append(getRad(vel[i]))

M = [0.0 for i in range(len(bins))]
N = [0 for i in range(len(bins))]
Example #8
0
import sys
import struct
import pygadgetreader as pg
import random
import math

infile = 'icsBIG_random'
outfile = 'cone_BIG'
with open(infile, mode='rb') as file:
	filecontent = file.read()
	file.close()

f=0
rbump=372.448
Mmove=8.2
N=pg.readheader(infile,"dmcount")
M=struct.unpack("dddddd",filecontent[28:28+8*6])[1]
Nmove=int(Mmove/M)
PPos=[]
PVel=[]
PID=[]
PMass=[]
for i in range(N):
	#Read Everything
	#The positions start at byte 268 (264-268 is an int 12*N)
	position=struct.unpack("fff",filecontent[268+12*i:268+12*i+12])
	PPos.append([p-1000.0 for p in position])
	#The velocities start at byte 276+12*N (8 previous bytes are 12*N, repeated twice)
	PVel.append(filecontent[276+12*N+12*i:276+12*N+12*i+12])
	#The particle IDs start at byte 284+24*N (8 previous bytes are 12*N then 4*N)
	PID.append(filecontent[284+24*N+4*i:284+24*N+4*i+4])
Example #9
0
def create_df(pathname,hist,hnum,dm):
  h0 = 71
  om_l = 0.734
  om_m = 0.266
  conv = 3.085677581e+19
  numcores = 16
  numsnaps = 185
  massp = 1.67262178e-24 #in grams
  gamma = 5./3.
  kb = 1.3806e-26 #in km^2*g/s^2
  for i in np.arange(len(hist)):
    print i
    if hist[184-i,1] != 0:
      switch = 0
      for j in np.arange(numcores): #Bring together all the AHF files for the snapshot
        temph = glob.glob(pathname+'analysis/ahf_snap%03d/ahf.snap_%03d.%04d.z*.*.AHF_halos'%(i,i,j))
        temph = str(temph).strip('[]').replace("'","")
        h = np.genfromtxt(temph)
        temppr = glob.glob(pathname+'analysis/ahf_snap%03d/ahf.snap_%03d.%04d.z*.*.AHF_profiles'%(i,i,j))
        temppr = str(temppr).strip('[]').replace("'","")
        p = np.genfromtxt(temppr)
        if switch == 0 and len(h) >0:
          halo = h
          switch = 1
        if switch == 1:
	  try:
            halo = np.vstack((halo,h))
          except:
	    print "nothing there"
      for j in np.arange(len(halo)): #Find our halo from all the halos of the snapshot
       try:
        if halo[j,0] == hist[184-i,1]:
          mvir = halo[j,3]/.71
	  vmax = halo[j,16]
          xcen = halo[j,5]/1000. #Grab relevant data (can always add more later)
          ycen = halo[j,6]/1000.
          zcen = halo[j,7]/1000.
          rvir = halo[j,11]/1000./.71
	  rmax = halo[j,12]/1000./.71
	  rhalf = 0
          sname = "%ssnapdir_%03d/snapshot_%03d"%(pathname,i,i)
	  bsize = pg.readheader(sname, 'boxsize')
	  if bsize > 25: #mfm007 is in kpc while everything else (even gizdm007) is in Mpc. This standardizes all that.
	    kfix = 1000
	  else:
	    kfix = 1
          red = pg.readheader(sname, 'redshift')
	  a = pg.readheader(sname, 'time')
          yr = scipy.integrate.quad(_a_dot_recip, 0,a, (h0, om_m, om_l))[0]*conv/(60*60*24*365*1e9)
	  dpid = pg.readsnap(sname, 'pid', 'dm')
          dmass = pg.readsnap(sname, 'mass', 'dm')*1.e10/.71
          dpos = pg.readsnap(sname, 'pos', 'dm')/kfix
	  dvel = pg.readsnap(sname, 'vel', 'dm')
          ddiff = np.sqrt((dpos[:,0]-xcen)**2+(dpos[:,1]-ycen)**2+(dpos[:,2]-zcen)**2)/.71
	  dpos = dpos[ddiff<rvir]
	  dvel = dvel[ddiff<rvir]
	  dmass = dmass[ddiff<rvir]
          dpid = dpid[ddiff<rvir]
	  ddiff = ddiff[ddiff<rvir]
	  rhalf = 0
	  hdf = pd.HDFStore('%sanalysis/dataframes/halo%s%s_giz%s_snap%03d.h5'%(pathname,hnum,res,ver,i))
	  hdf.put('particles/dm',pd.DataFrame(np.hstack((dpos,np.matrix(ddiff).T,np.matrix(dmass).T)), index = dpid, columns = (['x','y','z','r','mass'])))
	  if dm == 0:
            mstar = halo[j,64]/.71
            zarray = pg.readsnap(sname, 'zarray', 'gas')
            he_mf = zarray[:,1] #Helium mass fraction
            y_he = he_mf/(4*(1-he_mf))
            ne = pg.readsnap(sname, 'ne', 'gas') #Electron Abundance
            mu = (1+4*y_he)/(1+y_he+ne)
            mmw = mu*massp #mean molecular weight
            u = pg.readsnap(sname,'u','gas') #specific internal energy in km^2/s^2
            temp = mmw * (gamma-1.)*u/kb #temperature of gas
	    gpid = pg.readsnap(sname, 'pid', 'gas')
	    spid = pg.readsnap(sname, 'pid', 'star')
            gmass = pg.readsnap(sname, 'mass', 'gas')*1.e10/.71
            smass = pg.readsnap(sname, 'mass', 'star')*1.e10/.71
            gpos = pg.readsnap(sname, 'pos', 'gas')/kfix
            spos = pg.readsnap(sname, 'pos', 'star')/kfix
            gvel = pg.readsnap(sname, 'vel', 'gas')/kfix
            svel = pg.readsnap(sname, 'vel', 'star')/kfix
            sfr = pg.readsnap(sname, 'sfr', 'gas')
	    sft = pg.readsnap(sname, 'age', 'star')
            tmp = np.array([0,0])
	    gdiff = np.sqrt((gpos[:,0]-xcen)**2+(gpos[:,1]-ycen)**2+(gpos[:,2]-zcen)**2)/.71
            sdiff = np.sqrt((spos[:,0]-xcen)**2+(spos[:,1]-ycen)**2+(spos[:,2]-zcen)**2)/.71
	    gpos = gpos[gdiff<rvir]
	    gvel = gvel[gdiff<rvir]
	    gmass = gmass[gdiff<rvir]
	    temp = temp[gdiff<rvir]
	    sfr = sfr[gdiff<rvir]
            gpid = gpid[gdiff<rvir]
	    gdiff = gdiff[gdiff<rvir]
	    spos = spos[sdiff<rvir]
  	    svel = svel[sdiff<rvir]
	    smass = smass[sdiff<rvir]
	    sft = sft[sdiff<rvir]
            spid = spid[sdiff<rvir]
	    sdiff = sdiff[sdiff<rvir]
            sortsdiff = sdiff[np.argsort(sdiff)]
            cumsmass = np.cumsum(smass[np.argsort(sdiff)])
            q = 0
            print len(sortsdiff), mstar, max(cumsmass)
            while (cumsmass[q]<=mstar/2):
              rhalf = sortsdiff[q]
              q = q+1 
	    hdf.put('particles/gas',pd.DataFrame(np.hstack((gpos,np.matrix(gdiff).T,np.matrix(gmass).T,np.matrix(temp).T,np.matrix(sfr).T)), index = gpid, columns = (['x','y','z','r','mass','temp','sfr'])))
	    hdf.put('particles/star',pd.DataFrame(np.hstack((spos,np.matrix(sdiff).T,np.matrix(smass).T,np.matrix(sft).T)), index = spid, columns = (['x','y','z','r','mass','sft'])))
	  props = np.array([[xcen,ycen,zcen,rvir,rhalf,rmax,vmax,red,yr]])
	  hdf.put('props',pd.DataFrame(props,index = [halo[j,0]], columns = (['halox','haloy','haloz','rvir','rhalf','rmax','vmax','redshift','time'])))
	  hdf.close()

       except Exception,f:
          print f
	  props = np.array([[xcen,ycen,zcen,rvir,rhalf,rmax,vmax,red,yr]])
	  print halo[j,0], props
	  hdf = pd.HDFStore('%sanalysis/dataframes/halo%s%s_giz%s_snap%03d.h5'%(pathname,hnum,res,ver,i))
	  hdf.put('props',pd.DataFrame(props,index = [halo[j,0]], columns = (['halox','haloy','haloz','rvir','rhalf','rmax','vmax','redshift','time'])))
	  hdf.close()
          print "MISS"
Example #10
0
def radpro(pathname,sname,hist,dmo,rhalf,rmax):
  global i, grain, clr, count,conv
  numcores = 16
  massp = 1.67262178e-24 #in grams
  gamma = 5./3.
  kb = 1.3806e-26 #in km^2*g/s^2 
  G = 4.3e-6 #in kpc/M_sun (km/s)^2   
  switch = 0
  for j in np.arange(numcores): #Bring together all the AHF files for the snapshot
    temph = glob.glob(pathname+'ahf_snap%03d/ahf.snap_%03d.%04d.z*.*.AHF_halos'%(i,i,j)) 
    temph = str(temph).strip('[]').replace("'","")
    h = np.genfromtxt(temph)
    temppr = glob.glob(pathname+'ahf_snap%03d/ahf.snap_%03d.%04d.z*.*.AHF_profiles'%(i,i,j))
    temppr = str(temppr).strip('[]').replace("'","")
    p = np.genfromtxt(temppr)
    if switch == 0:
      halo = h
      switch = 1
    if switch == 1:
      try:
        halo = np.vstack((halo,h))
      except:
        print "nothing there"
  for j in np.arange(len(halo)): #Find our halo from all the halos of the snapshot
    if halo[j,0] == hist[184-i,1]:
      mstar = halo[j,64]
      mvir = halo[j,3]
      vmax = halo[j,16]
      xcen = halo[j,5] #Grab relevant data (can always add more later)
      ycen = halo[j,6]
      zcen = halo[j,7]
      rvir = halo[j,11]/.71
      bsize = pg.readheader(sname, 'boxsize')
      if bsize > 25: #mfm007 is in kpc while everything else (even gizdm007) is in Mpc. This standardizes all that.
        kfix = 1
      else:
	kfix = 1000
      mass = pg.readsnap(sname, 'mass', 'dm')*1.e10/.71
      pos = pg.readsnap(sname, 'pos', 'dm')*kfix
      tmp = np.array([0,0])
      diff = np.sqrt((pos[:,0]-xcen)**2+(pos[:,1]-ycen)**2+(pos[:,2]-zcen)**2)/.71
      mass = mass[diff<=rvir]
      diff = diff[diff<=rvir]
      cum = np.cumsum(mass[np.argsort(diff)])

      print xcen,ycen,zcen, rvir,pos
      binz = np.logspace(np.log10(.06),np.log10(rvir),grain)
      massall, bin_edge = np.histogram( diff,bins=binz, weights =mass) 
      x = 10**(np.log10(binz[1:])-np.log10(binz[1]/binz[0])/2)
      if dmo == 0:
        rmax = halo[j,12]/.71
        gmass = pg.readsnap(sname, 'mass', 'gas')*1.e10/.71
        smass = pg.readsnap(sname, 'mass', 'star')*1.e10/.71
        gpos = pg.readsnap(sname, 'pos', 'gas')*kfix
        spos = pg.readsnap(sname, 'pos', 'star')*kfix
        sdiff = np.sqrt((spos[:,0]-xcen)**2+(spos[:,1]-ycen)**2+(spos[:,2]-zcen)**2)/.71
        gdiff = np.sqrt((gpos[:,0]-xcen)**2+(gpos[:,1]-ycen)**2+(gpos[:,2]-zcen)**2)/.71
	smass = smass[sdiff<=rvir]
	gmass = gmass[gdiff<=rvir]
	sdiff = sdiff[sdiff<=rvir]
	gdiff = gdiff[gdiff<=rvir]
	scum = np.cumsum(smass[np.argsort(sdiff)])
	gcum = np.cumsum(gmass[np.argsort(gdiff)])
	totdiff = np.append(np.append(diff,sdiff),gdiff)
	totmass = np.append(np.append(mass,smass),gmass)
	totcum = np.cumsum(totmass[np.argsort(totdiff)])
	irhalf = abs(scum-sum(smass)/2).argmin()
	rhalf = sdiff[np.argsort(sdiff)][irhalf]
	itotrhalf = abs(np.sort(totdiff)-rhalf).argmin()
	print 'rhalf is %f'%rhalf
	irmax = np.sqrt(G*totcum/np.sort(totdiff)).argmax()
	rmax = totdiff[np.argsort(totdiff)][irmax]
	print 'rmax is %f'%rmax


	#print len(sdiff), binz, len(smass)
        gmassall, bin_edge = np.histogram( gdiff,bins=binz, weights =gmass) 
        smassall, bin_edge = np.histogram( sdiff,bins=binz, weights =smass)
	#irhalf = (abs(bin_edge-max(bin_edge[np.cumsum(smassall)<=sum(smassall)/2]))).argmin()

        #print bin_edge[np.cumsum(smassall)<=sum(smassall)/2],rvir,sum(smassall)#sum(smassall), np.cumsum(smassall) #x[irhalf],np.sqrt(G*sum(massall[:irhalf+1])/x[irhalf])
        ax1.scatter(rhalf,np.sqrt(G*totcum[itotrhalf]/rhalf),marker='s',s = 80,color='%s'%clr[count],label='%s'%(hnum[w]))
        #ax1.scatter(rmax,np.sqrt(G*totcum[irmax]/rmax),marker='D',s = 80,color='%s'%clr[count],label='%s Rmax'%(hnum))
        return massall, gmassall, smassall, x, rhalf,rmax
      else:
        massall = 0.83120300751*massall
	irhalf = (abs(np.sort(diff)-rhalf)).argmin()
	irmax = (abs(np.sort(diff)-rmax)).argmin()
	print np.sqrt(G*cum[irhalf]/rhalf), np.sqrt(G*cum[irmax]/rmax)
	ax1.scatter(rhalf,np.sqrt(G*cum[irhalf]/rhalf),marker='^',s = 80,color='%s'%clr[count],label='%s DMO'%(hnum[w]))
	#ax1.scatter(rmax,np.sqrt(G*cum[irmax]/rmax),marker='v',s = 80,color='%s'%clr[count],label='%s DMO Rmax'%(hnum))
        count +=1
        return massall, x
def gather_particles(main_progen,pathname,snum,hnum,fnum): #Use progenitors array to gather all their star particles in AHF particle files into the main particle array (now we have each particles' ID, position, velocity and whether they were part of the main progenitor or from a merger)

  global switch
  h0 = 71
  om_l = 0.734
  om_m = 0.266
  conv = 3.085677581e+19
  fix = 1
  mainhaloid, mainprogenid, progen = gather_progen(pathname,snum,hnum)
  my_cols = ['id', 'type', 'x', 'y', 'z', 'vx', 'vy', 'vz']
  for i in np.arange(fnum):
    temp = glob.glob(pathname+'analysis/ahf_snap%03d/ahf.snap_%03d.%04d.z*.*.AHF_particles'%(snum-1,snum-1,i))
    temp = str(temp).strip('[]').replace("'","")
    prev_particles = pd.read_csv(temp, names=my_cols, sep='\t')
    prev_particles['main'] = pd.Series(2*np.ones(len(prev_particles)),index=prev_particles.index) # append a new column that denotes whether the particle is in the main halo (1), is from a merger(0) or is undetermined (2). 
    prev_particles['r_form'] = pd.Series(np.zeros(len(prev_particles)),index=prev_particles.index)
    prev_particles['atime'] = pd.Series(np.zeros(len(prev_particles)),index=prev_particles.index)
    prev_particles['ctime'] = pd.Series(np.zeros(len(prev_particles)),index=prev_particles.index)
    prev_particles['mass'] = pd.Series(np.zeros(len(prev_particles)),index=prev_particles.index)

    for j,e in enumerate(prev_particles['id']): # Search through particle file to find instances where the first column contains two numbers (acts as a header for each halo). 
      if type(e)==types.StringType and len(e.split())==2 and (int(e.split()[1]) in progen)==True: # Make sure the halo id is in the progenitor array
        haloid = int(e.split()[1])# e.split()[0] is the number of particles, [1] is the halo ID
	numpart = int(e.split()[0])
	halostars =np.array(prev_particles.ix[j+1:j+numpart][prev_particles.ix[j+1:j+numpart,'type']==4])
	if len(halostars>0):
	  try:
	    if haloid == mainprogenid: #Main progenitor?
	      if switch == 0:
	        halostars[:,8] = 1
		halostars = formation_radius(pathname,snum,i,mainprogenid,halostars)
	        switch = 1
	      else:
	        halostars[np.logical_not(np.in1d(halostars[:,0].astype('int'),main_progen[:,0].astype('int'))),8] = 3 #Mark particles in halostars that arent in main_progen as 3.
	        main_progen[np.logical_not(np.in1d(main_progen[:,0].astype('int'),halostars[:,0].astype('int'))),8] = 3 # Mark particles in main_progen that arent in halostars as 3. This is just in case the main progenitor did not contribute ALL of its particles to the daughter.
	        hstar_und = halostars[:,8]==2 #Undetermined particles remaining in the halostars array (need their flags from main_progen) <---this might be overkill but its good to have regardless
	        main_need = main_progen[:,8]!=3 #Cuts out all the particles that did not participate in merger
	        halostars[np.argsort(halostars[hstar_und,0].astype('int')),8] = main_progen[np.argsort(main_progen[main_need,0].astype('int')),8]
		halostars[np.argsort(halostars[hstar_und,0].astype('int')),9] = main_progen[np.argsort(main_progen[main_need,0].astype('int')),9]
		halostars[np.argsort(halostars[hstar_und,0].astype('int')),10] = main_progen[np.argsort(main_progen[main_need,0].astype('int')),10]
		halostars[np.argsort(halostars[hstar_und,0].astype('int')),11] = main_progen[np.argsort(main_progen[main_need,0].astype('int')),11]
		halostars[np.argsort(halostars[hstar_und,0].astype('int')),12] = main_progen[np.argsort(main_progen[main_need,0].astype('int')),12]
	    else:# Then Merger.
	      halostars[:,8] = 0 #Now the last column becomes a zero to denote that the particle came from a merger MAY NEED TO EDIT THIS. CLEARLY THE COLUMNS ARE BEING PUT IN OUT OF ORDER.
	      atime = pg.readheader(pathname+'snapdir_%03d/snapshot_%03d'%(snum,snum),'time')
	      atime = scipy.integrate.quad(_a_dot_recip, 0,atime, (h0, om_m, om_l))[0]*conv/3600/24/365/1e9
	      halostars[:,10] =  atime# SET EQUAL TO ACCRETION TIME. ALTER C TIME TO 11 AND MASS FOR 12!!!!!
	    progen_part = np.vstack((progen_part, halostars)) #Add the id of particle, the type (only allow stars at this point), position, velocity and main or merger flag. 
	  except Exception,f:
            print f
	    if haloid == mainprogenid: 
	      if switch == 0:
	        halostars[:,8] = 1
		halostars = formation_radius(pathname,snum,i,mainprogenid,halostars)
	        switch = 1
	      else:
	        halostars[np.logical_not(np.in1d(halostars[:,0].astype('int'),main_progen[:,0].astype('int'))),8] = 3 
	        main_progen[np.logical_not(np.in1d(main_progen[:,0].astype('int'),halostars[:,0].astype('int'))),8] = 3
	        hstar_und = halostars[:,8]==2 #Undetermined particles remaining in the halostars array (need their flags from main_progen) <---this might be overkill but its good to have regardless
	        main_need = main_progen[:,8]!=3 #Cuts out all the particles that did not participate in merger
		if len(halostars[hstar_und])>0:
	          halostars[np.argsort(halostars[hstar_und,0].astype('int')),8] = main_progen[np.argsort(main_progen[main_need,0].astype('int')),8]
	    else:
	      halostars[:,8] = 0
	    progen_part = halostars
Example #12
0
import numpy as np
from matplotlib import rc
import pylab as plt
import sys
import struct
import pygadgetreader as pg
import random

original='icsMED'
outfile='icsMED_random'

with open(original, mode='rb') as file:
	filecontent = file.read()
	file.close()

N=pg.readheader(original,"dmcount")
print N
print struct.unpack("dddddd",filecontent[28:28+8*6])
head=filecontent[0:268]
PPos=[]
PVel=[]
PID=[]
PMass=[]
for i in range(N):
	#Read Everything
	#The positions start at byte 268 (264-268 is an int 12*N)
	PPos.append(filecontent[268+12*i:268+12*i+12])
	#The positions start at byte 276+12*N (8 previous bytes are 12*N, repeated twice)
	PVel.append(filecontent[276+12*N+12*i:276+12*N+12*i+12])
	#The particle IDs start at byte 284+24*N (8 previous bytes are 12*N then 4*N)
	PID.append(filecontent[284+24*N+4*i:284+24*N+4*i+4])
Example #13
0
import numpy as np
from matplotlib import rc
import pylab as plt
import sys
import struct
import pygadgetreader as pg
import random

with open('cube1e12', mode='rb') as file:
    filecontent = file.read()
    file.close()

f = 0
N = pg.readheader('cube1e12', "dmcount")
PPos = []
PVel = []
PID = []
PMass = []
for i in range(N):
    #Read Everything
    #The positions start at byte 268 (264-268 is an int 12*N)
    PPos.append(filecontent[268 + 12 * i:268 + 12 * i + 12])
    #The velocities start at byte 276+12*N (8 previous bytes are 12*N, repeated twice)
    PVel.append(filecontent[276 + 12 * N + 12 * i:276 + 12 * N + 12 * i + 12])
    #The particle IDs start at byte 284+24*N (8 previous bytes are 12*N then 4*N)
    PID.append(filecontent[284 + 24 * N + 4 * i:284 + 24 * N + 4 * i + 4])
    #This is followed by 4 bytes, 4*N. The particle mass array is not present in the file.
    #PMass.append(filecontent[280+28*N+4*i:280+28*N+4*i+4])

PPos2 = ''
PVel2 = ''
Example #14
0
        #add it to the lists
        #A key point to note is that the format of the file differs a bit from what's in the documentation. Each block (Header, Pos, Vel, Id) is bracketed by a 4-byte integer before and after equal to the number of bytes in that block. So the header, for example, does not go from 0-256, but rather 4-260, with 0-4 and 260-264 both being the integer 256. I can't find mention of this in the documentation.
        #The positions start at byte 268 (264-268 is an int 12*N)
        PPos = PPos + filecontent[268 + 12 * n:268 + 12 * n + 12]
        #The positions start at byte 276+12*N (8 previous bytes are 12*N, repeated twice)
        PVel = PVel + filecontent[276 + 12 * N[1] + 12 * n:276 + 12 * N[1] +
                                  12 * n + 12]
        #The particle IDs start at byte 284+24*N (8 previous bytes are 12*N then 4*N)
        PID = PID + filecontent[284 + 24 * N[1] + 4 * n:284 + 24 * N[1] +
                                4 * n + 4]
        #This is followed by 4 bytes, 4*N. The particle mass array is not present in the file.
        #PMass = PMass+filecontent[280+28*N[1]+4*n:280+28*N[1]+4*n+4]

    #Create the new file, packing up and concatenating all the data
    filecontentnew = filecontent[:4] + packN + packM + filecontent[
        76:100] + packN + filecontent[124:264] + struct.pack(
            'i', Ndm * 12) + PPos + struct.pack('i', Ndm * 12) + struct.pack(
                'i',
                Ndm * 12) + PVel + struct.pack('i', Ndm * 12) + struct.pack(
                    'i', Ndm * 4) + PID + struct.pack('i', Ndm * 4)

with open('output', mode='wb') as file:
    file.write(filecontentnew)
    file.close()

#This just checks to make sure the file completed correctly
filename = 'output'
print pg.readheader(filename, "dmcount")
print pg.readheader(filename, "starcount")
print pg.readsnap(filename, "mass", 'dm')[0]
Example #15
0
with open(infile, mode='rb') as file:
    filecontent = file.read()
    file.close()

#f is the SIDM fraction, Ndm is the total number of particles you want. This script takes the random NFW profile (as input) and makes half the dark matter particles non-interacting. It then adjusts the masses so as to give the desired SIDM fraction (by mass).
f = float(sys.argv[1])
Ndm = -1  #-1 for default (leave total number of particles unchanged). This removes the random sampling.

#This array lists the number of particles of each species
N = struct.unpack("iiiiii", filecontent[4:28])
print N

if (Ndm == -1):
    #This leaves the number of particles unchanged, and therefore we don't rely on the random sampling.
    Ndm = N[1]
    packN = struct.pack('iiiiii', 0, int(Ndm * 0.5), 0, 0,
                        Ndm - int(Ndm * 0.5), 0)
    M = struct.unpack("dddddd", filecontent[28:28 + 8 * 6])
    print M
    packM = struct.pack('dddddd', 0, 2 * f * M[1], 0, 0, 2 * (1 - f) * M[1], 0)
    filecontentnew = filecontent[:4] + packN + packM + filecontent[
        76:100] + packN + filecontent[124:]
with open(outfile, mode='wb') as file:
    file.write(filecontentnew)
    file.close()

#This just checks to make sure the file completed correctly
print pg.readheader(outfile, "dmcount")
print pg.readheader(outfile, "starcount")
print pg.readsnap(outfile, "mass", 'dm')[0]