示例#1
0
def test_profile_zero_weight():
    def DMparticles(pfilter, data):
        filter = data[(pfilter.filtered_type, "particle_type")] == 1
        return filter

    def DM_in_cell_mass(field, data):
        return data['deposit', 'DM_density'] * data['index', 'cell_volume']

    add_particle_filter("DM",
                        function=DMparticles,
                        filtered_type='io',
                        requires=["particle_type"])

    ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030")

    ds.add_particle_filter('DM')

    ds.add_field(("gas", "DM_cell_mass"),
                 units="g",
                 function=DM_in_cell_mass,
                 sampling_type='cell')

    sp = ds.sphere(ds.domain_center, (10, 'kpc'))

    profile = yt.create_profile(sp, [("gas", "density")],
                                [("gas", "temperature")],
                                weight_field=("gas", "DM_cell_mass"))

    assert not np.any(np.isnan(profile['gas', 'temperature']))
示例#2
0
def test_profile_zero_weight():
    def DMparticles(pfilter, data):
        filter = data[(pfilter.filtered_type, "particle_type")] == 1
        return filter

    def DM_in_cell_mass(field, data):
        return data['deposit', 'DM_density']*data['index', 'cell_volume']

    add_particle_filter("DM", function=DMparticles,
                        filtered_type='io', requires=["particle_type"])

    _fields = ("particle_position_x", "particle_position_y",
               "particle_position_z", "particle_mass", "particle_velocity_x",
               "particle_velocity_y", "particle_velocity_z", "particle_type")
    _units = ('cm', 'cm', 'cm', 'g', 'cm/s', 'cm/s', 'cm/s', 'dimensionless')
    ds = fake_random_ds(32, particle_fields=_fields,
                        particle_field_units=_units, particles=16)

    ds.add_particle_filter('DM')
    ds.add_field(("gas", "DM_cell_mass"), units="g", function=DM_in_cell_mass,
                 sampling_type='cell')

    sp = ds.sphere(ds.domain_center, (10, 'kpc'))

    profile = yt.create_profile(sp,
                                [("gas", "density")],
                                [("gas", "radial_velocity")],
                                weight_field=("gas", "DM_cell_mass"))

    assert not np.any(np.isnan(profile['gas', 'radial_velocity']))
示例#3
0
def compute_disk_masses(filenames):
    rds = np.arange(28,43)
    rds = rds[::-1]
    timesteps = np.zeros(len(rds))
    gas_masses = np.zeros((len(rds),len(filenames)))
    stellar_masses = np.zeros((len(rds),len(filenames)))

    add_particle_filter("formed_star", function=formed_star, filtered_type='all',
                        requires=["creation_time"])

    for j in range(len(filenames)):
        center_guess = [0.48988587,0.47121728,0.50938220]
        for i in range(len(rds)):
            filein = filenames[j]+'/RD00'+str(rds[i])+'/RD00'+str(rds[i])
            ds = yt.load(filein)
            ds.add_particle_filter('formed_star')
            halo_center, halo_velocity = get_halo_center(ds,center_guess)
            center_guess = halo_center
            (Lx,x) = diskVectors(ds,halo_center)
            disk = ds.disk(halo_center,Lx,(40.,'kpc'),(20.,'kpc'))
            ## let's look for cold/dense gas
            ## ISM conditions from review paper:
            ## n > 0.1, T < 4
            idx = np.where((disk['H_p0_number_density'] < 0.1) &
                           (disk['Temperature'] < 1e4))[0]
            gas_masses[i,j] = np.sum(disk['cell_mass'][idx].in_units('Msun'))
            stellar_masses[i,j] = np.sum(disk['formed_star', 'particle_mass'].in_units('Msun'))
            timesteps[i] = ds.current_redshift
    data = {'gas_masses':gas_masses,'stellar_masses':stellar_masses,'timesteps':timesteps}
    cPickle.dump(data,open('disk_mass_evol.cpkl','wb'),protocol=-1)
    return gas_masses,stellar_masses,timesteps
示例#4
0
def set_up_enzo(ds):
    def star_filter(pfilter, data):
        return (data[pfilter.filtered_type, 'creation_time'] > 0)

    add_particle_filter('stars',
                        function=star_filter,
                        filtered_type='all',
                        requires=['creation_time'])
    ds.add_particle_filter('stars')

    def dm_filter(pfilter, data):
        return (data[pfilter.filtered_type, 'creation_time'] == 0)

    add_particle_filter('darkmatter',
                        function=dm_filter,
                        filtered_type='all',
                        requires=['creation_time'])
    ds.add_particle_filter('darkmatter')

    def particle_creation_time(field, data):
        return data['stars', 'creation_time']

    ds.add_field(('stars', 'particle_creation_time'),
                 sampling_type='particle',
                 function=particle_creation_time,
                 units='s')
示例#5
0
def test_particle_projection_filter():
    '''

    This tests particle projection plots for filter fields.
    

    '''
    def formed_star(pfilter, data):
        filter = data["all", "creation_time"] > 0
        return filter

    add_particle_filter("formed_star",
                        function=formed_star,
                        filtered_type='all',
                        requires=["creation_time"])

    plot_field = ('formed_star', 'particle_mass')

    decimals = 12
    ds = data_dir_load(g30)
    ds.add_particle_filter('formed_star')
    for ax in 'xyz':
        attr_name = "set_log"
        for args in PROJ_ATTR_ARGS[attr_name]:
            test = PlotWindowAttributeTest(ds, plot_field, ax, attr_name, args,
                                           decimals, 'ParticleProjectionPlot')
            test_particle_projection_filter.__name__ = test.description
            yield test
示例#6
0
def set_up_gizmo(ds):
    def star_mass_rename(field, data):
        return data['PartType4', 'particle_mass']

    ds.add_field(('stars', 'particle_mass'),
                 sampling_type='particle',
                 function=star_mass_rename,
                 units='g')

    ad = ds.all_data()
    m1 = ad['PartType1', 'Masses']
    unique_dm1_masses = np.unique(m1)
    m2 = ad['PartType2', 'Masses']
    unique_dm2_masses = np.unique(m2)

    def dm_filter(pfilter, data):
        allowed = np.zeros(data[pfilter.filtered_type, 'Masses'].shape,
                           dtype=bool)
        for v in ds.arr(
                np.concatenate([unique_dm1_masses, unique_dm2_masses]).v,
                m2.units):
            allowed = np.logical_or(allowed, data[pfilter.filtered_type,
                                                  'Masses'] == v)
        return allowed

    add_particle_filter('darkmatter',
                        function=dm_filter,
                        filtered_type='all',
                        requires=['Masses'])
    ds.add_particle_filter('darkmatter')

    co = Cosmology(hubble_constant=ds.hubble_constant,
                   omega_matter=ds.omega_matter,
                   omega_lambda=ds.omega_lambda,
                   omega_curvature=0.0)

    def particle_creation_time_rename(field, data):
        return co.t_from_a(data['PartType4', 'StellarFormationTime'])

    ds.add_field(('stars', 'particle_creation_time'),
                 sampling_type='particle',
                 function=particle_creation_time_rename,
                 units='s')

    def metal_density(field, data):
        return data['gas', 'metallicity'] * data['gas', 'density']

    ds.add_field(('gas', 'metal_density'),
                 sampling_type='particle',
                 function=metal_density,
                 units='g/cm**3')
    alias_default_velocities(ds, 'PartType0', 'particle')
示例#7
0
def set_up_gadget(ds):
    def star_mass_rename(field, data):
        return data['PartType4', 'particle_mass']

    ds.add_field(('stars', 'particle_mass'),
                 sampling_type='particle',
                 function=star_mass_rename,
                 units='g')

    ad = ds.all_data()
    m1 = ad['PartType1', 'Masses']
    assert np.amin(m1) == np.amax(m1)
    unique_dm1_mass = np.amin(m1)
    m5 = ad['PartType5', 'Masses']
    unique_dm5_masses = np.unique(m5)

    def dm_filter(pfilter, data):
        allowed = data[pfilter.filtered_type, 'Masses'] == unique_dm1_mass
        for v in unique_dm5_masses:
            allowed = np.logical_or(allowed, data[pfilter.filtered_type,
                                                  'Masses'] == v)
        return allowed

    add_particle_filter('darkmatter',
                        function=dm_filter,
                        filtered_type='all',
                        requires=['Masses'])
    ds.add_particle_filter('darkmatter')

    co = Cosmology(hubble_constant=ds.hubble_constant,
                   omega_matter=ds.omega_matter,
                   omega_lambda=ds.omega_lambda,
                   omega_curvature=0.0)

    def particle_creation_time_rename(field, data):
        return co.t_from_a(data['PartType4', 'StellarFormationTime'])

    ds.add_field(('stars', 'particle_creation_time'),
                 sampling_type='particle',
                 function=particle_creation_time_rename,
                 units='s')

    def metal_density(field, data):
        return data['gas', 'metallicity'] * data['gas', 'density']

    ds.add_field(('gas', 'metal_density'),
                 sampling_type='particle',
                 function=metal_density,
                 units='g/cm**3')
    alias_default_velocities(ds, 'PartType0', 'particle')
