Example #1
0
def test_snapshot_update() :
    f1 = pynbody.load("testdata/test_out.tipsy")
    f1['pos']
    f1['pos'] = np.arange(0,len(f1)*3).reshape(len(f1),3)
    
    # convert units -- the array should get written out in simulation units
    f1.g['pos'].convert_units('Mpc')

    f1['pos'].write(overwrite=True)
    f1.gas['metals'] = np.ones(len(f1.gas))*123.
    f1.star['metals'] = np.ones(len(f1.star))*345.

    f1.gas['metals'].write(overwrite=True)
    del f1

    f2 = pynbody.load("testdata/test_out.tipsy")
    assert (f2['pos']==np.arange(0,len(f2)*3).reshape(len(f2),3)).all()
    assert (f2.gas['metals']==123.).all() # should have updated gas.metals
    assert not (f2.star['metals']==345.).any() # should not have written out changes to star.metals

    # this is a completion:
    f2.dm['metals'] = np.ones(len(f2.dm))*789.1

    # should now be a simulation-level array... write it out
    f2['metals'].write(overwrite=True)

    del f2['metals']

    
    f3 = pynbody.load("testdata/test_out.tipsy")
    assert (f3.dm['metals']==789.1).all()
Example #2
0
def pbload(filename, paramname=None):
    """
    Loads a snapshot using pynbody.  Can load a single species by appending
    ::gas, ::star, or ::dm to the filename
    
    Parameters
    ----------
    
    filename : str
        Filename to load
    paramname : str
        (optional) .param file to use
    
    Returns
    -------
    
    sim : snapshot
        A pynbody snapshot
    """
    if '::' in filename:
        
        filename, species = filename.split('::')
        sim = pb.load(filename, paramname=paramname)
        sim = getattr(sim, species)
        
    else:
        
        sim = pb.load(filename, paramname=paramname)
        
    return sim
Example #3
0
def test_array_metadata() :
    f1 = pynbody.load("testdata/test_out.tipsy")
    
    f1.gas['zog'] = np.ones(len(f1.gas))
    f1.gas['zog'].units = "Msol kpc^-1"
    f1.gas['zog'].write()

    f1['banana'] = np.ones(len(f1))*0.5
    f1['banana'].units = "kpc^3 Myr^-1"
    f1['banana'].write()

    del f1

    f1 = pynbody.load("testdata/test_out.tipsy")
    assert "banana" in f1.loadable_keys()
    assert "zog" not in f1.loadable_keys()
    assert "banana" in f1.gas.loadable_keys()
    assert "zog" in f1.gas.loadable_keys()

    try:
        f1.star["zog"] # -> KeyError
        assert False # Shouldn't have been able to load gas-only array zog
    except KeyError :
        pass

    f1.gas['zog']
    assert f1.gas['zog'][0]==1.0
    assert f1.gas['zog'].units == "Msol kpc^-1"

    f1.star['banana']
    f1.gas['banana']
    f1.dm['banana']
    assert f1['banana'].units=="kpc^3 Myr^-1"
Example #4
0
def test_unit_persistence():
    f = pynbody.load("testdata/test_g2_snap")

    # f2 is the comparison case - just load the whole
    # position array and convert it, simple
    f2 = pynbody.load("testdata/test_g2_snap")
    f2['pos']
    f2.physical_units()

    f.gas['pos']
    f.physical_units()
    assert (f.gas['pos'] == f2.gas['pos']).all()

    # the following lazy-loads should lead to the data being
    # auto-converted
    f.dm['pos']
    assert (f.gas['pos'] == f2.gas['pos']).all()
    assert (f.dm['pos'] == f2.dm['pos']).all()

    # the final one is the tricky one because this will trigger
    # an array promotion and hence internally inconsistent units
    f.star['pos']

    assert (f.star['pos'] == f2.star['pos']).all()

    # also check it hasn't messed up the other bits of the array!
    assert (f.gas['pos'] == f2.gas['pos']).all()
    assert (f.dm['pos'] == f2.dm['pos']).all()

    assert (f['pos'] == f2['pos']).all()
Example #5
0
def test_fam_sim():
    """Check that an array loaded as families is the same as one loaded as a simulation array"""
    snap2 = pynbody.load("testdata/test_g2_snap")
    snap3 = pynbody.load("testdata/test_g2_snap")
    snap3.gas["pos"]
    snap3.dm["pos"]
    snap3.star["pos"]
    assert((snap3["pos"] == snap2["pos"]).all())
Example #6
0
def test_units_override():
    f = pynbody.load("testdata/test_g2_snap.0")
    assert_equals(f.filename, "testdata/test_g2_snap")  # final '.0' is stripped
    assert_equals(f['pos'].units, "kpc a h^-1")

    # In this case the unit override system is not effective because
    # the final ".1" is not stripped away in the filename:
    # the file `test_g2_snap.units` is not used
    f_no_unit_override = pynbody.load("testdata/test_g2_snap.1")
    assert_equals(f_no_unit_override.filename, "testdata/test_g2_snap.1")
    assert_equals(f_no_unit_override['pos'].units, "Mpc a h^-1")  # from default_config.ini
Example #7
0
def getAllDust(lowz,catfiles,Rv,A1600max=2.0,halonum=[1],filename='dust.pkl'):
	f = open(catfiles,'r')
	files = f.readlines()
	dustExt = {'halos':halonum,'Rhl':np.zeros((len(halonum),len(files)+1)),'RDhalf':np.zeros((len(halonum),len(files)+1)),'z':np.zeros(len(files)+1),'u':np.zeros((len(halonum),len(files)+1)),'b':np.zeros((len(halonum),len(files)+1)),'v':np.zeros((len(halonum),len(files)+1)),'r':np.zeros((len(halonum),len(files)+1)),'i':np.zeros((len(halonum),len(files)+1)),'j':np.zeros((len(halonum),len(files)+1)),'h':np.zeros((len(halonum),len(files)+1)),'k':np.zeros((len(halonum),len(files)+1))}
	slz = pynbody.load(lowz)
        lz = str(round(slz.properties['a']**-1 -1,3))
        catend = '.cat.z'+lz+'\n'
        for i in range(len(files)):
                print "calculating dust corrections for ", files[i].strip('\n')
                xx = files[i].find(catend)
                simname=files[i][0:xx]
                s = pynbody.load(simname)
                h = s.halos()
                dustExt['z'][i] = s.properties['a']**-1 -1
                s.physical_units()
                catf = open(files[i].strip('\n'))
                cat = pickle.load(catf)
                catf.close()
		for j in range(len(halonum)):
                        print "halo", halonum[j]
                        progs, = np.where(cat==halonum[j])
                        if len(progs)==0:
                                print "no progenitors found in this step!"
                                continue
                        main = progs[0]
                        print "progenitor", main
                        h1 = h[main]
			dust,Rhalf = dustCor(h1,s,Rv,A1600max=A1600max)
			dustExt['RDhalf'][j,i] = Rhalf
#			dustExt['Rhl'][j,i] = Rhl
			for key in dust.keys():
				dustExt[key][j,i] = dust[key]
		del(s)
                del(h)
                del(h1)
                del(cat)
                gc.collect()
	print "calculating values for final step"
        h = slz.halos()
        slz.physical_units()
        for j in range(len(halonum)):
                h1 = h[halonum[j]]
		dust,Rhalf= dustCor(h1,slz,Rv)
		dustExt['z'][i+1] = slz.properties['a']**-1 -1
		dustExt['RDhalf'][j,i+1] = Rhalf
		for key in dust.keys():
			dustExt[key][j,i+1] = dust[key]
	if filename:
                print "saving data..."
                f = open(filename,'wb')
                pickle.dump(dustExt,f)
                f.close()
	return dustExt