示例#8
0
def test_profile_zero_weight():
    def DMparticles(pfilter, data):
        filter = data[(pfilter.filtered_type, "particle_type")] == 1
        return filter

    def DM_in_cell_mass(field, data):
        return data["deposit", "DM_density"] * data["index", "cell_volume"]

    add_particle_filter("DM",
                        function=DMparticles,
                        filtered_type="io",
                        requires=["particle_type"])

    _fields = (
        "particle_position_x",
        "particle_position_y",
        "particle_position_z",
        "particle_mass",
        "particle_velocity_x",
        "particle_velocity_y",
        "particle_velocity_z",
        "particle_type",
    )
    _units = ("cm", "cm", "cm", "g", "cm/s", "cm/s", "cm/s", "dimensionless")
    ds = fake_random_ds(32,
                        particle_fields=_fields,
                        particle_field_units=_units,
                        particles=16)

    ds.add_particle_filter("DM")
    ds.add_field(
        ("gas", "DM_cell_mass"),
        units="g",
        function=DM_in_cell_mass,
        sampling_type="cell",
    )

    sp = ds.sphere(ds.domain_center, (10, "kpc"))

    profile = yt.create_profile(
        sp,
        [("gas", "density")],
        [("gas", "radial_velocity")],
        weight_field=("gas", "DM_cell_mass"),
    )

    assert not np.any(np.isnan(profile["gas", "radial_velocity"]))
示例#9
0
def test_add_particle_filter_overriding():
    """Test the add_particle_filter overriding"""
    from yt.data_objects.particle_filters import filter_registry
    from yt.funcs import mylog

    def star_0(pfilter, data):
        pass

    def star_1(pfilter, data):
        pass

    # Use a closure to store whether the warning was called
    def closure(status):
        def warning_patch(*args, **kwargs):
            status[0] = True

        def was_called():
            return status[0]

        return warning_patch, was_called

    ## Test 1: we add a dummy particle filter
    add_particle_filter("dummy",
                        function=star_0,
                        filtered_type='all',
                        requires=["creation_time"])
    assert 'dummy' in filter_registry
    assert_equal(filter_registry['dummy'].function, star_0)

    ## Test 2: we add another dummy particle filter.
    ##         a warning is expected. We use the above closure to
    ##         check that.
    # Store the original warning function
    warning = mylog.warning
    monkey_warning, monkey_patch_was_called = closure([False])
    mylog.warning = monkey_warning
    add_particle_filter("dummy",
                        function=star_1,
                        filtered_type='all',
                        requires=["creation_time"])
    assert_equal(filter_registry['dummy'].function, star_1)
    assert_equal(monkey_patch_was_called(), True)

    # Restore the original warning function
    mylog.warning = warning
示例#10
0
    def create_field_info(self, *args, **kwa):
        """Extend create_field_info to add the particles types."""
        super(RAMSESDataset, self).create_field_info(*args, **kwa)
        # Register particle filters
        if ('io', 'particle_family') in self.field_list:
            for fname, value in particle_families.items():
                def loc(val):
                    def closure(pfilter, data):
                        filter = data[(pfilter.filtered_type, "particle_family")] == val
                        return filter

                    return closure
                add_particle_filter(fname, loc(value),
                                    filtered_type='io', requires=['particle_family'])

            for k in particle_families.keys():
                mylog.info('Adding particle_type: %s' % k)
                self.add_particle_filter('%s' % k)
示例#11
0
def test_OWLS_particlefilter():
    ds = data_dir_load(os33)
    ad = ds.all_data()

    def cold_gas(pfilter, data):
        temperature = data[pfilter.filtered_type, "Temperature"]
        filter = (temperature.in_units('K') <= 1e5)
        return filter

    add_particle_filter("gas_cold",
                        function=cold_gas,
                        filtered_type='PartType0',
                        requires=["Temperature"])
    ds.add_particle_filter('gas_cold')

    mask = (ad['PartType0', 'Temperature'] <= 1e5)
    assert ad['PartType0',
              'Temperature'][mask].shape == ad['gas_cold', 'Temperature'].shape
示例#12
0
def test_add_particle_filter():
    """Test particle filters created via add_particle_filter

    This accesses a deposition field using the particle filter, which was a
    problem in previous versions on this dataset because there are chunks with
    no stars in them.

    """
    def stars(pfilter, data):
        filter_field = (pfilter.filtered_type, "particle_mass")
        return data[filter_field] > 0.5

    add_particle_filter("stars",
                        function=stars,
                        filtered_type='all',
                        requires=["particle_mass"])
    ds = fake_random_ds(16, nprocs=8, particles=16)
    ds.add_particle_filter('stars')
    assert ('deposit', 'stars_cic') in ds.derived_field_list
def test_add_particle_filter():
    """Test particle filters created via add_particle_filter

    This accesses a deposition field using the particle filter, which was a
    problem in previous versions on this dataset because there are chunks with
    no stars in them.

    """

    def stars(pfilter, data):
        filter_field = (pfilter.filtered_type, "creation_time")
        return (data.ds.current_time - data[filter_field]) > 0

    add_particle_filter("stars", function=stars, filtered_type='all',
                        requires=["creation_time"])
    ds = yt.load(iso_galaxy)
    ds.add_particle_filter('stars')
    ad = ds.all_data()
    ad['deposit', 'stars_cic']
    assert True
示例#14
0
def test_add_particle_filter():
    """Test particle filters created via add_particle_filter

    This accesses a deposition field using the particle filter, which was a
    problem in previous versions on this dataset because there are chunks with
    no stars in them.

    """

    def stars(pfilter, data):
        filter_field = (pfilter.filtered_type, "creation_time")
        return (data.ds.current_time - data[filter_field]) > 0

    add_particle_filter("stars", function=stars, filtered_type='all',
                        requires=["creation_time"])
    ds = yt.load(iso_galaxy)
    ds.add_particle_filter('stars')
    ad = ds.all_data()
    ad['deposit', 'stars_cic']
    assert True
示例#15
0
    def create_field_info(self, *args, **kwa):
        """Extend create_field_info to add the particles types."""
        super().create_field_info(*args, **kwa)
        # Register particle filters
        if ("io", "particle_family") in self.field_list:
            for fname, value in particle_families.items():

                def loc(val):
                    def closure(pfilter, data):
                        filter = data[(pfilter.filtered_type, "particle_family")] == val
                        return filter

                    return closure

                add_particle_filter(
                    fname, loc(value), filtered_type="io", requires=["particle_family"]
                )

            for k in particle_families.keys():
                mylog.info("Adding particle_type: %s", k)
                self.add_particle_filter(f"{k}")
示例#16
0
文件: test_outputs.py 项目: tukss/yt
def test_OWLS_particlefilter():
    ds = data_dir_load(os33)
    ad = ds.all_data()

    def cold_gas(pfilter, data):
        temperature = data[pfilter.filtered_type, "Temperature"]
        filter = temperature.in_units("K") <= 1e5
        return filter

    add_particle_filter(
        "gas_cold",
        function=cold_gas,
        filtered_type="PartType0",
        requires=["Temperature"],
    )
    ds.add_particle_filter("gas_cold")

    mask = ad["PartType0", "Temperature"] <= 1e5
    assert (ad["PartType0",
               "Temperature"][mask].shape == ad["gas_cold",
                                                "Temperature"].shape)
示例#17
0
def test_add_particle_filter():
    """Test particle filters created via add_particle_filter

    This accesses a deposition field using the particle filter, which was a
    problem in previous versions on this dataset because there are chunks with
    no stars in them.

    """

    def stars(pfilter, data):
        filter_field = (pfilter.filtered_type, "particle_mass")
        return data[filter_field] > 0.5

    add_particle_filter("stars1", function=stars, filtered_type='all',
                        requires=["particle_mass"])
    ds = fake_random_ds(16, nprocs=8, particles=16)
    ds.add_particle_filter('stars1')
    assert ('deposit', 'stars1_cic') in ds.derived_field_list

    # Test without requires field
    add_particle_filter("stars2", function=stars)
    ds = fake_random_ds(16, nprocs=8, particles=16)
    ds.add_particle_filter('stars2')
    assert ('deposit', 'stars2_cic') in ds.derived_field_list

    # Test adding filter with fields not defined on the ds
    with assert_raises(YTIllDefinedParticleFilter) as ex:
        add_particle_filter("bad_stars", function=stars,
                            filtered_type='all', requires=["wrong_field"])
        ds.add_particle_filter('bad_stars')
    actual = str(ex.exception)
    desired = '\nThe fields\n\t(\'all\', \'wrong_field\'),\nrequired by the' \
              ' "bad_stars" particle filter, are not defined for this dataset.'
    assert_equal(actual, desired)
示例#18
0
	def __init__(self, path, ioutput, **kwargs):
		Snapshot.Snapshot.__init__(self, path, ioutput, "yt", **kwargs)
		'''
		Load the snapshot
		'''

		#self._snapshot = yt.load(os.path.join('%s/output_%05d/info_%05d.txt'%(path, ioutput, ioutput)))
		if "patch" in kwargs:
                        patch = kwargs.get("patch","default")
			print patch
		
		try:
			stars = kwargs.get("stars",False)
		except KeyError:
			stars = False

		try:
			dark = kwargs.get("dark",False)
		except KeyError:
			dark = False

		if "patch" in kwargs:
			if patch != None or patch != "normal":
				self._snapshot = yt.mods.load(os.path.join('%s/output_%05d/info_%05d.txt'%(path, ioutput, ioutput)), patch=patch)
#				self._snapshot = yt.mods.load(os.path.join('%s/output_%05d/info_%05d.txt'%(path, ioutput, ioutput)))
		else:
			self._snapshot = yt.mods.load(os.path.join('%s/output_%05d/info_%05d.txt'%(path, ioutput, ioutput)))

## snapshot filter methods ... for example, filtering out DM particles (creation time != 0)
		if stars == True:
			add_particle_filter("stars", function=star_filter, filtered_type="all", requires=["particle_age"])
			self._snapshot.add_particle_filter("stars")

		if dark == True:
			add_particle_filter("dark", function=dark_filter, filtered_type="all", requires=["particle_age"])
			self._snapshot.add_particle_filter("dark")
# Usage: mpirun -np <num_procs> --mca btl ^openib python this_script.py

import yt
from yt.analysis_modules.halo_analysis.halo_catalog import HaloCatalog
from yt.data_objects.particle_filters import add_particle_filter
from yt.analysis_modules.halo_finding.rockstar.api import RockstarHaloFinder
yt.enable_parallelism() # rockstar halofinding requires parallelism

# Create a dark matter particle filter
# This will be code dependent, but this function here is true for enzo

def DarkMatter(pfilter, data):
    filter = data[("all", "particle_type")] == 1 # DM = 1, Stars = 2
    return filter

add_particle_filter("dark_matter", function=DarkMatter, filtered_type='all', \
                    requires=["particle_type"])

# First, we make sure that this script is being run using mpirun with
# at least 3 processors as indicated in the comments above.
assert(yt.communication_system.communicators[-1].size >= 3)

# Load the dataset and apply dark matter filter
fn = "Enzo_64/DD0043/data0043"
ds = yt.load(fn)
ds.add_particle_filter('dark_matter')

# Determine highest resolution DM particle mass in sim by looking
# at the extrema of the dark_matter particle_mass field.
ad = ds.all_data()
min_dm_mass = ad.quantities.extrema(('dark_matter','particle_mass'))[0]
示例#20
0
def plot_standard_vcirc(sphere,
                        cylinder,
                        snap,
                        galaxy_name,
                        r_min=None,
                        r_max=None,
                        dr_factor=2,
                        vrot=True):
    """
	Your bog standard Vcirc plot, with the option to append rotation velocities to the plot.
	Requires stars, dark matter to be pre-filtered first
	"""

    from ramses_pp.analysis import utils, filter_utils

    if r_max == None:
        r_max = sphere["particle_positions_cylindrical_radius"].max().in_units(
            "kpc")


#		r_max = sphere.ds.arr(50,"kpc")

    if r_min == None:
        r_min = sphere.ds.arr(0, "kpc")

    # 1) get radial values
    r_indices, r_bins, r_filter, r_truths = utils.radial_indices(
        'particle_position_spherical_radius',
        sphere,
        r_min=None,
        r_max=r_max,
        dr_factor=2)

    ytsnap = snap.raw_snapshot()
    n_bins = len(r_bins)
    r_bins = ytsnap.arr(r_bins, "cmcm")
    m_bins_all = utils.mass_enclosed_bins(sphere,
                                          snap,
                                          r_bins,
                                          shape="sphere",
                                          type="all")
    m_bins_dark = utils.mass_enclosed_bins(sphere,
                                           snap,
                                           r_bins,
                                           shape="sphere",
                                           type="dark")
    m_bins_star = utils.mass_enclosed_bins(sphere,
                                           snap,
                                           r_bins,
                                           shape="sphere",
                                           type="stars")
    m_bins_gas = utils.mass_enclosed_bins(sphere,
                                          snap,
                                          r_bins,
                                          shape="sphere",
                                          type="gas")

    vcirc_all = utils.vcirc(r_bins, m_bins_all, sphere)
    vcirc_dark = utils.vcirc(r_bins, m_bins_dark, sphere)
    vcirc_star = utils.vcirc(r_bins, m_bins_star, sphere)
    vcirc_gas = utils.vcirc(r_bins, m_bins_gas, sphere)

    plt.plot(r_bins.in_units("kpc"),
             vcirc_all.in_units("km/s"),
             color="black",
             label=r"$V_{circ,all}$")
    plt.plot(r_bins.in_units("kpc"),
             vcirc_dark.in_units("km/s"),
             color="green",
             label=r"$V_{circ,dark}$")
    plt.plot(r_bins.in_units("kpc"),
             vcirc_star.in_units("km/s"),
             color="blue",
             label=r"$V_{circ,stars}$")
    plt.plot(r_bins.in_units("kpc"),
             vcirc_gas.in_units("km/s"),
             color="red",
             label=r"$V_{circ,gas}$")

    plt.xlabel("Radius [kpc]")
    plt.ylabel("Rotation Speed [km/s]")

    if vrot:
        # THE DISK SHOULD ALREADY BE FILTERED SPATIALLY KINDA
        print "doing stuff with vrot"
        min_z = sphere.ds.arr(-3.0, "kpc")
        max_z = sphere.ds.arr(3.0, "kpc")

        cold_disk = cylinder.cut_region(["obj['temperature'] < 1e4"])

        #		L = sphere.quantities.angular_momentum_vector(use_gas=True,use_particles=False)
        #		bv = sphere.get_field_parameter("bulk_velocity")
        #		L_mag = np.sqrt(np.power(L[0],2.0) + np.power(L[1],2.0) + np.power(L[2],2.0))
        #		L_norm = np.zeros(3)
        #		L_norm[0] = L[0].value/L_mag
        #		L_norm[1] = L[1].value/L_mag
        #		L_norm[2] = L[2].value/L_mag

        #		sphere.set_field_parameter("bulk_velocity",bv)
        #		sphere.set_field_parameter("normal",sphere.ds.arr(L_norm,"code_length"))

        #		cold_sphere.set_field_parameter("bulk_velocity",bv)
        #		cold_sphere.set_field_parameter("normal",sphere.ds.arr(L_norm,"code_length"))

        add_particle_filter("young_stars",
                            function=young_star_filter,
                            filtered_type="all",
                            requires=["particle_age"])
        cylinder.ds.add_particle_filter("young_stars")

        # cold gas

        print "filtering spatially"
        spatial_filter_tot = filter_utils.min_max_filter(
            cylinder, "particle_position_relative_z", min_z, max_z)
        spatial_filter_dark = filter_utils.min_max_filter(
            cylinder, ('dark', 'particle_position_relative_z'), min_z, max_z)
        spatial_filter_stars = filter_utils.min_max_filter(
            cylinder, ('stars', 'particle_position_relative_z'), min_z, max_z)
        spatial_filter_young_stars = filter_utils.min_max_filter(
            cylinder, ('young_stars', 'particle_position_relative_z'), min_z,
            max_z)

        r_tot = np.sqrt(
            np.power(
                cylinder["particle_position_relative_x"][spatial_filter_tot],
                2) + np.power(
                    cylinder["particle_position_relative_y"]
                    [spatial_filter_tot], 2))
        r_stars = np.sqrt(
            np.power(
                cylinder["stars", "particle_position_relative_x"]
                [spatial_filter_stars], 2) + np.power(
                    cylinder["stars", "particle_position_relative_y"]
                    [spatial_filter_stars], 2))
        r_young_stars = np.sqrt(
            np.power(
                cylinder["young_stars", "particle_position_relative_x"]
                [spatial_filter_young_stars], 2) + np.power(
                    cylinder["young_stars", "particle_position_relative_y"]
                    [spatial_filter_young_stars], 2))
        r_dark = np.sqrt(
            np.power(
                cylinder["dark", "particle_position_relative_x"]
                [spatial_filter_dark], 2) + np.power(
                    cylinder["dark", "particle_position_relative_y"]
                    [spatial_filter_dark], 2))

        #		r_gas = sphere["cylindrical_r"]
        #		r_cold_gas = cold_sphere["cylindrical_r"]

        print "computing vrots"
        #		vrot_tot = utils.manual_vrot(cylinder,type="all",r_filter = spatial_filter_tot)

        #		vrot_stars = utils.manual_vrot(cylinder,type="stars",r_filter = spatial_filter_stars)
        #		vrot_young_stars = utils.manual_vrot(cylinder,type="young_stars",r_filter = spatial_filter_young_stars)
        #		vrot_dark = utils.manual_vrot(cylinder,type="dark",r_filter = spatial_filter_dark)

        vrot_stars = yt.ProfilePlot(
            cylinder, ('stars', 'particle_position_cylindrical_radius'),
            [('stars', 'particle_velocity_cylindrical_theta')],
            weight_field=('stars', 'particle_mass'),
            n_bins=n_bins,
            x_log=False,
            y_log={('stars', 'particle_velocity_cylindrical_theta'): False})
        vrot_young_stars = yt.ProfilePlot(
            cylinder, ('young_stars', 'particle_position_cylindrical_radius'),
            [('young_stars', 'particle_velocity_cylindrical_theta')],
            weight_field=('young_stars', 'particle_mass'),
            n_bins=n_bins,
            x_log=False,
            y_log={
                ('young_stars', 'particle_velocity_cylindrical_theta'): False
            })
        vrot_dark = yt.ProfilePlot(
            cylinder, ('dark', 'particle_position_cylindrical_radius'),
            [('dark', 'particle_velocity_cylindrical_theta')],
            weight_field=('dark', 'particle_mass'),
            n_bins=n_bins,
            x_log=False,
            y_log={('dark', 'particle_velocity_cylindrical_theta'): False})

        r_stars_binned = vrot_stars.profiles[0].x.in_units("kpc").value
        r_young_stars_binned = vrot_young_stars.profiles[0].x.in_units(
            "kpc").value
        vrot_stars_binned = np.abs(vrot_stars.profiles[0][(
            'stars',
            'particle_velocity_cylindrical_theta')]).in_units("km/s").value
        vrot_young_stars_binned = np.abs(vrot_young_stars.profiles[0][(
            'young_stars',
            'particle_velocity_cylindrical_theta')]).in_units("km/s").value

        # this is not filtering in height yet

        vrot_gas = yt.ProfilePlot(cylinder,
                                  'cylindrical_r',
                                  ["velocity_cylindrical_theta"],
                                  weight_field="cell_mass",
                                  n_bins=n_bins,
                                  x_log=False,
                                  y_log={"velocity_cylindrical_theta": False})
        r_gas = vrot_gas.profiles[0].x
        vrot_gas = np.abs(vrot_gas.profiles[0]["velocity_cylindrical_theta"]
                          )  # this overwrites the yt plot object

        vrot_cold_gas = yt.ProfilePlot(
            cold_disk,
            'cylindrical_r', ["velocity_cylindrical_theta"],
            weight_field="cell_mass",
            n_bins=n_bins,
            x_log=False,
            y_log={"velocity_cylindrical_theta": False})
        r_cold_gas = vrot_cold_gas.profiles[0].x
        vrot_cold_gas = np.abs(
            vrot_cold_gas.profiles[0]["velocity_cylindrical_theta"])

        # bin the particle data
        print "binning the data"
        #	r_tot_binned, vrot_tot_binned = plot_manual_profile(r_tot,vrot_tot,units=["kpc","km/s"],filter=None,bins=30,abs=True,weight_profile="ones")
        #	r_stars_binned, vrot_stars_binned = plot_manual_profile(r_stars,vrot_stars,units=["kpc","km/s"],filter=None,bins=30,abs=True,weight_profile="ones")
        #	r_dark_binned, vrot_dark_binned = plot_manual_profile(r_dark,vrot_dark,units=["kpc","km/s"],filter=None,bins=30,abs=True,weight_profile="ones")
        #	r_young_stars_binned, vrot_young_stars_binned = plot_manual_profile(r_young_stars,vrot_young_stars,units=["kpc","km/s"],filter=None,bins=30,abs=True,weight_profile="ones")

        # make the plots look a little more pretty
        r_gas, vrot_gas = flatten_line(r_gas.in_units("kpc").value,
                                       vrot_gas.in_units("km/s").value,
                                       no_nan=False,
                                       extra_x=r_bins.in_units("kpc").max())
        # make the plots look a little more pretty
        r_cold_gas, vrot_cold_gas = flatten_line(
            r_cold_gas.in_units("kpc").value,
            vrot_cold_gas.in_units("km/s").value,
            no_nan=False,
            extra_x=r_bins.in_units("kpc").max())

        r_stars_binned, vrot_stars_binned = flatten_line(
            r_stars_binned,
            vrot_stars_binned,
            no_nan=True,
            append_max=True,
            double_zero=True,
            extra_x=r_bins.in_units("kpc").max())
        r_young_stars_binned, vrot_young_stars_binned = flatten_line(
            r_young_stars_binned,
            vrot_young_stars_binned,
            no_nan=True,
            append_max=True,
            double_zero=True,
            extra_x=r_bins.in_units("kpc").max())

        # finally do the plots
        print "plotting the data"
        #		plt.plot(r_dark,vrot_dark,label="vrot dark")
        plt.plot(r_stars_binned,
                 vrot_stars_binned,
                 label=r"$V_{rot,stars}$",
                 color="blue",
                 linestyle='dashed')
        plt.plot(r_young_stars_binned,
                 vrot_young_stars_binned,
                 label=r"$V_{rot,young stars}$",
                 color="purple",
                 linestyle='dashed')
        plt.plot(r_gas,
                 vrot_gas,
                 label=r"$V_{rot,gas}$",
                 color="red",
                 linestyle='dashed')
        plt.plot(r_cold_gas,
                 vrot_cold_gas,
                 label=r"$V_{rot,cold gas}$",
                 color="orange",
                 linestyle='dashed')

    plt.legend()
    plt.savefig(("%s_rot_circ.png" % galaxy_name))
    plt.savefig(("%s_rot_circ.pdf" % galaxy_name))
    plt.close()