Example #8
0
def test_indexing():
    f1 = pynbody.load("testdata/g15784.lr.01024")

    test_len = 12310
    for test_len in [100, 10000, 20000]:
        for i in range(5):
            subindex = np.random.permutation(np.arange(0, len(f1)))[:test_len]
            subindex.sort()
            f2 = pynbody.load("testdata/g15784.lr.01024", take=subindex)

            assert (f2['x'] == f1[subindex]['x']).all()
            assert (f2['iord'] == f1[subindex]['iord']).all()
Example #9
0
def test_partial_loading() :
    f_f = pynbody.load("testdata/nchilada_test/12M.00001")
    
    test_ptcls = [ 11634,  24181,  26275,  37336,  37795,  38040,  38280,  38327,
        38524,  39349,  46758,  48892,  52160,  53267,  53745,  68970,
        78073,  83777,  86865,  93492,  94596,  96567,  99713, 106100,
       107856, 111036, 111830, 112560, 115082, 117111, 117444, 117667,
       123604, 123665, 124911, 132957, 138551, 154869, 158919, 182131,
       184252, 190498, 197946, 198288, 204526, 221720, 226375, 226915,
       229959, 231778] # randomly generated sample
    
    f_p = pynbody.load("testdata/nchilada_test/12M.00001", take = test_ptcls )

    assert((f_p['pos']==f_f['pos'][test_ptcls]).all())
Example #10
0
def test_mass_unit_sanity():
    """Picks up on problems with converting array units as
    mass array gets loaded (which is a combination of a derived
    array and a loaded array)"""

    f1 = pynbody.load("testdata/ramses_partial_output_00250")
    f1['mass']
    f1.physical_units()

    f2 = pynbody.load("testdata/ramses_partial_output_00250")
    f2.physical_units()
    f2['mass']

    np.testing.assert_allclose(f1.dm['mass'], f2.dm['mass'], atol=1e-5)
Example #11
0
def test_per_particle_loading():
    """Tests that loading one family at a time results in the
    same final array as loading all at once. There are a number of
    subtelties in the gadget handler that could mess this up by loading
    the wrong data."""

    f_all = pynbody.load("testdata/test_g2_snap")
    f_part = pynbody.load("testdata/test_g2_snap")

    f_part.dm['pos']
    f_part.star['pos']
    f_part.gas['pos']

    assert (f_all['pos'] == f_part['pos']).all()
Example #12
0
def haloCat(lowz,highz,nhalos=50):
	print "matching halo catalog from ", highz, "to ", lowz
	s1 = pynbody.load(highz)
	s2 = pynbody.load(lowz)
	if s1.properties['a'] > s2.properties['a']:
		print "uh oh! highz file must actually be at higher z!"
		return
	b = pynbody.bridge.OrderBridge(s1,s2)
	cat = b.match_catalog()
	filename = highz+'.cat.z'+str(round(s2.properties['a']**-1-1,3))
	f = open(filename,'wb')
	pickle.dump(cat,f)
	f.close()
	return
Example #13
0
def test_array_update():
    f1 = pynbody.load("testdata/test_out.tipsy")

    f1['bla'] = np.zeros(len(f1))
    f1['bla'].units = 'km'
    f1['bla'].write()

    del(f1['bla'])

    f1['bla']

    f1.g['bla'] = 1
    f1.d['bla'] = 2
    f1.s['bla'] = 3

    # test the case where bla is a snapshot-level array

    try:
        f1.g['bla'].write()
        assert False  # should not be allowed to overwrite here
    except IOError:
        pass

    f1.write_array(
        'bla', [pynbody.family.gas, pynbody.family.dm], overwrite=True)

    del(f1['bla'])

    f1['bla']

    assert all(f1.g['bla'] == 1)
    assert all(f1.d['bla'] == 2)
    assert all(f1.s['bla'] == 0)

    # test the case where bla2 is a family-level array

    f1.g['bla2'] = np.zeros(len(f1.g))
    f1.g['bla2'].units = 'km'
    f1.s['bla2'] = np.ones(len(f1.s))

    f1.write_array('bla2', [pynbody.family.gas, pynbody.family.star])

    del(f1)

    f1 = pynbody.load("testdata/test_out.tipsy")

    assert all(f1.g['bla2'] == 0)
    assert all(f1.s['bla2'] == 1)
Example #14
0
def haloprof_cumplot(tfile,halo_nums,halotype = 'all',normalize = False):
    vmax = 12
    min_vmass = 1e8
    f_bar = 0.16510
    Zyield = 0.02788242
    
    hfb = pynbody.load(tfile)
    h = hfb.halos()
    halo_data = pickle_read(tfile + ".data")

    for halo_num in halo_nums:        
        cmx = plt.get_cmap("viridis_r") 
        cNorm  = colors.Normalize(vmin=np.log10(min_vmass), vmax = vmax)
        scalarMap = cm.ScalarMappable(norm=cNorm, cmap=cmx)
        if (os.path.isfile(tfile + "_" + halo_num + "_halo" + ".data") == True):
            p_gas = pickle_read(tfile + "_" + halo_num + "_halo" + ".data")
            mass_norm = h[int(halo_num)].properties['mass']*f_bar
            Z_norm = np.sum(h[int(halo_num)].star['massform'].in_units('Msol'))*Zyield
            colorVal = scalarMap.to_rgba(np.log10(h[int(halo_num)].properties['mass']))
            if (halotype == 'all'):
                axs[0].plot(p_gas['rrvir'][0],p_gas['mass_enc'][0]/mass_norm, color = colorVal)
                axs[1].plot(p_gas['rrvir'][0],p_gas['metals_enc'][0]/Z_norm, color = colorVal)
                plt.show()
            else:
                if (len(halo_data[halo_data['haloid'] == halo_num]) > 0) :
                    if (float(halo_data[halo_data['haloid'] == halo_num]['SFR']) > 1e-4) and (halotype == 'sf'):
                        axs[0].plot(p_gas['rrvir'][0],p_gas['mass_enc'][0]/mass_norm, color = colorVal)
                        axs[1].plot(p_gas['rrvir'][0],p_gas['metals_enc'][0]/Z_norm, color = colorVal)
                        plt.show()
                    if (float(halo_data[halo_data['haloid'] == halo_num]['SFR']) < 1e-4) and (halotype == 'quenched'):
                        axs[0].plot(p_gas['rrvir'][0],p_gas['mass_enc'][0]/mass_norm, color = colorVal)
                        axs[1].plot(p_gas['rrvir'][0],p_gas['metals_enc'][0]/Z_norm, color = colorVal)
                        plt.show()    
Example #15
0
def test_float_kd():
    f = pynbody.load("testdata/test_g2_snap")
    del f.properties['boxsize']

    assert f.dm['mass'].dtype==f.dm['pos'].dtype==np.float32
    assert f.dm['smooth'].dtype==np.float32

    # make double copy
    g = pynbody.new(len(f.dm))
    g.dm['pos']=f.dm['pos']
    g.dm['mass']=f.dm['mass']

    assert g.dm['mass'].dtype==g.dm['pos'].dtype==g.dm['smooth'].dtype==np.float64

    # check smoothing lengths agree (they have been calculated differently
    # using floating/double routines)

    npt.assert_allclose(f.dm['smooth'],g.dm['smooth'],rtol=1e-4)
    npt.assert_allclose(f.dm['rho'],g.dm['rho'],rtol=1e-4)

    # check all combinations of float/double smoothing
    double_ar = np.ones(len(f.dm),dtype=np.float64)
    float_ar = np.ones(len(f.dm),dtype=np.float32)

    double_double = g.dm.kdtree.sph_mean(double_ar,32)
    double_float = g.dm.kdtree.sph_mean(float_ar,32)
    float_double = f.dm.kdtree.sph_mean(double_ar,32)
    float_float = f.dm.kdtree.sph_mean(float_ar,32)

    # take double-double as 'gold standard' (though of course if any of these
    # fail it could also be a problem with the double-double case)

    npt.assert_allclose(double_double,double_float,rtol=1e-4)
    npt.assert_allclose(double_double,float_double,rtol=1e-4)
    npt.assert_allclose(double_double,float_float,rtol=1e-4)