示例#21
0
def lazy_load_galaxy(sim_name,
                     sim_patch="normal",
                     snap_no=None,
                     halo_id=None,
                     return_snap=True,
                     return_halos=True,
                     filter_stars=True,
                     filter_dark=True,
                     disk_h=10,
                     disk_w=50,
                     disk_units="kpccm"):
    """
	reads in the simulation and returns the galaxy, halo_sphere the ytsnapshot and the snap object
	since you find yourself doing this a lot, I figured it would make sense as a function in it'w own right
	"""
    sim = Simulation.load(sim_name)

    # super lazy mode activated
    if snap_no == None:
        snap = sim.snapshot(sim.num_snapshots(), module="yt", patch=sim_patch)
    else:
        snap = sim.snapshot(snap_no, module="yt", patch=sim_patch)
    if halo_id == None:
        halo_id = 0

    ytsnap = snap.raw_snapshot()
    all_data = ytsnap.all_data()

    halos = snap.halos()
    print halos
    print halos[0]["pos"], halos[0]["Rvir"]
    galaxy_halo = halos[halo_id]
    print galaxy_halo
    print "getting halo sphere"
    halo_sphere = ytsnap.sphere(galaxy_halo["pos"], galaxy_halo["Rvir"])
    add_particle_filter("stars",
                        function=star_filter,
                        filtered_type="all",
                        requires=["particle_age"])
    halo_sphere.ds.add_particle_filter("stars")
    add_particle_filter("dark",
                        function=dark_filter,
                        filtered_type="all",
                        requires=["particle_age"])
    halo_sphere.ds.add_particle_filter("dark")
    disk_height = ytsnap.arr(disk_h, disk_units)
    disk_width = ytsnap.arr(disk_w, disk_units)

    cylinder, disks = load_disk_data(snap,
                                     sim_name,
                                     sim_patch,
                                     halo_id=halo_id,
                                     snapno=None,
                                     n_disks=1,
                                     disk_h=disk_height,
                                     disk_w=disk_width,
                                     cylinder_w=disk_width,
                                     cylinder_h=disk_height,
                                     extra=None,
                                     overwrite=True,
                                     save=False,
                                     center=None,
                                     normal=None)

    add_particle_filter("stars",
                        function=star_filter,
                        filtered_type="all",
                        requires=["particle_age"])
    cylinder.ds.add_particle_filter("stars")

    add_particle_filter("dark",
                        function=dark_filter,
                        filtered_type="all",
                        requires=["particle_age"])
    cylinder.ds.add_particle_filter("dark")

    return cylinder, halo_sphere, ytsnap, snap
示例#22
0
def load_disk_data(snap,
                   sim_name,
                   sim_patch,
                   halo_id=0,
                   snapno=None,
                   n_disks=1,
                   disk_h=None,
                   disk_w=None,
                   cylinder_w=None,
                   cylinder_h=None,
                   extra=None,
                   overwrite=False,
                   save=True,
                   center=None,
                   normal=None):
    """
	Efficient way of loading disks and cylinder
	designed to take either a redshift or a snapshot number
	use this for effective loops
	processes can be speeded up by reloading data if it already exists
	"""

    if disk_h == None:
        disk_h = snap.raw_snapshot().arr(5, "kpccm")

    if disk_w == None:
        disk_w = snap.raw_snapshot().arr(50, "kpccm")

    if cylinder_w == None:
        cylinder_w = snap.raw_snapshot().arr(50, "kpccm")

    if cylinder_h == None:
        cylinder_h = snap.raw_snapshot().arr(5, "kpccm")

    if overwrite == True:
        halos = snap.halos()
        print halos[halo_id]["pos"].in_units("kpccm"), "halo_location"
        disks, cylinder = halos[halo_id].galaxy_disk(n_disks=n_disks,
                                                     disk_h=disk_h,
                                                     disk_w=disk_w,
                                                     cylinder_w=cylinder_w,
                                                     cylinder_h=cylinder_h,
                                                     center=center,
                                                     normal=normal)

        if extra == "young":  # lets load disks based on the position of the youngest stars
            add_particle_filter("young_stars",
                                function=young_star_filter,
                                filtered_type="all",
                                requires=["particle_age"])
            sphere.ds.add_particle_filter("young_stars")
            disk_length = cylinder_all[
                "young_stars",
                "particle_position_cylindrical_radius"].in_units("kpc").max()
            #from the cylinder, grab the distance of the furthest young star
            # and then enter some recursion
            return load_disk_data(snap,
                                  sim_name,
                                  sim_patch,
                                  halo_id=halo_id,
                                  n_disks=n_disks,
                                  disk_h=disk_h,
                                  disk_w=disk_length,
                                  cylinder_w=disk_length,
                                  cylinder_h=cylinder_h,
                                  extra=None,
                                  overwrite=True,
                                  save=save,
                                  center=center,
                                  normal=normal)

        elif extra == "density":
            # find the radius at which the stellar density is at 10 Msun/pc
            return load_disk_data(snap,
                                  sim_name,
                                  sim_patch,
                                  halo_id=halo_id,
                                  n_disks=n_disks,
                                  disk_h=disk_h,
                                  disk_w=disk_w,
                                  cylinder_w=disk_w,
                                  cylinder_h=cylinder_h,
                                  extra=None,
                                  overwrite=True,
                                  save=save,
                                  center=center,
                                  normal=normal)
        else:
            # will fix it for disks later
            #			for i in range(0,n_disks):
            #				disks[i].save_object((str(halo_id) + "_disk_" + str(i)),(object_storage + "_" + sim_name + "_" + str(snap.output_number) + ".cpkl"  ) )
            print object_storage + sim_name + "_" + str(
                snap.output_number()) + ".cpkl"
            if save:
                cylinder.save_object((str(halo_id) + "_cylinder"),
                                     (object_storage + sim_name + "_" +
                                      str(snap.output_number()) + ".cpkl"))
            return cylinder, disks
    else:
        # might be worth storing the number of disks somewhere safe
        # lets reload these objects rather than spend time recomputing them

        ds = snap.raw_snapshot()
        disks = []
        try:
            data_file = shelve.open((object_storage + sim_name + "_" +
                                     str(snap.output_number()) + ".cpkl"))
        except:
            print "data object does not exist, going to make it"
            return load_disk_data(snap,
                                  sim_name,
                                  sim_patch,
                                  halo_id=halo_id,
                                  n_disks=n_disks,
                                  disk_h=disk_h,
                                  disk_w=disk_w,
                                  cylinder_w=cylinder_w,
                                  cylinder_h=cylinder_h,
                                  extra=extra,
                                  overwrite=True,
                                  save=save,
                                  center=center,
                                  normal=normal)


#		for i in range(0,n_disks):
#			ds, disk = data_file[(str(halo_id) + "_disk_" + str(i))]
#			disks.append(disk)
        ds, cylinder = data_file[(str(halo_id) + "_cylinder")]
        return cylinder, disks
示例#23
0
def tipsy_field_add(fname,bounding_box = None ,ds=None,add_smoothed_quantities=True):

    def _gassmoothinglength(field,data):
        return data[("Gas", "smoothing_length")].in_units('pc')

    def _starmetals(field,data):
        return data[("newstars", "Metals")]
    
    def _starcoordinates(field,data):
        return data[("newstars", "Coordinates")]

    def _starformationtime(field,data):
        return data[("newstars", "FormationTime")]

    def _stellarages(field,data):
        ad = data.ds.all_data()
        simtime = data.ds.current_time.in_units('Gyr')
        simtime = simtime.value
        age = simtime - data[("newstars","FormationTime")].in_units('Gyr').value
        age[np.where(age < 1.e-3)[0]] = 1.e-3
        age = data.ds.arr(age,'Gyr')
        return age

    def _starmasses(field,data):
        return data[("newstars", "Mass")]


    def _diskstarcoordinates(field,data):
        return data[("diskstars", "Coordinates")]
        
    def _diskstarmasses(field,data):
        return data[("diskstars", "Mass")]
    
    
    def _gasdensity(field,data):
        return data[("Gas", "Density")]

    def _gasmetals(field,data):
        return data[("Gas", "Metals")]
        
    def _gascoordinates(field,data):
        return data[("Gas", "Coordinates")]

    def _gassmootheddensity(field,data):
        if float(yt.__version__[0:3]) >= 4:
            return data.ds.parameters['octree'][("Gas", "Density")]
        else:
            return data[("deposit", "Gas_density")]
    
    def _gassmoothedmetals(field,data):
        if float(yt.__version__[0:3]) >= 4:
            return data.ds.parameters['octree'][("Gas", "Metals")]
        else:
            return data[("deposit", "Gas_smoothed_metallicity")]
            # Does this field exist?
        
    def _gassmoothedmasses(field,data):
        if float(yt.__version__[0:3]) >= 4:
            return data.ds.parameters['octree'][("Gas", "Mass")]
        else:
            return data[("deposit", "Gas_mass")]

    def _gasmasses(field,data):
        return data[("Gas","Mass")]

    def _dustmass_dtm(field,data):
        return (data[("Gas","Metals")]*data[("Gas","Mass")]*cfg.par.dusttometals_ratio)

    def _li_ml_dustmass(field,data):
        return (data.ds.arr(data.ds.parameters['li_ml_dustmass'].value,'code_mass'))


    def _dustmass_rr(field,data):
        #hard coded values from remy-ruyer table 1
        a = 2.21
        alpha = 2.02
        x_sun = 8.69

        x = 12.+np.log10(data["Gas","Metals"]/cfg.par.solar * 10.**(x_sun-12.) )
        y = a + alpha*(x_sun-np.asarray(x))
        gas_to_dust_ratio = 10.**(y)
        dust_to_gas_ratio = 1./gas_to_dust_ratio
        return dust_to_gas_ratio * data["Gas","Mass"]

    def _dustmass_li_bestfit(field,data):
        log_dust_to_gas_ratio = (2.445*np.log10(data["Gas","Metals"]/cfg.par.solar))-(2.029)
        dust_to_gas_ratio = 10.**(log_dust_to_gas_ratio)
        return dust_to_gas_ratio * data["Gas","Mass"]


    def _dustsmoothedmasses(field, data):
        if float(yt.__version__[0:3]) >= 4:
            return (data.ds.parameters['octree'][("dust","mass")])
            
        else:
            return (data.ds.arr(data[("Gas", "dust_mass")].value, 'code_mass'))


    def _li_ml_dustsmoothedmasses(field,data):
        return (data.ds.parameters['octree'][("Gas", "li_ml_dustmass")])


    def _metaldens(field,data):
        return (data["Gas","Density"]*data["Gas","Metals"])

    def _gasfh2(field,data):
        try: return data[("Gas","H2")]
        except: return (data.ds.arr(data[("Gas", "Mass")].value*0, 'dimensionless'))

    def _gassfr(field,data):
        instsfr = data.ds.arr(data[("Gas", "Mass")].value*0, 'Msun/yr')
        # temperature below which SF can happen (K)
        try: tempcut = ds.quan(ds.parameters["dTempMax"],'K')
        except: tempcut = ds.quan(10**3,'K') # default for g14 sims
        denscut = ds.quan(100*1.67*10**-24,'g/cm**3') # density above which SF can happen - default for g14 sims
        # star formation timescale (s)
        try: deltat = ds.quan(ds.parameters["dDeltaStarForm"]*3.15569*10**7,'s')
        except: deltat = ds.quan(10**6*3.15569*10**7,'s') # 1 Myr
        # Star formation efficiency
        try: cstarfac = ds.parameters["dCStar"]
        except: cstarfac = 0.15
        # Mass at which stars form (Msol)
        try: massform = ds.quan(ds.parameters["dInitStarMass"]*ds.parameters["dMsolUnit"],'Msun')
        except: massform = max(data[("newstars", "Mass")])
        SFposs = np.where((data[("Gas","Temperature")]<tempcut) & (data[("Gas","Density")]>denscut))
        try: cstar = cstarfac*data[("Gas","H2")][SFposs] # SF efficiency with molecular hydrogen
        except: cstar = cstarfac*data[("Gas","Mass")][SFposs]/data[("Gas","Mass")][SFposs]
        dynt = 1.0/np.sqrt(data[("Gas","Density")][SFposs]*4.0*np.pi*G)
        SFeff = 1.0 - np.e**(-1.0*cstar*deltat/dynt)
        instsfr[SFposs] = (data[("Gas","Mass")][SFposs]/massform)*SFeff
        return instsfr

    if fname != None:
        ds = yt.load(fname)
        ds.index
    
    #if we're in the 4.x branch of yt, load up the octree for smoothing
    if float(yt.__version__[0:3]) >= 4:
        left = np.array([pos[0] for pos in bounding_box])
        right = np.array([pos[1] for pos in bounding_box])
        # Add option for scatter vs gather to parameters_master file?
        octree = ds.octree(left,right,n_ref=cfg.par.n_ref)
        ds.parameters['octree'] = octree
    

    #set up particle filters to figure out which stars might have been
    #initalized with the simulation.  we'll call stars that are formed
    #in the simulation 'new_stars' (no matter how old they are), and
    #stars that are initalized with the simulation as 'diskstars'.
    #Assume that no cosmology someone uses will give us a Hubble time
    #> 15 Gyr.

    def newstars(pfilter, data):
        age = data.ds.current_time - data[pfilter.filtered_type, "creation_time"]
        filter = np.logical_and(age.in_units('Gyr') <= 15, age.in_units('Gyr') >= 0)
        return filter

    def diskstars(pfilter, data):
        age = data.ds.current_time - data[pfilter.filtered_type, "creation_time"]
        filter = np.logical_or(age.in_units('Gyr') >= 15, age.in_units('Gyr') <= 0)
        return filter


    add_particle_filter("newstars", function=newstars, filtered_type='Stars', requires=["creation_time"])
    add_particle_filter("diskstars", function=diskstars, filtered_type='Stars', requires=["creation_time"])

    ds.add_particle_filter("newstars")
    ds.add_particle_filter("diskstars")

    ad = ds.all_data()

    #add the regular powderday fields
    ds.add_field(("star","metals"),function=_starmetals,units="code_metallicity",sampling_type='particle')
    ds.add_field(("star","coordinates"),function=_starcoordinates,units='cm',sampling_type='particle')
    ds.add_field(("star","formationtime"),function=_starformationtime,units='Gyr',sampling_type='particle')
    ds.add_field(("stellar","ages"),function=_stellarages,units='Gyr',sampling_type='particle')
    ds.add_field(("star","masses"),function=_starmasses,units='g',sampling_type='particle')
    ds.add_field(("gas","density"),function=_gasdensity,units='g/cm**3',sampling_type='particle')
    ds.add_field(("gas","metals"),function=_gasmetals,units="code_metallicity",sampling_type='particle')
    ds.add_field(("gas","coordinates"),function=_gascoordinates,units='cm',sampling_type='particle')
    if add_smoothed_quantities == True:
        ds.add_field(("gas","smootheddensity"),function=_gassmootheddensity,units='g/cm**3',sampling_type='particle')
        ds.add_field(("gas","smoothedmetals"),function=_gassmoothedmetals,units='code_metallicity',sampling_type='particle')
        ds.add_field(("gas","smoothedmasses"),function=_gassmoothedmasses,units='g',sampling_type='particle')
    ds.add_field(("gas","masses"),function=_gasmasses,units='g',sampling_type='particle')
    ds.add_field(("gas","fh2"),function=_gasfh2,units='dimensionless',sampling_type='particle')
    ds.add_field(("gas","sfr"),function=_gassfr,units='g/s',sampling_type='particle')
    ds.add_field(("gas","smoothinglength"),function=_gassmoothinglength,units='pc',sampling_type='particle')
    ds.add_field(("metal","dens"),function=_metaldens,units="g/cm**3", sampling_type='particle')
    #only add the disk star fields if there are any disk stars
    if len(ad["diskstars","Mass"]) > 0 :
        ds.add_field(("diskstar","masses"),function=_diskstarmasses,units='g',sampling_type='particle')
        ds.add_field(("diskstar","coordinates"),function=_diskstarcoordinates,units='cm',sampling_type='particle')

    #add the dust mass, but only if we're using the DTM dust mass
    if cfg.par.dust_grid_type == 'dtm':
        ds.add_field(("dust","mass"), function=_dustmass_dtm,units='code_mass',sampling_type='particle')

    if cfg.par.dust_grid_type == 'rr':
        ds.add_field(("dust","mass"),function=_dustmass_rr,  units='code_mass',sampling_type='particle')



    if cfg.par.dust_grid_type == 'li_ml':
        if float(yt.__version__[0:3]) < 4:
            raise KeyError("li_ml is not implemented for tipsy front ends with yt<4. Please set another dust grid type in the parameters or upgrade to yt4")
        #the issue is that we can't smooth the dust onto a grid that
        #is necessary in dust_grid_gen/li_ml_oct because yt3.x
        #requires a field: ('PartType0', 'particle_position').
        else:
        #get the dust to gas ratio
            ad = ds.all_data()
            li_ml_dgr = dgr_ert(ad["Gas","Metals"],ad["gas","sfr"],ad["Gas","Mass"])
            li_ml_dustmass = ((10.**li_ml_dgr)*ad["Gas","Mass"]).in_units('code_mass')
            #this is an icky way to pass this to the function for ds.add_field in the next line. but such is life.
            ds.parameters['li_ml_dustmass'] = li_ml_dustmass
            ds.add_field(("Gas","li_ml_dustmass"),function=_li_ml_dustmass,units='code_mass',sampling_type='particle')
            #just adding a new field that is called 'dustmass' so that we
            #can save it later in analytics.
            ds.add_field(("dust","mass"),function=_li_ml_dustmass,units='code_mass',sampling_type='particle')
            ds.add_deposited_particle_field(("Gas","li_ml_dustmass"),"sum")
            if add_smoothed_quantities == True:
                ds.add_field(("Gas","li_ml_dustsmoothedmasses"), function=_li_ml_dustsmoothedmasses,units='code_mass',sampling_type='particle')


    if cfg.par.dust_grid_type == 'li_bestfit':
        ds.add_field(("dust","mass"),function=_dustmass_li_bestfit,  units='code_mass',sampling_type='particle')

    ad = ds.all_data()
    return ds