Example #16
0
def glassify(snapshot, shape, changaPreset='default', verbose=False, \
             fulloutput=False):
    """
    Glassifies a snapshot, saves the results to the default filename (see 
    sphglass.filenames()) and returns the snapshot.  snapshot can be a filename
    or a pynbody SimSnap
    """
    
    inFile, fPrefix = filenames()
    paramname = fPrefix + '.param'
    
    if not isinstance(snapshot, str):
        
        snapshot.write(filename=inFile, fmt=pynbody.tipsy.TipsySnap)
        snapshotName = inFile
        
    else:
        
        snapshotName = snapshot
        snapshot = pynbody.load(snapshotName)
        
    try:
        
        param = makeBoxParam(snapshot, shape, fulloutput)
        diskpy.utils.configsave(param, paramname, 'param')
        shutil.move(snapshotName, inFile)
        glass = reglassify(changaPreset, verbose, fulloutput)
        
    finally:
        
        shutil.move(inFile, snapshotName)
        
    return glass
Example #17
0
def test_array_unit_sanity() :
    """Picks up on problems with converting arrays as they
    get promoted from family to simulation level"""

    
    f.gas['pos']
    f.star['pos']
    f.dm['pos']
    f.physical_units()

    f2 = pynbody.load("testdata/ramses_partial_output_00250")
    f2.physical_units()
    f2.gas['pos']
    f2.dm['pos']
    f2.star['pos']
    
    
    
    
    print "OK for stars,gas,dm:"
    
    print close_enough(f2.star['pos'],f.star['pos']).all(), \
        close_enough(f2.gas['pos'],f.gas['pos']).all(), \
        close_enough(f2.dm['pos'],f.dm['pos']).all()
    
    assert close_enough(f2['pos'],f['pos']).all()
Example #18
0
def test_issue321():
    """L-PICOLA outputs single-precision with no mass block, which causes problems
    with testing kd-trees"""

    f = pynbody.load("testdata/lpicola/lpicola_z0p000.0")
    assert f['pos'].dtype==np.dtype('float32')
    assert f['mass'].dtype==np.dtype('float32')
Example #19
0
def test_alt_names():
    _h5py_copy_with_key_rename('testdata/Test_NOSN_NOZCOOL_L010N0128/data/snapshot_103/snap_103.hdf5',
                'testdata/Test_NOSN_NOZCOOL_L010N0128/data/snapshot_103/snap_103_altnames.hdf5')

    snap_alt = pynbody.load('testdata/Test_NOSN_NOZCOOL_L010N0128/data/snapshot_103/snap_103_altnames.hdf5')
    assert 'mass' in snap_alt.loadable_keys()
    assert all(snap_alt['mass']==snap['mass'])
Example #20
0
def load_center(output, align=True, halo=0):
    """
    Loads a RAMSES output and centers it on the desired halo. The hop
    center is used for an initial estimate, but for more precise
    centering, a shrinking-sphere center is calculated.

    **Inputs**:    
    
    *output* : path to RAMSES output directory

    **Optional Keywords**: 

    *align* : whether to align the snapshot based on the angular momentum in the central region (default = True)

    *halo* : halo to center on (default = 0)
    """


    s = pynbody.load(output)
    hop_center(s,halo)

    st = s[pynbody.filt.Sphere('100 kpc')]
    
    cen = pynbody.analysis.halo.center(st,retcen=True,mode='ssc',verbose=True)
    
    if align: 
        pynbody.analysis.angmom.faceon(st.s,disk_size='10 kpc',cen=cen,mode='ssc')
    else :
        s['pos'] -= cen

    s['pos'].convert_units('kpc')
    s['vel'].convert_units('km s^-1')

    return s
Example #21
0
	def gethalos(self):
		f = open('files.list', 'r')
		simfiles = f.readlines()
		nsnaps = len(simfiles)
		f.close()
		f = open('steps', 'r')
		snaps = f.readlines()
		f.close()
		initarr = np.ones((len(self.bhiords), len(snaps))) * -1
		self.bhhalos = {'Grp': initarr}
		for i in range(nsnaps):
			if os.path.exists(simfiles[i].strip('\n') + '.rockstar.grp'):
				grpfile = simfiles[i].strip('\n') + '.rockstar.grp'
			else:
				if os.path.exists(simfiles[i].strip('\n') + '.amiga.grp'):
					grpfile = simfiles[i].strip('\n') + '.amiga.grp'
				else:
					print "ERROR there is no grp file for this step!"
					continue
			sim = pynbody.load(simfiles[i].strip('\n'))
			simind = np.where(np.in1d(sim.stars['iord'], self.bhiords))
			orbind = np.where(np.inqd(self.bhiords, sim.stars['iord']))
			simind += len(sim.dm) + len(sim.gas)
			del sim['iord']
			gc.collect()
			grp = readcol(grpfile, skipline=1)
			self.bhhalos['Grp'][orbind][:, i] = grp[simind]
			del grp, simind, orbind
			gc.collect()
Example #22
0
def powerspectrum(f, mMax=30, rbins=50, paramname=None):
    """
    The density power spectrum along the angular direction, summed along the
    radial direction.
    
    Parameters
    ----------
    f : SimSnap or str
        Snapshot of a disk OR filename for snapshot
    mMax : int
        Maximum fourier mode to calculate
    rbins : int or array
        Number of radial bins or the binedges to use
        
    Returns
    -------
    
    m : array
        Array of the fourier modes from 0 to mMax (integers)
    power : array
        Power in the fourier modes, summed along radial direction.  Power is
        take to be the square of the surface density fourier transform
    """
    if isinstance(f, str):
        
        f = pynbody.load(f, paramname=paramname)
        
    r, m, sigtransform = sigmafft(f, rbins, 2*mMax + 1)
    m = m[0,:]
    power = (abs(sigtransform)**2).sum(0)
    
    return m, power
Example #23
0
def loadfiles(task):
#Load an individual simulation
    tbegin = time.clock()

    dirs,files,grp,finalstep = task
    tfile = dirs + files + '.' + finalstep + '/' + files + '.' + finalstep
    print(tfile + '.' + grp)
    s = pynbody.load(tfile)
    s.physical_units()
    print("simulation loaded")
    hs = s.halos()       
    h = hs[int(grp)]
    print("halos loaded")
    pynbody.analysis.halo.center(h,mode='com') #not as accurate as hyb but saves memory and time
    
    pynbody.analysis.angmom.sideon(h)
    print('halo aligned')
    hrvir = np.max(h.gas['r'])      
    #Read in iords of all particle that have been in the disk
    disk_iord_file = pyfits.open(dirs + 'grp' + grp + '.reaccrdisk_iord.fits')
    disk_iord = disk_iord_file[0].data
    indicies = np.in1d(s['iord'],disk_iord)
    disk_parts = s[np.nonzero(indicies)]
    #Make images
    outfilebase = dirs + files + '.grp' + grp
    print('Disk particles selected, now write to ' + outfilebase)
    outflowImages(s,disk_parts,hrvir,outfilebase)
    pltZvsR(disk_parts,hrvir,outfilebase)
    print 'Memory usage: %s (kb)' % resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
    tend = time.clock()
    print 'Time elapsed: %f ' % (float(tend) - float(tbegin))
Example #24
0
def read_full_orbit_file(filename, simname):
	f = open('files.list','r')
	files = f.readlines()
	s = pynbody.load(files[0].strip('\n'))
	f.close()
	a = None

	try:
		bhid, time, step, mass, x, y, z, vx, vy, vz, pot, mdot, dm, E, dt, a = readcol(filename, twod=False)
	except:
		bhid, time, step, mass, x, y, z, vx, vy, vz, pot, mdot, dm, E, dt = readcol(filename, twod=False)

	output = {'iord':bhid, 'time':time, 'step':step, 'mass':mass, 'x':x, 'y':y,
			  'z':z, 'vx':vx, 'vy':vy, 'vz':vz, 'pot':pot, 'mdot':mdot, 'dm':dm, 'E':E, 'dt':dt, 'a':a}
	if a is None:
		a, = cosmology.getScaleFactor(pynbody.array.SimArray(time,s.infer_original_units('Gyr')),s)
		output['a'] = a
	units = {'x':'kpc', 'y':'kpc', 'z':'kpc', 'vx':'km s**-1', 'vy':'km s**-1', 'vz':'km s**-1',
			 'mdot':'Msol yr**-1', 'dm':'Msol', 'dt':'Gyr', 'time':'Gyr', 'mass':'Msol'}

	for key in ['x', 'y', 'z', 'vx', 'vy', 'vz']:
		print "fixing scale factor for", key
		output[key] *= output['a']

	for key in units.keys():
		print "converting units for ", key
		origunit = s.infer_original_units(units[key])
		if key in ['x', 'y', 'z', 'vx', 'vy', 'vz']: origunit = origunit / pynbody.units.Unit('a')
		output[key] = pynbody.array.SimArray(output[key],origunit)
		output[key] = output[key].in_units(units[key])

	order = np.argsort(output['time'])
	util.cutdict(output,order)
	return output
Example #25
0
 def _LoadNewData(self, fluidtype):
     # Load data into pynbody
     print "STARTED LOADING DATA ", self._filename
     ro = self._snapdata
     if ro == None:
         try:
             ro=pynbody.load(self._filename)
         except:
             print "ABORTING LOADING (Opening snapshot failed - does this file exist?)"
             return
     if fluidtype == "stars":
         fluid = ro.stars
     elif fluidtype == "gas":
         fluid = ro.gas
     elif fluidtype == "dm":
         fluid = ro.dm
     else:
         print "Fluid type",fluidtype," not recognised! Use stars, gas or dm."
         raise TypeError
     posns = fluid["pos"]
     # No points?
     if len(posns) <= 1:
         print "ABORTING LOADING (No stars)"
         return
     smooth = fluid["smooth"]
     if not fluidtype == "gas":
         mass = fluid["mass"]
     else:
         mass = fluid["mass"]*fluid["temp"] # Hacky! Mmm. Basically display thermal energy in an element?
     if fluidtype == "dm":
         mass *= 0.1 # Artificially lower the brightness
     # Cut off background gas to save on rendering
     #if fluidtype == "gas":
     #    cutoff = 1e-3
     #    lim = mass > cutoff*np.max(mass)
     #    posns = posns[lim]
     #    smooth = smooth[lim]
     #    mass = mass[lim]
     # Process lengths to fit screen
     rescalepoints = True
     if rescalepoints:
         pmin, pmax = (np.min(posns),np.max(posns))
         posns = (posns - pmin) / (pmax - pmin)
         smooth /= (pmax - pmin)
     if smooth.max() <= 0.0:
         smooth *= 0.0
         smooth += 1.0
     else:
         smooth[smooth <= 0.0] = smooth[smooth > 0.0].min()
     cheaprescale = False
     if cheaprescale:
         cheap = fluid["pos"].units
         posns /= cheap
         smooth /= cheap
     posns -= 0.5
     self._outnum = 0#self._FindOutNum(filename)
     self._time = 0.0#ro._info["time"]
     self._snapdata = ro
     print "DONE LOADING DATA"
     return posns, smooth, mass
Example #26
0
def writeBHMark(simname,step,Name=None,iord=False,massrange=False):
	if not Name: f = open('BH.'+step+'.mark','w')
	else: f = open(Name,'w')
	s = pynbody.load(simname+'.'+step)
	f.write(str(len(s))+' '+str(len(s.gas))+' '+str(len(s.star))+'\n')
	if not iord: 
		if not massrange:
			bhind, = np.where(s.stars['tform']<0)
		else:
			if len(massrange) != 2:
				print "error massrange must be a length 2 tuple!"
				return
			bhind, = np.where((s.stars['tform']<0)&(s.stars['mass'].in_units('Msol')<massrange[1])&(s.stars['mass'].in_units('Msol')>massrange[0]))
	else:	
		bhind = np.array([])
		for ii in range(len(iord)):
			tmpind, = np.where(s.stars['iord']==iord[ii])
			if len(tmpind)==0: print "uh oh... iord ", iord[ii]," not found!"
			bhind = np.append(bhind,tmpind)
	bhindreal = bhind+len(s.dark)+len(s.gas)+1
	for ii in range(len(bhindreal)):
		f.write(str(bhindreal[ii])+'\n')
	f.close()
	del(s)
	return bhindreal
Example #27
0
def setup():
    global f
    f = pynbody.load("testdata/g15784.lr.01024")

    # for compatibility with original results, pretend the box
    # is not periodic
    del f.properties['boxsize']
Example #28
0
    def __init__(self,simname):
        self.simname = simname
        self.db_mergers = {}
        mergerfile = simname+'.mergers'
        print "reading .mergers file..."
        time, step, ID, IDeat, ratio, kick = readcol(mergerfile,twod=False)

        print "checking for bad IDs..."
        bad = np.where(ID<0)[0]
        if len(bad)>0:
            ID[bad] = 2*2147483648 + ID[bad]
        bad2 = np.where(IDeat<0)[0]
        if len(bad2)>0:
            IDeat[bad2] = 2*2147483648 + IDeat[bad2]

        uIDeat, indices = np.unique(IDeat, return_index=True)

        self.rawdat = {'time':time, 'ID1':ID, 'ID2':IDeat, 'ratio':ratio, 'kick':kick, 'step':step}
        util.cutdict(self.rawdat,indices)
        ordr = np.argsort(self.rawdat['ID2'])
        util.cutdict(self.rawdat,ordr)

        f = open('files.list','r')
        s = pynbody.load(f.readline().strip('\n'))
        f.close()
        scale, red = cosmology.getScaleFactor(pynbody.array.SimArray(self.rawdat['time'],'Gyr'),s)
        self.rawdat['redshift'] = red

        uIDeat, cnt = np.unique(self.rawdat['ID2'], return_counts=True)
        if len(np.where(cnt>1)[0])>0:
            print "SHIIIIIIT"