示例#24
0
    age = (data.ds.current_time -
           data["Stars", "creation_time"]).in_units("Myr")
    filter = np.logical_and(age >= 10, age < 100)
    return filter


def stars_old(pfilter, data):
    age = data.ds.current_time - data["Stars", "creation_time"]
    filter = np.logical_or(age < 0, age.in_units("Myr") >= 100)
    return filter


# Create the particle filters
add_particle_filter(
    "stars_young",
    function=stars_10Myr,
    filtered_type="Stars",
    requires=["creation_time"],
)
add_particle_filter(
    "stars_medium",
    function=stars_100Myr,
    filtered_type="Stars",
    requires=["creation_time"],
)
add_particle_filter("stars_old",
                    function=stars_old,
                    filtered_type="Stars",
                    requires=["creation_time"])

# Load a dataset and apply the particle filters
filename = "TipsyGalaxy/galaxy.00300"
示例#25
0
def enzo_field_add(fname, ds=None, starages=False):
    def _starmetals(field, data):
        return data[('newstars', 'metallicity_fraction')]

    def _starcoordinates(field, data):
        #set units of cm then tack them back on because the column_stack loses them
        xpos = data[('newstars', 'particle_position_x')].in_units("cm")
        ypos = data[('newstars', 'particle_position_y')].in_units("cm")
        zpos = data[('newstars', 'particle_position_z')].in_units("cm")
        coordinates = np.column_stack((xpos, ypos, zpos))
        coordinates = data.ds.arr(coordinates, "cm")
        return coordinates

    def _stellarages(field, data):
        age = ds.current_time.in_units('Gyr') - data[
            ('newstars', 'creation_time')].in_units('Gyr')
        age[np.where(age < 1.e-3)[0]] = 1.e-3
        return age

    def _starmasses(field, data):
        return data[('newstars', 'particle_mass')]

    def _gasdensity(field, data):
        return data[('gas', 'density')]

    def _gasmetals(field, data):
        return data[('gas', 'metallicity')]

    def _gasmasses(field, data):
        return data[('gas', 'cell_mass')]

    def _gasfh2(field, data):
        try:
            return data[('gas', 'FractionH2')]
        except:
            return data[('gas',
                         'metallicity')] * 0.  #just some dimensionless array

    #load the ds
    if fname != None:
        ds = yt.load(fname)
        ds.index

    #set up particle_filters to figure out which particles are stars.
    #we'll call particles that have ages > 0 stars.

    def newstars(pfilter, data):
        age = data[pfilter.filtered_type, "creation_time"]
        filter = age.in_units('Gyr') > 0
        return filter

    add_particle_filter("newstars",
                        function=newstars,
                        filtered_type='all',
                        requires=["creation_time"])
    ds.add_particle_filter("newstars")
    ad = ds.all_data()

    ds.add_field(('star', 'metals'),
                 function=_starmetals,
                 units="code_metallicity",
                 sampling_type='particle')
    ds.add_field(('star', 'coordinates'),
                 function=_starcoordinates,
                 units="cm",
                 sampling_type='particle')
    ds.add_field(('stellar', 'ages'),
                 function=_stellarages,
                 units='Gyr',
                 sampling_type='particle')
    ds.add_field(('star', 'masses'),
                 function=_starmasses,
                 units='g',
                 sampling_type='particle')
    ds.add_field(('gas', 'density'),
                 function=_gasdensity,
                 units='g/cm**3',
                 sampling_type='cell')
    ds.add_field(('gas', 'metals'),
                 function=_gasmetals,
                 units="code_metallicity",
                 sampling_type='cell')
    ds.add_field(('gas', 'fh2'),
                 function=_gasfh2,
                 units='dimensionless',
                 sampling_type='cell')
    ds.add_field(('gas', 'masses'),
                 function=_gasmasses,
                 units='g',
                 sampling_type='cell')

    ad = ds.all_data()

    return ds
示例#26
0
import yt
import numpy as np
from yt.data_objects.particle_filters import add_particle_filter
from matplotlib import pyplot as plt


def formed_star(pfilter, data):
    filter = data["all", "creation_time"] > 0
    return filter


add_particle_filter("formed_star",
                    function=formed_star,
                    filtered_type="all",
                    requires=["creation_time"])

filename = "IsolatedGalaxy/galaxy0030/galaxy0030"

ds = yt.load(filename)
ds.add_particle_filter("formed_star")
ad = ds.all_data()
masses = ad["formed_star", "particle_mass"].in_units("Msun")
formation_time = ad["formed_star", "creation_time"].in_units("yr")