Example #29
0
	def plt_lumfun(self, style, minM = 1e6, maxM = None, minL = 1e42, maxL = None,
				volume=25**3, overplot=False,label=None, bins=50, redshift=1, plotdata=True, dotitle=True,lw=2):
		from .. import plotting
		from .. import cosmology
		import colldata as dat

		f = open('files.list', 'r')
		simfiles = f.readlines()
		f.close()
		sim = pynbody.load(simfiles[0].strip('\n'))
		tt = self.single_BH_data(self.bhiords[0],'time')
		dt = tt[1] - tt[0]
		zz = np.where((redshift > dat.hop_bhlf_zbinsl)&(redshift < dat.hop_bhlf_zbinsh))
		print "single timestep time: ", dt
		if maxM is None: maxM = self.data['mass'].max()*2
		if minM is None: minM = 0
		if maxL is None: maxL = self.data['lum'].max()*2
		if minL is None: minL = 0
		ok, = np.where((self.data['lum'] > minL)&(self.data['lum'] <= maxL)&(self.data['mass']>minM)&(self.data['mass']<maxM)&(self.data['scalefac']**-1 - 1 > dat.hop_bhlf_zbinsl[zz])&(self.data['scalefac']**-1 - 1 < dat.hop_bhlf_zbinsh[zz]))
		tlz = cosmology.getTime(dat.hop_bhlf_zbinsl[zz],sim)
		thz = cosmology.getTime(dat.hop_bhlf_zbinsh[zz],sim)
		T = tlz - thz
		if minL >0: lrange = [np.log10(minL), np.log10(maxL)]
		else: lrange = [np.log10(self.data['lum'].min()), np.log10(maxL)]
		dlogl = (lrange[1] - lrange[0])/float(bins)
		data = np.histogram(np.log10(self.data['lum'][ok]),bins=bins,range=lrange)
		phi = data[0]*(dt/(T*dlogl*volume))
		lbins = data[1]
		plotting.plt.step(lbins[0:-1],np.log10(phi),style, label=label, linewidth=lw, where='post')
		if plotdata is True:
			# Hopkins 07 data
			tardat, = np.where(dat.hop_bhlf_obs['redshift']==dat.hop_bhlf_z[zz])
			plotting.plt.errorbar(dat.hop_bhlf_obs['lbol'][tardat] + util.loglbol_sun, dat.hop_bhlf_obs['dphi'][tardat],yerr=dat.hop_bhlf_obs['sig'][tardat],fmt='o',color='grey',ecolor='grey',label='Hopkins+ 2007 (Compilation)')
			if dat.hop_bhlf_z[zz] == 6:
				# For z = 6, Barger+ 03 data
				plotting.plt.errorbar([dat.bar_bhlfz6_L],[dat.bar_bhlfz6_phi],
									xerr=dat.bar_bhlfz6_Lerr,yerr=dat.bar_bhlfz6_phierr,
									fmt='^',color='k',label='Barger+2003')
				# and Fiore+ 12 data
				plotting.plt.errorbar([dat.fio_bhlf_L6F],[dat.fio_bhlf_phi6F],
									xerr=[[dat.fio_bhlf_L6Fm],[dat.fio_bhlf_L6Fp]],
									yerr=[[dat.fio_bhlf_errphi6Fm],[dat.fio_bhlf_errphi6Fp]],
									fmt='s',color='k',label='Fiore+ 2012')
			if dat.hop_bhlf_z[zz] == 5:
				l1450 = np.log10(4.4)+util.mcABconv(dat.mcg_bhlf_obs['M1450'],util.c/0.145e-4)
				dphi = 10**dat.mcg_bhlf_obs['logphi']
				dphip = (2./5.) * (dphi + dat.mcg_bhlf_obs['sig'])
				dphim = (2./5.) * (dphi - dat.mcg_bhlf_obs['sig'])
				dphi = np.log10((2./5.)*dphi)
				dphierr = [dphi-np.log10(dphim),np.log10(dphip)-dphi]
				plotting.plt.errorbar(l1450,dphi,yerr=dphierr,fmt='D',color='k',label='McGreer+ 2013')
		if overplot is False:
			if dotitle is True:
				plotting.plt.title(str(dat.hop_bhlf_zbinsl[zz[0]])+' < z < '+str(dat.hop_bhlf_zbinsh[zz[0]]))
			plotting.plt.xlabel(r'log$_{10}$($L_{bol}$ [ergs/s]))',fontsize=30)
			plotting.plt.ylabel(r'log$_{10}$($\phi$ [Mpc$^{-3}$ dex$^{-1}$])',fontsize=30)
		if label is not None or plotdata is True:
			plotting.plt.legend(loc='lower left',fontsize=20)
		return
Example #30
0
def setup() :
    X = glob.glob("testdata/test_out.*")
    for z in X :
        os.unlink(z)
    
    global f, h
    f = pynbody.load("testdata/g15784.lr.01024")
    h = f.halos()
Example #31
0
import pynbody
import matplotlib.pylab as plt
import numpy as np
import glob

files = glob.glob(
    '/home/shared/data/h148/h148.cosmo50PLK.3072g3HbwK1BH.00????/h148.cosmo50PLK.3072g3HbwK1BH.00????'
)

#print len(files)
for file in files:
    sp = file.split(".")
    s = pynbody.load(file)
    #^ loading the snapshot
    iordwewant = 101863883
    BHfilter = pynbody.filt.LowPass(
        'tform', 0.0)  # this makes a filter for particles with negative form
    BH = s.stars[
        BHfilter]  # this identifies the black holes and makes a black hole object called BH
    #want = BH[1]  # BH in halo 3
    Iord = BH['iord']
    #print Iord
    trying = np.where(Iord == iordwewant)
    #print trying
    HaloIds = BH['amiga.grp']
    #print HaloIds
    count = HaloIds[trying]
    #print count
    h = s.halos()
    #haloes we need to only look are #3,5,6,11,12
    pynbody.analysis.angmom.faceon(h[count[0]])
def setup():
    global f
    f = pynbody.load("testdata/ramses_new_format_partial_output_00001")
Example #33
0
def test_bridge_factory():
    f1 = pynbody.load("testdata/g15784.lr.01024")
    f2 = pynbody.load("testdata/g15784.lr.01024")
    b = pynbody.bridge.bridge_factory(f1, f2)

    assert isinstance(b, pynbody.bridge.OrderBridge)
Example #34
0
def snapshot_gen(ICobj):
    """
    Generates a tipsy snapshot from the initial conditions object ICobj.
    
    Returns snapshot, param
    
        snapshot: tipsy snapshot
        param: dictionary containing info for a .param file
    Note: Code has been edited (dflemin3) such that now it returns a snapshot for a circumbinary disk
    where initial conditions generated assuming star at origin of mass M.  After gas initialized, replaced
    star at origin with binary system who's center of mass lies at the origin and who's mass m1 +m2 = M
    """

    print 'Generating snapshot...'
    # Constants
    G = SimArray(1.0, 'G')
    # ------------------------------------
    # Load in things from ICobj
    # ------------------------------------
    print 'Accessing data from ICs'
    settings = ICobj.settings

    # snapshot file name
    snapshotName = settings.filenames.snapshotName
    paramName = settings.filenames.paramName

    #Load user supplied snapshot (assumed to be in cwd)
    path = "/astro/store/scratch/tmp/dflemin3/nbodyshare/9au-Q1.05-129K/"
    snapshot = pynbody.load(path + snapshotName)

    # particle positions
    r = snapshot.gas['r']
    xyz = snapshot.gas['pos']

    # Number of particles
    nParticles = len(snapshot.gas)

    # molecular mass
    m = settings.physical.m

    #Pull star mass from user-supplied snapshot
    ICobj.settings.physical.M = snapshot.star[
        'mass']  #Total stellar mass in solar masses
    m_star = ICobj.settings.physical.M

    # disk mass
    m_disk = np.sum(snapshot.gas['mass'])
    m_disk = isaac.match_units(m_disk, m_star)[0]

    # mass of the gas particles
    m_particles = m_disk / float(nParticles)

    # re-scale the particles (allows making of low-mass disk)
    m_particles *= settings.snapshot.mScale

    # -------------------------------------------------
    # Assign output
    # -------------------------------------------------
    print 'Assigning data to snapshot'
    # Get units all set up
    m_unit = m_star.units
    pos_unit = r.units

    if xyz.units != r.units:

        xyz.convert_units(pos_unit)

    # time units are sqrt(L^3/GM)
    t_unit = np.sqrt((pos_unit**3) * np.power((G * m_unit), -1)).units
    # velocity units are L/t
    v_unit = (pos_unit / t_unit).ratio('km s**-1')
    # Make it a unit, save value for future conversion
    v_unit_vel = v_unit
    #Ensure v_unit_vel is the same as what I assume it is.
    assert (np.fabs(AddBinary.VEL_UNIT - v_unit_vel) <
            AddBinary.SMALL), "VEL_UNIT not equal to ChaNGa unit! Why??"

    v_unit = pynbody.units.Unit('{0} km s**-1'.format(v_unit))

    # Other settings
    metals = settings.snapshot.metals
    star_metals = metals

    # Estimate the star's softening length as the closest particle distance
    eps = r.min()

    # Make param file
    param = isaac.make_param(snapshot, snapshotName)
    param['dMeanMolWeight'] = m

    gc.collect()

    # CALCULATE VELOCITY USING calc_velocity.py.  This also estimates the
    # gravitational softening length eps

    preset = settings.changa_run.preset

    # -------------------------------------------------
    # Estimate time step for changa to use
    # -------------------------------------------------
    # Save param file
    isaac.configsave(param, paramName, 'param')
    # Save snapshot
    snapshot.write(filename=snapshotName, fmt=pynbody.tipsy.TipsySnap)
    # est dDelta
    dDelta = ICgen_utils.est_time_step(paramName, preset)
    param['dDelta'] = dDelta

    # -------------------------------------------------
    # Create director file
    # -------------------------------------------------
    # largest radius to plot
    r_director = float(0.9 * r.max())
    # Maximum surface density
    sigma_min = float(ICobj.sigma(r_director))
    # surface density at largest radius
    sigma_max = float(ICobj.sigma.input_dict['sigma'].max())
    # Create director dict
    director = isaac.make_director(sigma_min,
                                   sigma_max,
                                   r_director,
                                   filename=param['achOutName'])
    ## Save .director file
    #isaac.configsave(director, directorName, 'director')
    """
    Now that the gas disk is initializes around the primary (M=m1), add in the
    second star as specified by the user.
    """

    #Now that velocities and everything are all initialized for gas particles, create new snapshot to return in which
    #single star particle is replaced by 2, same units as above
    snapshotBinary = pynbody.new(star=2, gas=nParticles)
    snapshotBinary['eps'] = 0.01 * SimArray(
        np.ones(nParticles + 2, dtype=np.float32), pos_unit)
    snapshotBinary['metals'] = SimArray(
        np.zeros(nParticles + 2, dtype=np.float32))
    snapshotBinary['vel'].units = v_unit
    snapshotBinary['pos'].units = pos_unit
    snapshotBinary['mass'].units = snapshot['mass'].units
    snapshotBinary['rho'] = SimArray(np.zeros(nParticles + 2,
                                              dtype=np.float32))

    #Assign gas particles with calculated/given values from above
    snapshotBinary.gas['pos'] = snapshot.gas['pos']
    snapshotBinary.gas['vel'] = snapshot.gas['vel']
    snapshotBinary.gas['temp'] = snapshot.gas['temp']
    snapshotBinary.gas['rho'] = snapshot.gas['rho']
    snapshotBinary.gas['eps'] = snapshot.gas['eps']
    snapshotBinary.gas['mass'] = snapshot.gas['mass']
    snapshotBinary.gas['metals'] = snapshot.gas['metals']

    #Load Binary system obj to initialize system
    binsys = ICobj.settings.physical.binsys
    m_disk = isaac.strip_units(np.sum(snapshotBinary.gas['mass']))
    binsys.m1 = isaac.strip_units(m_star)
    binsys.m1 = binsys.m1 + m_disk
    #Recompute cartesian coords considering primary as m1+m_disk
    binsys.computeCartesian()

    x1, x2, v1, v2 = binsys.generateICs()

    #Assign position, velocity assuming CCW orbit
    snapshotBinary.star[0]['pos'] = SimArray(x1, pos_unit)
    snapshotBinary.star[0]['vel'] = SimArray(v1, v_unit)
    snapshotBinary.star[1]['pos'] = SimArray(x2, pos_unit)
    snapshotBinary.star[1]['vel'] = SimArray(v2, v_unit)
    """
    We have the binary positions about their center of mass, (0,0,0), so 
    shift the position, velocity of the gas disk to be around the primary.
    """
    snapshotBinary.gas['pos'] += snapshotBinary.star[0]['pos']
    snapshotBinary.gas['vel'] += snapshotBinary.star[0]['vel']

    #Set stellar masses: Create simArray for mass, convert units to simulation mass units
    snapshotBinary.star[0]['mass'] = SimArray(binsys.m1 - m_disk, m_unit)
    snapshotBinary.star[1]['mass'] = SimArray(binsys.m2, m_unit)
    snapshotBinary.star['metals'] = SimArray(star_metals)

    print 'Wrapping up'
    # Now set the star particle's tform to a negative number.  This allows
    # UW ChaNGa treat it as a sink particle.
    snapshotBinary.star['tform'] = -1.0

    #Set sink radius, stellar smoothing length as fraction of distance
    #from primary to inner edge of the disk
    r_sink = eps
    snapshotBinary.star[0]['eps'] = SimArray(r_sink / 2.0, pos_unit)
    snapshotBinary.star[1]['eps'] = SimArray(r_sink / 2.0, pos_unit)
    param['dSinkBoundOrbitRadius'] = r_sink
    param['dSinkRadius'] = r_sink
    param['dSinkMassMin'] = 0.9 * binsys.m2
    param['bDoSinks'] = 1

    return snapshotBinary, param, director
Example #35
0
import pynbody
import matplotlib.pylab as plt

#im loading the snapshot

s = pynbody.load(
    '/home/shared/data/h148/h148.cosmo50PLK.3072g3HbwK1BH.004096/h148.cosmo50PLK.3072g3HbwK1BH.004096'
)

#save it by ctrl-x-s 'to save work'

# gonna start loading the halo'galaxies' now

h = s.halos()

#halos we need to only look are # 3,5,6,11,12

pynbody.analysis.angmom.faceon(h[3])

#^^ its centering on the halo that i have picked which is 3 at the moment
#and giving it a shape of a disk almost like a dinner plate

s.physical_units()

#^^ making all the data into a certain amount by mul everything for me

p = pynbody.analysis.profile.Profile(h[3].s, min=.01, max=50)
#^^ starts everything from the center reaching outwards almost like axis

f, axs = plt.subplots(1, 2, figsize=(14, 6))
#^^ axs helps start making the graph
Example #36
0
def test_load_one_halo(path, nhalos):
    f = pynbody.load(path)
    halos = f.halos()
    np.testing.assert_allclose(halos[1].properties["members"],
                               halos[1]["iord"])
    assert len(halos) == nhalos
Example #37
0
def setup():
    global snap
    snap = pynbody.load("testdata/test_g2_snap")
Example #38
0
def setup():
    global f
    f = pynbody.load("testdata/ramses_partial_output_00250")
import pynbody
import numpy as np
import pandas as pd
import matplotlib.pylab as plt
import readcol
import BH_functions as BHF

files = readcol.readcol('/Jillian/h229/files.list')
files = files[:, 0]

#f =  open("h229.dat", "w+")
for j in range(13):

    # loading the snapshotS
    s = pynbody.load('/Jillian/h229/' + file[j])
    s.physical_units()
    # convert the units
    s.physical_units()

    # load the halos
    h = s.halos()

    # function to find black hole
    def findBH(s):
        BHfilter = pynbody.filt.LowPass('tform', 0.0)
        BH = s.stars[BHfilter]
        return BH

    BH = findBH(s)
Example #40
0
def test_no_mass_block():
    f = pynbody.load("testdata/gadget_no_mass")
    f['mass']  # should succeed
currentdir =  ''

for i in range(len(file)):
    # first, check if we're in a new timestep. if so, 
    # close prior file and make a new one
    thisdir = file[i].split("/")
    if thisdir[0] != currentdir:
        if i != 0:
            f.close()
        currentdir = thisdir[0]
        print "new dir ",thisdir[0]
        f = open(thisdir[0]+"/sigmas.dat","w")

 #   if (i == 0):
 #       continue  # skip halo 1
    s = pynbody.load(file[i])
    if len(s.stars) < tinyhalolimit:  # tiny halos don't get kinematics
        print "skipping tiny halo "
        continue
    s.physical_units()
    #print " numbers of particles ", len(s.g),len(s.d),len(s.s)
    # get the halo id from the file name
    splitfile = file[i].split(".")
    haloid = splitfile[7]
    #print haloid," haloid"

    pynbody.analysis.halo.center(s,mode='ssc')
    #pynbody.plot.sph.image(s.g,qty='rho',units='g cm^-2',width=100,cmap='Greys')
    #pynbody.plot.stars.render(s,width='10 kpc')
    #radius = pynbody.derived.r(s.stars)
    #print min(radius),max(radius)