time_range = [0, 5e8]  # years
n_bins = 1000
hist, bins = np.histogram(
    formation_time,
    bins=n_bins,
    range=time_range,
)
示例#27
0
def decomp_stars(data,
                 snap,
                 disk_min=0.8,
                 disk_max=1.1,
                 plot=False,
                 r_min=None,
                 r_max=None,
                 spline=False,
                 sim_object_type=None,
                 manual_jz_flag=False,
                 reverse_orientation=True,
                 AMR=True,
                 type="stars"):
    """
	At the moment, this technique can only filter for disk stars
	This is computed by calculating the ratio of Jz/Jcirc
	See this paper http://arxiv.org/pdf/1210.2578.pdf
	returns the indices, id's and the ratio
	"""
    print "starting decomp stars"
    try:
        data["stars", "particle_index"]
    except:  # stars field does not exist, lets add it
        print "adding stars field to data"
        add_particle_filter("stars",
                            function=star_filter,
                            filtered_type="all",
                            requires=["particle_age"])
        data.ds.add_particle_filter("stars")
    print "decomposing stars into disk and non-disk, please wait"
    if AMR == True and type == "gas":
        print "step on the gas"
        print "field len", len(data["index", "spherical_radius"])
        r_indices, r_bins, r_filter, r_truths = radial_indices(
            ("index", "spherical_radius"), data, r_min, r_max)
    else:
        print "stars"
        print "field len", len(data[type,
                                    "particle_spherical_position_radius"])
        r_indices, r_bins, r_filter, r_truths = radial_indices(
            (type, "particle_spherical_position_radius"), data, r_min, r_max)
    print "LENGTHS"
    print len(r_indices), len(r_bins), len(r_filter), len(r_truths)
    # THIS IS NEEDED FOR THE CORRECT JZ AND JCIRC
    m_bins = mass_enclosed_bins(data,
                                snap,
                                r_bins,
                                shape="sphere",
                                type="all",
                                sim_object_type=sim_object_type,
                                AMR=AMR)
    v_circ = vcirc(r_bins, m_bins, data)
    j_circ = jcirc(data, r_indices, v_circ, r_filter, type=type, AMR=AMR)

    if manual_jz_flag == False:
        j_z = jz(data,
                 r_filter=r_filter,
                 type=type,
                 reverse_orientation=reverse_orientation,
                 AMR=AMR)
    else:
        j_z = manual_jz(data, r_filter=r_filter, type=type, AMR=AMR)

    try:
        test = r_bins.in_units("cmcm")
        min_unit = "cmcm"
    except yt.units.unit_object.UnitParseError:
        min_unit = "cm"

    print "test lengths"
    print len(j_z), "j_z"
    print len(j_circ), "j_circ"
    print len(r_truths), "r_truths"
    print len(r_indices), "r_indices"

    if min_unit == "cmcm":
        ratio = data.ds.arr(
            j_z.in_units("kpccm**2/s").value /
            j_circ.in_units("kpccm**2/s").value, "dimensionless")
    else:
        ratio = data.ds.arr(
            j_z.in_units("kpc**2/s").value / j_circ.in_units("kpc**2/s").value,
            "dimensionless")
    # get indices of stars which satisfy the conditions

    # expand ratio into context of origonal array
    if AMR == True and type == "gas":
        ratio_expanded = np.zeros((len(data["gas", "cell_mass"])))
    else:
        ratio_expanded = np.zeros(
            (len(data[type, "particle_spherical_position_radius"])))
    j = 0
    for i in range(0, len(r_truths)):
        # if false, insert a dummy value that will never get through the filter
        if r_truths[i] == False:
            ratio_expanded[i] = -99999
        else:
            ratio_expanded[i] = ratio[j]
            j += 1

    x = np.logical_and(ratio_expanded >= disk_min, ratio_expanded <= disk_max)
    y = np.where(x == True)
    disk_star_indices = ratio_expanded[y]

    if AMR == True and type == "gas":
        disk_star = data["gas", "cell_mass"][y]
    else:
        disk_star = data[type, "particle_index"][y]

    print "NUMBER OF DISK", len(disk_star)

    if plot != None:

        plot_utils.plot_pdf(ratio, (plot + "_jzjcirc_dist.png"),
                            "jz/jcirc",
                            "PDF",
                            x_min=-1.0,
                            x_max=1.5,
                            nbins=100,
                            spline=spline)


#		weights = np.ones_like(ratio)/len(ratio)
#		from scipy.interpolate import UnivariateSpline
#		x_vals = bins[:-1] + ((bins[1] - bins[0]) / 2.0 )
#		f = UnivariateSpline(x_vals, hist, s=100)
#		plt.plot(x_vals,f(x_vals),"r-")
#		plt.xlabel('jz/jcirc')
#		plt.ylabel('Distribution')
#		plt.axis([-1.0, 1.5,0.0,(max(hist) + (max(hist) * 0.1))])
#		plt.savefig(plot + "_jzjcirc_dist.png")
#		plt.close()

# attempt 2
#from scipy.stats import rv_continuous

#	x_plot = np.linspace(-1.0,1.5,1000)
#		fig = plt.figure()
#		ax = fig.add_subplot(1,1,1)
#		ax.hist(ratio, bins=100, normed=True)
#		ax.plot(x_plot, rv_continuous.pdf(ratio), "r-", label="pdf")
#		ax.legend(loc="best")
#
#		plt.xlabel('jz/jcirc')
##		plt.ylabel('Distribution')
#		plt.axis([-1.0, 1.5,0.0,0.1])
#		plt.savefig(plot + "_jzjcirc_dist2.png")
#		plt.close()

#		hist, bin_edges = np.histogram(ratio,bins=300)
#
#
#		real_bins_temp = np.resize(bin_edges,len(bin_edges)-1)
#		bins = real_bins_temp + 0.5 * np.diff(bin_edges)
#		y = np.zeros(len(hist))
##                inverse_density_function = sp.interpolate.interp1d(
#		for i in range(0,len(y)):
#			y[i] = hist[i].astype(float) /
#
#		l = plt.plot(bins,y,"r",linewidth=1, marker="o")
#		plt.xlabel('jz/jcirc')
#		plt.ylabel('Distribution')
#		plt.axis([-1.0, 1.5,0.0,(y.max() + 0.02)])
#		plt.savefig(plot + "jzjcirc_dist.png")
#		plt.close()

    return disk_star_indices, disk_star, ratio, x
示例#28
0
def tipsy_field_add(fname,
                    bounding_box=None,
                    ds=None,
                    add_smoothed_quantities=True):
    def _starmetals(field, data):
        return data[('newstars', 'Metals')]

    def _starcoordinates(field, data):
        return data[('newstars', 'Coordinates')]

    def _starformationtime(field, data):
        return data[('newstars', 'FormationTime')]

    def _stellarages(field, data):
        ad = data.ds.all_data()
        simtime = data.ds.current_time.in_units('Gyr')
        simtime = simtime.value
        age = simtime - ad["starformationtime"].in_units('Gyr').value
        age[np.where(age < 1.e-3)[0]] = 1.e-3
        age = data.ds.arr(age, 'Gyr')
        return age

    def _starmasses(field, data):
        return data[('newstars', 'Mass')]

    def _diskstarcoordinates(field, data):
        return data[('diskstars', 'Coordinates')]

    def _diskstarmasses(field, data):
        return data[("diskstars", "Mass")]

    def _gasdensity(field, data):
        return data[('Gas', 'Density')]

    def _gasmetals(field, data):
        return data[('Gas', 'Metals')]

    def _gascoordinates(field, data):
        return data[('Gas', 'Coordinates')]

    def _gassmootheddensity(field, data):
        return data[('deposit', 'Gas_density')]

    def _gassmoothedmetals(field, data):
        return data[('deposit', 'Gas_smoothed_metallicity')]

    def _gassmoothedmasses(field, data):
        return data[('deposit', 'Gas_mass')]

    def _gasmasses(field, data):
        return data[('Gas', 'Mass')]

    def _metaldens(field, data):
        return (data["Gas", "Density"] * data["Gas", "Metals"])

    def _gasfh2(field, data):
        try:
            return data[('PartType0', 'FractionH2')]  # change this
        except:
            return (data.ds.arr(data[("Gas", "Mass")].value * 0,
                                'dimensionless'))

    def _gassfr(field, data):
        try:
            return data[('PartType0', 'StarFormationRate')]  # change this
        except:
            return (data.ds.arr(data[("Gas", "Mass")].value * 0,
                                'code_mass/code_time'))

    if fname != None:
        ds = yt.load(fname,
                     over_refine_factor=cfg.par.oref,
                     n_ref=cfg.par.n_ref)
        ds.index

    #set up particle filters to figure out which stars might have been
    #initalized with the simulation.  we'll call stars that are formed
    #in the simulation 'new_stars' (no matter how old they are), and
    #stars that are initalized with the simulation as 'diskstars'.
    #Assume that no cosmology someone uses will give us a Hubble time
    #> 15 Gyr.

    def newstars(pfilter, data):
        age = data.ds.current_time - data[pfilter.filtered_type,
                                          "creation_time"]
        filter = np.logical_and(
            age.in_units('Gyr') <= 15,
            age.in_units('Gyr') >= 0)
        return filter

    def diskstars(pfilter, data):
        age = data.ds.current_time - data[pfilter.filtered_type,
                                          "creation_time"]
        filter = np.logical_or(
            age.in_units('Gyr') >= 15,
            age.in_units('Gyr') <= 0)
        return filter

    add_particle_filter("newstars",
                        function=newstars,
                        filtered_type='Stars',
                        requires=["creation_time"])
    add_particle_filter("diskstars",
                        function=diskstars,
                        filtered_type='Stars',
                        requires=["creation_time"])

    ds.add_particle_filter("newstars")
    ds.add_particle_filter("diskstars")

    ad = ds.all_data()

    #add the regular powderday fields
    ds.add_field(('starmetals'),
                 function=_starmetals,
                 units="code_metallicity",
                 particle_type=True)
    ds.add_field(('starcoordinates'),
                 function=_starcoordinates,
                 units='cm',
                 particle_type=True)
    ds.add_field(('starformationtime'),
                 function=_starformationtime,
                 units='Gyr',
                 particle_type=True)
    ds.add_field(('stellarages'),
                 function=_stellarages,
                 units='Gyr',
                 particle_type=True)
    ds.add_field(('starmasses'),
                 function=_starmasses,
                 units='g',
                 particle_type=True)
    ds.add_field(('gasdensity'),
                 function=_gasdensity,
                 units='g/cm**3',
                 particle_type=True)
    ds.add_field(('gasmetals'),
                 function=_gasmetals,
                 units="code_metallicity",
                 particle_type=True)
    ds.add_field(('gascoordinates'),
                 function=_gascoordinates,
                 units='cm',
                 particle_type=True)
    if add_smoothed_quantities == True:
        ds.add_field(('gassmootheddensity'),
                     function=_gassmootheddensity,
                     units='g/cm**3',
                     particle_type=True)
        ds.add_field(('gassmoothedmetals'),
                     function=_gassmoothedmetals,
                     units='code_metallicity',
                     particle_type=True)
        ds.add_field(('gassmoothedmasses'),
                     function=_gassmoothedmasses,
                     units='g',
                     particle_type=True)
    ds.add_field(('gasmasses'),
                 function=_gasmasses,
                 units='g',
                 particle_type=True)
    ds.add_field(('gasfh2'),
                 function=_gasfh2,
                 units='dimensionless',
                 particle_type=True)
    ds.add_field(('gassfr'), function=_gassfr, units='g/s', particle_type=True)
    ds.add_field(('metaldens'),
                 function=_metaldens,
                 units="g/cm**3",
                 particle_type=True)
    #only add the disk star fields if there are any disk stars
    if len(ad["diskstars", "Mass"]) > 0:
        ds.add_field(('diskstarmasses'),
                     function=_diskstarmasses,
                     units='g',
                     particle_type=True)
        ds.add_field(('diskstarcoordinates'),
                     function=_diskstarcoordinates,
                     units='cm',
                     particle_type=True)

    ad = ds.all_data()
    return ds
    age = data.ds.current_time - data["Stars", "creation_time"]
    filter = np.logical_and(age >= 0, age.in_units('Myr') < 10)
    return filter