Example #42
0
import pynbody
import matplotlib as plt

#Loads snapshot
s = pynbody.load(
    '/data/h258/stampedetesting/glenna/h258.cosmo50cmb.3072gst1bwdK1BH.000128')

#Put the units in the right way
s.physical_units()

#initiates a halo catalogue object for the given snapshot
h = s.halos()


#Function for finding BH
def findBH(s):
    """A function that returns particles whose property is less than max """
    BH = s.stars[(pynbody.filt.LowPass('tform', 0.0))]
    return BH


BH = findBH(s)
BH_position = BH['pos']
print BH['mass']
print(s.families(), s.loadable_keys, ())
print(BH)
print(BH_position)
Example #43
0
def setup():
    global snap, subfind
    snap = pynbody.load(
        'testdata/Test_NOSN_NOZCOOL_L010N0128/data/snapshot_103/snap_103.hdf5')
    subfind = pynbody.load(
        'testdata/Test_NOSN_NOZCOOL_L010N0128/data/subhalos_103/subhalo_103')
gasarray = []
dmarray = []
stararray = []
sfrarray = []
inflowarray = []
outflowarray = []
bharray = []

surfden1kpc = []
ssfr = []

datafiles = sorted(glob.glob(filename + gal + '/' + gal + '.0????'))
print(datafiles)
print("printed datafiles above")
for d in datafiles:
    sim = pynbody.load(d)
    if sim.properties['z'] > 5:
        continue
    h = sim.halos()
    h1 = h[1]
    h1.physical_units()
    pynbody.analysis.halo.center(h1, mode='hyb')
    pynbody.analysis.angmom.faceon(h1)

    newstarmass = 0
    stars, darkmatter, gas, inflow, outflow = 0, 0, 0, 0, 0
    for pos, mass, age in zip(sim.star['pos'].in_units('kpc'),
                              sim.star['mass'].in_units('Msol'),
                              sim.star['age'].in_units('yr')):
        if (pos[0]**2 + pos[1]**2 + pos[2]**2) < 1:
            stars += mass
Example #45
0
    k = 1000
    limits = -100000, 30000  # No limits
    # limits = 5000, 8000
    tN = 10

    do_spectral_smoothing = True
    do_spatial_smoothing = True
    do_spectral_rebinning = True

    # cube = create_single_spectra_cube(bins=bins)

    snap_name = os.path.join(
        SIM_PATH,
        "mb.{}_p{}_a800_r600/out/snapshot_{:04d}".format(sim, peri, isnap))
    print('Star mass: {:.2g} Msol'.format(
        pynbody.load(snap_name).s['mass'].sum().in_units('Msol')))

    save_pickle = contract_name("sp",
                                sim,
                                isnap,
                                peri,
                                size_cuboid,
                                ext='pkl',
                                fix=fix_star_met_age,
                                doppler_shift=doppler_shift)

    print("Computing cube spectra...")
    spectra1d, (x,
                y), last_valid_freq = get_spectra(snap_name=snap_name,
                                                  save_pickle=save_pickle,
                                                  size_cuboid=size_cuboid,
Example #46
0
import pynbody
import matplotlib.pylab as plt
plt.switch_backend("agg")

#im loading the snapshot

s = pynbody.load('/mnt/storm/storm.cosmo25cmb.4096g5HbwK1BH.004096/storm.cosmo25cmb.4096g5HbwK1BH.004096')   

#save it by ctrl-x-s 'to save work'



# gonna start loading the halo'galaxies' now

h = s.halos()

#halo we need to look at is #2


pynbody.analysis.angmom.faceon(h[2])

#^^ its centering on the halo that i have picked which is 3 at the moment
#and giving it a shape of a disk almost like a dinner plate

s.physical_units()

#^^ making all the data into a certain amount by mul everything for me

p = pynbody.analysis.profile.Profile(h[2].s,min=.01,max=50)
#^^ starts everything from the center reaching outwards almost like axis
Example #47
0
import pynbody
import matplotlib.pylab as plt

# load the snapshot and set to physical units
s = pynbody.load('testdata/g15784.lr.01024.gz')

# load the halos
h = s.halos()

# center on the largest halo and align the disk
pynbody.analysis.angmom.faceon(h[1])

# convert all units to something reasonable (kpc, Msol etc)
s.physical_units()

# create a profile object for the stars (by default this is a 2D profile)
p = pynbody.analysis.profile.Profile(h[1].s, min=.01, max=50)

# make the figure and sub plots
f, axs = plt.subplots(1, 2, figsize=(14, 6))

# make the plot
axs[0].plot(p['rbins'], p['density'], 'k')
axs[0].semilogy()
axs[0].set_xlabel('R [kpc]')
axs[0].set_ylabel(r'$\Sigma_{\star}$ [M$_{\odot}$ kpc$^{-2}$]')

# make a 3D density plot of the dark matter (note ndim=3 in the constructor below)
p = pynbody.analysis.profile.Profile(h[1].d, min=.01, max=50, ndim=3)

axs[1].plot(p['rbins'], p['density'], 'k')
Example #48
0
def clstar(f, r_cut=None, r_max=None, center_on_star=True):
    """
    Deletes particles within a given radius of the star and recenters the snapshot
    on the center of mass of the system.
    
    *** ARGUMENTS ***

    * f *       Either a filename pointing to a snapshot to be loaded -OR- 
        a pynbody SimSnap    
    
    * r_cut *   Remove particles at r < r_cut from the star.  If None, defaults
        to 0.02 AU
    
    * r_max *   Remove particles at r > r_max.  If None, r_max is infinity
    
    * center_on_star *  True or False.  If True, the simulation is re-centered
        on the star.
    
    *** RETURNS ***
    
    Returns a re-centered SimSnap with particles removed
    """
    if r_cut is None:
        # Default radial cut-off for particles.  IE, delete all particles
        # at r < r_cut
        r_cut = SimArray(0.02, 'au')
    if isinstance(f, basestring):
        # Assume f is a file name for a snapshot
        fName = f
        f = pynbody.load(fName)
    else:
        # Assume f is a pynbody SimSnap
        fName = f.filename
    # Center around star
    starPos = f.star['pos'][0].copy()
    for n in range(3):
        f['pos'][:, n] -= starPos[[n]]
    # Remove particles at r < r_cut (except the star)
    r = f.gas['rxy']
    use_ind = np.ones(len(f), dtype='bool')
    if r_max is None:
        use_ind[0:-1] = (r >= r_cut)
    else:
        use_ind[0:-1] = ((r >= r_cut) & (r < r_max))

    n_cut = (~use_ind).sum()

    if n_cut > 0:

        # Transfer momentum to the star
        m_g = f.g['mass'][[0]]
        m_g_tot = m_g * (~use_ind).sum()
        p_g = (m_g * f['vel'][~use_ind]).sum(0)
        p_s = f.s['mass'] * f.s['vel']
        v_s = (p_s + p_g) / (f.s['mass'] + m_g_tot)
        f.s['vel'] = v_s.in_units(f.s['vel'].units)
        f.s['mass'] += m_g_tot

        # Delete particles
        f = f[use_ind]
        print 'Deleted {0} particles'.format(n_cut)

    # If we're not centering on the star, add it's initial position back in
    if not center_on_star:

        for n in range(3):
            f['pos'][:, n] += starPos[[n]]

    return f
Example #49
0
def f():
    yield pynbody.load("testdata/output_00080")
import numpy as np
import pynbody as pyn
import matplotlib.pyplot as plt
from matplotlib.ticker import LogLocator
from glob import glob

path = "/home/grondjj/Data/RadTransfer/Isothemal_Spheres/"
folders = glob(path + "Test/[0-9]*[.e]*[0-9]/")
iCut = np.load(path + "Soln/inShadowsAndBalls.npy")
af = np.array(pyn.load(path + "Test/1e-08/balls.00001").g["radFlux"])
af_cut = np.array(pyn.load(path + "Test/1e-08/balls.00001").g["radFlux"])[iCut]
N = len(af)

cells = []
taus = []
rmse = []
rmse_cut = []

for f in folders:
    nf = np.array(pyn.load(f + "balls.00001").g["radFlux"])
    nf_cut = np.array(pyn.load(f + "balls.00001").g["radFlux"])[iCut]
    rmse.append(np.sqrt(np.sum(((nf - af) / af)**2) / len(af)))
    rmse_cut.append(
        np.sqrt(np.sum(((nf_cut - af_cut) / af_cut)**2) / len(af_cut)))
    taus.append(float(f.split('/')[-2]))
    switch = 0
    with open(f + "/output.txt", 'r') as f:
        for line in f:
            if line[:7] == "nActive":
                if switch == 0:
                    cells.append(int(line.split(',')[-2].split(' ')[-1]))
width = 1000  # kpc

ax_d_sonia = plt.subplot(gs[0, 0])
ax_g_sonia = plt.subplot(gs[0, 1])
ax_s_sonia = plt.subplot(gs[0, 2])
ax_d_sandra = plt.subplot(gs[1, 0])
ax_g_sandra = plt.subplot(gs[1, 1])
ax_s_sandra = plt.subplot(gs[1, 2])
cbax_d = plt.subplot(gs[2, 0])
cbax_g = plt.subplot(gs[2, 1])
cbax_s = plt.subplot(gs[2, 2])

# TOP ROW: SONIA
sim = '/home/christenc/Data/Sims/h242.cosmo50PLK.3072g/h242.cosmo50PLK.3072gst5HbwK1BH/snapshots_200bkgdens/h242.cosmo50PLK.3072gst5HbwK1BH.004096'
name = 'h242'
s = pynbody.load(sim)
s.physical_units()
h = s.halos()
h_dummy = s.halos(dummy=True)
print('Loaded simulation')

labels = []

i = 0

h1x = h_dummy[1].properties['Xc']
h1y = h_dummy[1].properties['Yc']
h1z = h_dummy[1].properties['Zc']

smin, smax = -width // 2, width // 2
print('Centering halo 1')
Example #52
0
def test_family_array_dtype() :
    # test for issue #186
    f = pynbody.load('testdata/g15784.lr.01024.gz')
    f.g['rho'] = np.zeros(len(f.g),dtype=np.float32)
    f.s['rho']
Example #53
0
def test_conversion():
    """Check that we can convert a file from tipsy format and load it again"""
    snap4 = pynbody.load("testdata/g15784.lr.01024")
    snap4.write(fmt=pynbody.gadget.GadgetSnap,
                filename="testdata/test_conversion.gadget")
    snap5 = pynbody.load("testdata/test_conversion.gadget")
Example #54
0
def test_g1_load():
    """Check we can load gadget-1 files also"""
    snap2 = pynbody.load("testdata/gadget1.snap")
Example #55
0
def test_write_single_array():
    """Check that we can write a single array and read it back"""
    snap["pos"].write(overwrite=True)
    snap6 = pynbody.load("testdata/test_g2_snap")
    assert((snap6["pos"] == snap["pos"]).all())
Example #56
0
import pynbody

infile = 'snapshot.001500'
outfile = 'nostar.std'

gstar = pynbody.load(infile)

print 'star mass: ', gstar.s['mass']
print 'star eps: ', gstar.s['eps']
print 'star pos: ', gstar.s['pos']
print 'star vel: ', gstar.s['vel']

# transform to astrocentric coordinates
pynbody.transformation.inverse_xv_translate(gstar, gstar.s['pos'][0],
                                            gstar.s['vel'][0])
gstar.g.write(filename=outfile, fmt=pynbody.tipsy.TipsySnap)
Example #57
0
def loader(path):
    '''returns snapshot and halo'''
    snap = pynbody.load(path)
    snap.physical_units()
    h = snap.halos()
    return snap, h
Example #58
0
def setup_param(param, snapshot=None, r_orb=1.0, n_orb=10.0, n_image=None, n_snap=100, \
n_check=None):
    """
    Sets up the following for a .param file:
        
        nSteps
        dDumpFrameStep
        iOutInterval
        iCheckInterval
        
    **ARGUMENTS**
    
    param : str or param_dict (see isaac.configparser, configsave)
        parameter file for the simulation, must already have dDelta and units
        set properly
        IF a str, assumed to be a filename
    snapshot : str or TipsySnap(see pynbody) or None
        Snapshot for the simulation.  Needed to estimate the outer orbital
        period.  
        IF a str, assumed to be a filename
        IF None, the file pointed to by param is used
    r_orb : float
        radius to calculate the outer orbital period at as a fraction of the
        radius of the farthest out particle.  Must be between 0 and 1
    n_orb : float
        number of outer orbital periods to run simulation for
    n_image : int or None
        Total number of frames to dump (ie, dDumpFrameStep)
        If None, defaults to n_snap
    n_snap : int
        Total number of simulation outputs
    n_check : int or None
        Total number of simulation checkpoints.  If None, defaults to n_snap
    """

    if (r_orb > 1) | (r_orb < 0):

        raise ValueError, 'r_orb must be between 0 and 1'

    if isinstance(snapshot, str):

        # A filename has been passed, not a tipsy snapshot
        snapshot = pynbody.load(snapshot)

    if isinstance(param, str):

        # A filename has been passed.  Load the dictionary
        param = configparser(param, 'param')

    else:

        # Copy so as to not overwrite the input dict
        param = copy.deepcopy(param)

    R_max = r_orb * snapshot.g['rxy'].max()
    M_star = snapshot.s['mass']

    # Read in .param stuff
    l_unit = '{} kpc'.format(param['dKpcUnit'])
    m_unit = '{} Msol'.format(SimArray(param['dMsolUnit'], 'Msol'))

    # Outer radius and star mass in simulation units
    r = float(R_max.in_units(l_unit))
    M = float(M_star.in_units(m_unit))

    # Calculate the number of time steps to use
    dt = param['dDelta']
    period = 2 * np.pi * np.sqrt(r**3 / M)
    N = int(np.round(n_orb * period / dt))
    param['nSteps'] = N

    # Calculate how often to output snapshots, frames, checkpoints
    if n_check is None:

        n_check = n_snap

    if n_image is None:

        n_image = n_snap

    param['dDumpFrameStep'] = int(N / n_image)
    param['iOutInterval'] = int(N / n_snap)
    param['iCheckInterval'] = int(N / n_check)

    return param
Example #59
0
def test_index_list():
    f = pynbody.load("testdata/g15784.lr.01024")
    h = f.halos()
    index_list = h[1].get_index_list(f)
#import all the good stuff!
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
import pynbody
import pylab
import numpy as np
import matplotlib.pylab as plt
import astropy.units as u

#Now I need a code that will load the simulation (s will stand for simulation)
s = pynbody.load("cptmarvel.cosmo25cmb.4096g5HbwK1BH.004096.5.std")

#The following code will change the units to make it more appealing
s.physical_units()

#Center it
pynbody.analysis.angmom.faceon(s)
'''
#This code tells me what properties of the simulation I can call on
keys = s.loadable_keys()
print(keys)
'''
'''
Previous Student used a function which tells the computer to filter through
the simulation to find anything with 'tform' (time formed) equal to an integer
lower than 0.

This makes sense since BH have a negative 'tform' and all negative integers
are less than 0
'''