def stars_100Myr(pfilter, data):
    age = (data.ds.current_time - data["Stars", "creation_time"]).in_units('Myr')
    filter = np.logical_and(age >= 10, age < 100)
    return filter

def stars_old(pfilter, data):
    age = data.ds.current_time - data["Stars", "creation_time"]
    filter = np.logical_or(age < 0, age.in_units('Myr') >= 100)
    return filter

# Create the particle filters
add_particle_filter("stars_young", function=stars_10Myr, filtered_type='Stars',
                    requires=["creation_time"])
add_particle_filter("stars_medium", function=stars_100Myr, filtered_type='Stars',
                    requires=["creation_time"])
add_particle_filter("stars_old", function=stars_old, filtered_type='Stars',
                    requires=["creation_time"])

# Load a dataset and apply the particle filters
filename = "TipsyGalaxy/galaxy.00300"
ds = yt.load(filename)
ds.add_particle_filter('stars_young')
ds.add_particle_filter('stars_medium')
ds.add_particle_filter('stars_old')

# What are the total masses of different ages of star in the whole simulation 
# volume?
ad = ds.all_data()
示例#30
0
import yt
from yt.extensions.astro_analysis.halo_analysis.halo_catalog import HaloCatalog
from yt.data_objects.particle_filters import add_particle_filter
from yt.extensions.astro_analysis.halo_finding.rockstar.api import RockstarHaloFinder
yt.enable_parallelism()  # rockstar halofinding requires parallelism

# Create a dark matter particle filter
# This will be code dependent, but this function here is true for enzo


def DarkMatter(pfilter, data):
    filter = data[("all", "particle_type")] == 1  # DM = 1, Stars = 2
    return filter

add_particle_filter("dark_matter", function=DarkMatter, filtered_type='all', \
                    requires=["particle_type"])

# First, we make sure that this script is being run using mpirun with
# at least 3 processors as indicated in the comments above.
assert (yt.communication_system.communicators[-1].size >= 3)

# Load the dataset and apply dark matter filter
fn = "Enzo_64/DD0043/data0043"
ds = yt.load(fn)
ds.add_particle_filter('dark_matter')

# Determine highest resolution DM particle mass in sim by looking
# at the extrema of the dark_matter particle_mass field.
ad = ds.all_data()
min_dm_mass = ad.quantities.extrema(('dark_matter', 'particle_mass'))[0]
示例#31
0
fileout = "fig__star_formation_rate"
nbin = 50
dpi = 150

# load data
ds = yt.load(filein)


# define the particle filter for the newly formed stars
def new_star(pfilter, data):
    filter = data["all", "ParCreTime"] > 0
    return filter


add_particle_filter("new_star",
                    function=new_star,
                    filtered_type="all",
                    requires=["ParCreTime"])
ds.add_particle_filter("new_star")

# get the mass and creation time of the new stars
ad = ds.all_data()
mass = ad["new_star", "ParMass"].in_units("Msun")
creation_time = ad["new_star", "ParCreTime"].in_units("Myr")

# bin the data
t_start = 0.0
t_end = ds.current_time.in_units("Myr")
t_bin = np.linspace(start=t_start, stop=t_end, num=nbin + 1)
upper_idx = np.digitize(creation_time, bins=t_bin, right=True)
time = 0.5 * (t_bin[:-1] + t_bin[1:])
示例#32
0
from yt.utilities.logger import ytLogger as mylog

from yt_p3bh.pop_iii import \
    get_MS_lifetime


def _pop3(pfilter, data):
    return ((data['particle_type'] == 5) & (data['particle_mass'].in_units('Msun') < 1e-10)) \
        | ((data['particle_type'] == 1) & (data['creation_time'] > 0) & \
           (data['particle_mass'].in_units('Msun') > 1)) \
        | ((data['particle_type'] == 5) & (data['particle_mass'].in_units('Msun') > 1e-3))


add_particle_filter(
    "pop_3",
    function=_pop3,
    filtered_type="all",
    requires=["particle_type", "creation_time", "particle_mass"])


def _pop3_black_hole(pfilter, data):
    ct = data["creation_time"]
    stars = (ct > 0)
    if not stars.any():
        return stars

    Zcr = data.ds.parameters['PopIIIMetalCriticalFraction']
    Zfr = data["metallicity_fraction"]
    stars &= (Zfr < Zcr)
    if not stars.any():
        return stars
示例#33
0
    else:
        bv = data.ds.arr(np.zeros(3), "cm/s")
    xv = data["gas", "velocity_x"] - bv[0]
    yv = data["gas", "velocity_y"] - bv[1]
    center = data.get_field_parameter('center')
    x_hat = data["x"] - center[0]
    y_hat = data["y"] - center[1]
    r = np.sqrt(x_hat * x_hat + y_hat * y_hat)
    x_hat /= r
    y_hat /= r

    return (yv * x_hat - xv * y_hat)


add_particle_filter("young_stars",
                    function=young_stars,
                    filtered_type='all',
                    requires=["particle_type"])
yt.add_field("Disk_H",
             function=_Disk_H,
             units="pc",
             take_log=False,
             validators=[ValidateParameter('center')])
yt.add_field("Global_Disk_Radius",
             function=_Global_Disk_Radius,
             units="cm",
             take_log=False,
             validators=[ValidateParameter('center')])
yt.add_field("Disk_Radius",
             function=_Disk_Radius,
             units="cm",
             take_log=False,
import yt
import numpy as np
from yt.data_objects.particle_filters import add_particle_filter
from matplotlib import pyplot as plt

def formed_star(pfilter, data):
    filter = data["all", "creation_time"] > 0
    return filter

add_particle_filter("formed_star", function=formed_star, filtered_type='all',
                    requires=["creation_time"])

filename = "IsolatedGalaxy/galaxy0030/galaxy0030"

ds = yt.load(filename)
ds.add_particle_filter('formed_star')
ad = ds.all_data()
masses = ad['formed_star', 'particle_mass'].in_units('Msun')
formation_time = ad['formed_star', 'creation_time'].in_units('yr')

time_range = [0, 5e8] # years
n_bins = 1000
hist, bins = np.histogram(formation_time, bins=n_bins, range=time_range,)
inds = np.digitize(formation_time, bins=bins)
time = (bins[:-1] + bins[1:])/2

sfr = np.array([masses[inds == j].sum()/(bins[j+1]-bins[j])
                for j in range(len(time))])
sfr[sfr == 0] = np.nan

plt.plot(time/1e6, sfr)