示例#1
0
def test_clump_field_parameters():
    """
    Make sure clump finding on fields with field parameters works.
    """
    def _also_density(field, data):
        factor = data.get_field_parameter("factor")
        return factor * data["density"]

    ds = data_dir_load(i30)
    ds.add_field("also_density",
                 function=_also_density,
                 units=ds.fields.gas.density.units,
                 sampling_type="cell",
                 validators=[ValidateParameter("factor")])
    data_source = ds.disk([0.5, 0.5, 0.5], [0., 0., 1.], (8, 'kpc'),
                          (1, 'kpc'))
    data_source.set_field_parameter("factor", 1)

    step = 2.0
    field = ("gas", "density")
    c_min = 10**np.floor(np.log10(data_source[field]).min())
    c_max = 10**np.floor(np.log10(data_source[field]).max() + 1)

    master_clump_1 = Clump(data_source, ("gas", "density"))
    master_clump_1.add_validator("min_cells", 20)
    master_clump_2 = Clump(data_source, ("gas", "also_density"))
    master_clump_2.add_validator("min_cells", 20)

    find_clumps(master_clump_1, c_min, c_max, step)
    find_clumps(master_clump_2, c_min, c_max, step)
    leaf_clumps_1 = get_lowest_clumps(master_clump_1)
    leaf_clumps_2 = get_lowest_clumps(master_clump_2)

    for c1, c2 in zip(leaf_clumps_1, leaf_clumps_2):
        assert_array_equal(c1["gas", "density"], c2["gas", "density"])
示例#2
0
def test_arbitrary_field_parameters():
    def _test_field(field, data):
        par = data.get_field_parameter('test_parameter')
        return par * data['all', 'particle_mass']

    ds = fake_random_ds(64, nprocs=8, particles=16**2)
    ds.add_field(('all', 'test_field'), units='g',
                 function=_test_field, sampling_type='particle',
                validators=[ValidateParameter('test_parameter')])

    agrid = ds.arbitrary_grid([0.4, 0.4, 0.4], [0.99, 0.99, 0.99],
                              dims=[32, 32, 32])
    agrid.set_field_parameter('test_parameter', 2)
    assert_array_equal(2*agrid['all', 'particle_mass'], agrid['all', 'test_field'])
示例#3
0
def test_arbitrary_field_parameters():
    def _test_field(field, data):
        par = data.get_field_parameter("test_parameter")
        return par * data["all", "particle_mass"]

    ds = fake_random_ds(64, nprocs=8, particles=16 ** 2)
    ds.add_field(
        ("all", "test_field"),
        units="g",
        function=_test_field,
        sampling_type="particle",
        validators=[ValidateParameter("test_parameter")],
    )

    agrid = ds.arbitrary_grid([0.4, 0.4, 0.4], [0.99, 0.99, 0.99], dims=[32, 32, 32])
    agrid.set_field_parameter("test_parameter", 2)
    assert_array_equal(2 * agrid["all", "particle_mass"], agrid["all", "test_field"])
示例#4
0
def setup_magnetic_field_fields(registry, ftype="gas", slice_info=None):
    def _magnetic_energy(field, data):
        """This assumes that your front end has provided Bx, By, Bz in
        units of Gauss. If you use MKS, make sure to write your own
        magnetic_energy field to deal with non-unitary \mu_0.
        """
        return (data[ftype, "magnetic_field_x"]**2 +
                data[ftype, "magnetic_field_y"]**2 +
                data[ftype, "magnetic_field_z"]**2) / (8 * np.pi)

    registry.add_field((ftype, "magnetic_energy"),
                       function=_magnetic_energy,
                       units="erg / cm**3")

    def _plasma_beta(field, data):
        """This assumes that your front end has provided Bx, By, Bz in
        units of Gauss. If you use MKS, make sure to write your own
        PlasmaBeta field to deal with non-unitary \mu_0.
        """
        return data[ftype, 'pressure'] / data[ftype, 'magnetic_energy']

    registry.add_field((ftype, "plasma_beta"), function=_plasma_beta, units="")

    def _magnetic_pressure(field, data):
        return data[ftype, 'magnetic_energy']

    registry.add_field((ftype, "magnetic_pressure"),
                       function=_magnetic_pressure,
                       units="erg / cm**3")

    def _magnetic_field_strength(field, data):
        return np.sqrt(8. * np.pi * data[ftype, "magnetic_energy"])

    registry.add_field((ftype, "magnetic_field_strength"),
                       function=_magnetic_field_strength,
                       units="gauss")

    def _magnetic_field_poloidal(field, data):
        normal = data.get_field_parameter("normal")
        d = data[ftype, 'magnetic_field_x']
        Bfields = data.ds.arr([
            data[ftype, 'magnetic_field_x'], data[ftype, 'magnetic_field_y'],
            data[ftype, 'magnetic_field_z']
        ], d.units)

        theta = data["index", 'spherical_theta']
        phi = data["index", 'spherical_phi']

        return get_sph_theta_component(Bfields, theta, phi, normal)

    registry.add_field((ftype, "magnetic_field_poloidal"),
                       function=_magnetic_field_poloidal,
                       units="gauss",
                       validators=[ValidateParameter("normal")])

    def _magnetic_field_toroidal(field, data):
        normal = data.get_field_parameter("normal")
        d = data[ftype, 'magnetic_field_x']
        Bfields = data.ds.arr([
            data[ftype, 'magnetic_field_x'], data[ftype, 'magnetic_field_y'],
            data[ftype, 'magnetic_field_z']
        ], d.units)

        phi = data["index", 'spherical_phi']
        return get_sph_phi_component(Bfields, phi, normal)

    registry.add_field((ftype, "magnetic_field_toroidal"),
                       function=_magnetic_field_toroidal,
                       units="gauss",
                       validators=[ValidateParameter("normal")])
示例#5
0
def setup_magnetic_field_fields(registry, ftype="gas", slice_info=None):
    ds = registry.ds

    unit_system = ds.unit_system
    pc = registry.ds.units.physical_constants

    axis_names = registry.ds.coordinates.axis_order

    if (ftype, f"magnetic_field_{axis_names[0]}") not in registry:
        return

    u = registry[ftype, f"magnetic_field_{axis_names[0]}"].units

    def mag_factors(dims):
        if dims == dimensions.magnetic_field_cgs:
            return 4.0 * np.pi
        elif dims == dimensions.magnetic_field_mks:
            return ds.units.physical_constants.mu_0

    def _magnetic_field_strength(field, data):
        xm = f"relative_magnetic_field_{axis_names[0]}"
        ym = f"relative_magnetic_field_{axis_names[1]}"
        zm = f"relative_magnetic_field_{axis_names[2]}"

        B2 = (data[ftype, xm])**2 + (data[ftype, ym])**2 + (data[ftype, zm])**2

        return np.sqrt(B2)

    registry.add_field(
        (ftype, "magnetic_field_strength"),
        sampling_type="local",
        function=_magnetic_field_strength,
        validators=[ValidateParameter("bulk_magnetic_field")],
        units=u,
    )

    def _magnetic_energy_density(field, data):
        B = data[ftype, "magnetic_field_strength"]
        return 0.5 * B * B / mag_factors(B.units.dimensions)

    registry.add_field(
        (ftype, "magnetic_energy_density"),
        sampling_type="local",
        function=_magnetic_energy_density,
        units=unit_system["pressure"],
    )

    registry.alias(
        (ftype, "magnetic_energy"),
        (ftype, "magnetic_energy_density"),
        deprecate=("4.0.0", "4.1.0"),
    )

    def _plasma_beta(field, data):
        return data[ftype, "pressure"] / data[ftype, "magnetic_energy_density"]

    registry.add_field((ftype, "plasma_beta"),
                       sampling_type="local",
                       function=_plasma_beta,
                       units="")

    def _magnetic_pressure(field, data):
        return data[ftype, "magnetic_energy_density"]

    registry.add_field(
        (ftype, "magnetic_pressure"),
        sampling_type="local",
        function=_magnetic_pressure,
        units=unit_system["pressure"],
    )

    if registry.ds.geometry == "cartesian":

        def _magnetic_field_poloidal(field, data):
            normal = data.get_field_parameter("normal")

            Bfields = ustack([
                data[ftype, "relative_magnetic_field_x"],
                data[ftype, "relative_magnetic_field_y"],
                data[ftype, "relative_magnetic_field_z"],
            ])

            theta = data["index", "spherical_theta"]
            phi = data["index", "spherical_phi"]

            return get_sph_theta_component(Bfields, theta, phi, normal)

        def _magnetic_field_toroidal(field, data):
            normal = data.get_field_parameter("normal")

            Bfields = ustack([
                data[ftype, "relative_magnetic_field_x"],
                data[ftype, "relative_magnetic_field_y"],
                data[ftype, "relative_magnetic_field_z"],
            ])

            phi = data["index", "spherical_phi"]
            return get_sph_phi_component(Bfields, phi, normal)

    elif registry.ds.geometry == "cylindrical":

        def _magnetic_field_poloidal(field, data):
            bm = data.get_field_parameter("bulk_magnetic_field")
            r = data["index", "r"]
            z = data["index", "z"]
            d = np.sqrt(r * r + z * z)
            rax = axis_names.find("r")
            zax = axis_names.find("z")
            return (data[ftype, "magnetic_field_r"] - bm[rax]) * (r / d) + (
                data[ftype, "magnetic_field_z"] - bm[zax]) * (z / d)

        def _magnetic_field_toroidal(field, data):
            ax = axis_names.find("theta")
            bm = data.get_field_parameter("bulk_magnetic_field")
            return data[ftype, "magnetic_field_theta"] - bm[ax]

    elif registry.ds.geometry == "spherical":

        def _magnetic_field_poloidal(field, data):
            ax = axis_names.find("theta")
            bm = data.get_field_parameter("bulk_magnetic_field")
            return data[ftype, "magnetic_field_theta"] - bm[ax]

        def _magnetic_field_toroidal(field, data):
            ax = axis_names.find("phi")
            bm = data.get_field_parameter("bulk_magnetic_field")
            return data[ftype, "magnetic_field_phi"] - bm[ax]

    else:

        # Unidentified geometry--set to None

        _magnetic_field_toroidal = None
        _magnetic_field_poloidal = None

    registry.add_field(
        (ftype, "magnetic_field_poloidal"),
        sampling_type="local",
        function=_magnetic_field_poloidal,
        units=u,
        validators=[
            ValidateParameter("normal"),
            ValidateParameter("bulk_magnetic_field"),
        ],
    )

    registry.add_field(
        (ftype, "magnetic_field_toroidal"),
        sampling_type="local",
        function=_magnetic_field_toroidal,
        units=u,
        validators=[
            ValidateParameter("normal"),
            ValidateParameter("bulk_magnetic_field"),
        ],
    )

    def _alfven_speed(field, data):
        B = data[ftype, "magnetic_field_strength"]
        return B / np.sqrt(
            mag_factors(B.units.dimensions) * data[ftype, "density"])

    registry.add_field(
        (ftype, "alfven_speed"),
        sampling_type="local",
        function=_alfven_speed,
        units=unit_system["velocity"],
    )

    def _mach_alfven(field, data):
        return data[ftype, "velocity_magnitude"] / data[ftype, "alfven_speed"]

    registry.add_field(
        (ftype, "mach_alfven"),
        sampling_type="local",
        function=_mach_alfven,
        units="dimensionless",
    )

    b_units = registry.ds.quan(1.0, u).units
    if dimensions.current_mks in b_units.dimensions.free_symbols:
        rm_scale = pc.qp.to("C", "SI")**3 / (4.0 * np.pi * pc.eps_0)
    else:
        rm_scale = pc.qp**3 / pc.clight
    rm_scale *= registry.ds.quan(
        1.0, "rad") / (2.0 * np.pi * pc.me**2 * pc.clight**3)
    rm_units = registry.ds.quan(1.0, "rad/m**2").units / unit_system["length"]

    def _rotation_measure(field, data):
        return (rm_scale * data[ftype, "magnetic_field_los"] *
                data[ftype, "El_number_density"])

    registry.add_field(
        (ftype, "rotation_measure"),
        sampling_type="local",
        function=_rotation_measure,
        units=rm_units,
        validators=[ValidateParameter("axis", {"axis": [0, 1, 2]})],
    )
示例#6
0
def setup_fluid_vector_fields(registry, ftype="gas", slice_info=None):
    # Current implementation for gradient is not valid for curvilinear geometries
    if is_curvilinear(registry.ds.geometry): return

    unit_system = registry.ds.unit_system
    # slice_info would be the left, the right, and the factor.
    # For example, with the old Enzo-ZEUS fields, this would be:
    # slice(None, -2, None)
    # slice(1, -1, None)
    # 1.0
    # Otherwise, we default to a centered difference.
    if slice_info is None:
        sl_left = slice(None, -2, None)
        sl_right = slice(2, None, None)
        div_fac = 2.0
    else:
        sl_left, sl_right, div_fac = slice_info
    sl_center = slice(1, -1, None)

    def _baroclinic_vorticity_x(field, data):
        rho2 = data[ftype, "density"].astype(np.float64)**2
        return (data[ftype, "pressure_gradient_y"] *
                data[ftype, "density_gradient_z"] -
                data[ftype, "pressure_gradient_z"] *
                data[ftype, "density_gradient_z"]) / rho2

    def _baroclinic_vorticity_y(field, data):
        rho2 = data[ftype, "density"].astype(np.float64)**2
        return (data[ftype, "pressure_gradient_z"] *
                data[ftype, "density_gradient_x"] -
                data[ftype, "pressure_gradient_x"] *
                data[ftype, "density_gradient_z"]) / rho2

    def _baroclinic_vorticity_z(field, data):
        rho2 = data[ftype, "density"].astype(np.float64)**2
        return (data[ftype, "pressure_gradient_x"] *
                data[ftype, "density_gradient_y"] -
                data[ftype, "pressure_gradient_y"] *
                data[ftype, "density_gradient_x"]) / rho2

    bv_validators = [
        ValidateSpatial(1, [(ftype, "density"), (ftype, "pressure")])
    ]
    for ax in 'xyz':
        n = "baroclinic_vorticity_%s" % ax
        registry.add_field((ftype, n),
                           sampling_type="cell",
                           function=eval("_%s" % n),
                           validators=bv_validators,
                           units=unit_system["frequency"]**2)

    create_magnitude_field(registry,
                           "baroclinic_vorticity",
                           unit_system["frequency"]**2,
                           ftype=ftype,
                           slice_info=slice_info,
                           validators=bv_validators)

    def _vorticity_x(field, data):
        vz = data[ftype, "relative_velocity_z"]
        vy = data[ftype, "relative_velocity_y"]
        f = ((vz[sl_center, sl_right, sl_center] -
              vz[sl_center, sl_left, sl_center]) /
             (div_fac * just_one(data["index", "dy"])))
        f -= ((vy[sl_center, sl_center, sl_right] -
               vy[sl_center, sl_center, sl_left]) /
              (div_fac * just_one(data["index", "dz"])))
        new_field = data.ds.arr(np.zeros_like(vz, dtype=np.float64), f.units)
        new_field[sl_center, sl_center, sl_center] = f
        return new_field

    def _vorticity_y(field, data):
        vx = data[ftype, "relative_velocity_x"]
        vz = data[ftype, "relative_velocity_z"]
        f = ((vx[sl_center, sl_center, sl_right] -
              vx[sl_center, sl_center, sl_left]) /
             (div_fac * just_one(data["index", "dz"])))
        f -= ((vz[sl_right, sl_center, sl_center] -
               vz[sl_left, sl_center, sl_center]) /
              (div_fac * just_one(data["index", "dx"])))
        new_field = data.ds.arr(np.zeros_like(vz, dtype=np.float64), f.units)
        new_field[sl_center, sl_center, sl_center] = f
        return new_field

    def _vorticity_z(field, data):
        vx = data[ftype, "relative_velocity_x"]
        vy = data[ftype, "relative_velocity_y"]
        f = ((vy[sl_right, sl_center, sl_center] -
              vx[sl_left, sl_center, sl_center]) /
             (div_fac * just_one(data["index", "dx"])))
        f -= ((vx[sl_center, sl_right, sl_center] -
               vx[sl_center, sl_left, sl_center]) /
              (div_fac * just_one(data["index", "dy"])))
        new_field = data.ds.arr(np.zeros_like(vy, dtype=np.float64), f.units)
        new_field[sl_center, sl_center, sl_center] = f
        return new_field

    vort_validators = [
        ValidateSpatial(1, [(ftype, "velocity_%s" % d) for d in 'xyz']),
        ValidateParameter('bulk_velocity')
    ]

    for ax in 'xyz':
        n = "vorticity_%s" % ax
        registry.add_field((ftype, n),
                           sampling_type="cell",
                           function=eval("_%s" % n),
                           units=unit_system["frequency"],
                           validators=vort_validators)
    create_magnitude_field(registry,
                           "vorticity",
                           unit_system["frequency"],
                           ftype=ftype,
                           slice_info=slice_info,
                           validators=vort_validators)
    create_squared_field(registry,
                         "vorticity",
                         unit_system["frequency"]**2,
                         ftype=ftype,
                         slice_info=slice_info,
                         validators=vort_validators)

    def _vorticity_stretching_x(field, data):
        return data[ftype, "velocity_divergence"] * data[ftype, "vorticity_x"]

    def _vorticity_stretching_y(field, data):
        return data[ftype, "velocity_divergence"] * data[ftype, "vorticity_y"]

    def _vorticity_stretching_z(field, data):
        return data[ftype, "velocity_divergence"] * data[ftype, "vorticity_z"]

    for ax in 'xyz':
        n = "vorticity_stretching_%s" % ax
        registry.add_field((ftype, n),
                           sampling_type="cell",
                           function=eval("_%s" % n),
                           units=unit_system["frequency"]**2,
                           validators=vort_validators)

    create_magnitude_field(registry,
                           "vorticity_stretching",
                           unit_system["frequency"]**2,
                           ftype=ftype,
                           slice_info=slice_info,
                           validators=vort_validators)

    def _vorticity_growth_x(field, data):
        return -data[ftype, "vorticity_stretching_x"] - \
          data[ftype, "baroclinic_vorticity_x"]

    def _vorticity_growth_y(field, data):
        return -data[ftype, "vorticity_stretching_y"] - \
          data[ftype, "baroclinic_vorticity_y"]

    def _vorticity_growth_z(field, data):
        return -data[ftype, "vorticity_stretching_z"] - \
          data[ftype, "baroclinic_vorticity_z"]

    for ax in 'xyz':
        n = "vorticity_growth_%s" % ax
        registry.add_field((ftype, n),
                           sampling_type="cell",
                           function=eval("_%s" % n),
                           units=unit_system["frequency"]**2,
                           validators=vort_validators)

    def _vorticity_growth_magnitude(field, data):
        result = np.sqrt(data[ftype, "vorticity_growth_x"]**2 +
                         data[ftype, "vorticity_growth_y"]**2 +
                         data[ftype, "vorticity_growth_z"]**2)
        dot = data.ds.arr(np.zeros(result.shape), "")
        for ax in "xyz":
            dot += (data[ftype, "vorticity_%s" % ax] *
                    data[ftype, "vorticity_growth_%s" % ax]).to_ndarray()
        result = np.sign(dot) * result
        return result

    registry.add_field((ftype, "vorticity_growth_magnitude"),
                       sampling_type="cell",
                       function=_vorticity_growth_magnitude,
                       units=unit_system["frequency"]**2,
                       validators=vort_validators,
                       take_log=False)

    def _vorticity_growth_magnitude_absolute(field, data):
        return np.sqrt(data[ftype, "vorticity_growth_x"]**2 +
                       data[ftype, "vorticity_growth_y"]**2 +
                       data[ftype, "vorticity_growth_z"]**2)

    registry.add_field((ftype, "vorticity_growth_magnitude_absolute"),
                       sampling_type="cell",
                       function=_vorticity_growth_magnitude_absolute,
                       units=unit_system["frequency"]**2,
                       validators=vort_validators)

    def _vorticity_growth_timescale(field, data):
        domegax_dt = data[ftype, "vorticity_x"] / data[ftype,
                                                       "vorticity_growth_x"]
        domegay_dt = data[ftype, "vorticity_y"] / data[ftype,
                                                       "vorticity_growth_y"]
        domegaz_dt = data[ftype, "vorticity_z"] / data[ftype,
                                                       "vorticity_growth_z"]
        return np.sqrt(domegax_dt**2 + domegay_dt**2 + domegaz_dt**2)

    registry.add_field((ftype, "vorticity_growth_timescale"),
                       sampling_type="cell",
                       function=_vorticity_growth_timescale,
                       units=unit_system["time"],
                       validators=vort_validators)

    ########################################################################
    # With radiation pressure
    ########################################################################

    def _vorticity_radiation_pressure_x(field, data):
        rho = data[ftype, "density"].astype(np.float64)
        return (data[ftype, "radiation_acceleration_y"] *
                data[ftype, "density_gradient_z"] -
                data[ftype, "radiation_acceleration_z"] *
                data[ftype, "density_gradient_y"]) / rho

    def _vorticity_radiation_pressure_y(field, data):
        rho = data[ftype, "density"].astype(np.float64)
        return (data[ftype, "radiation_acceleration_z"] *
                data[ftype, "density_gradient_x"] -
                data[ftype, "radiation_acceleration_x"] *
                data[ftype, "density_gradient_z"]) / rho

    def _vorticity_radiation_pressure_z(field, data):
        rho = data[ftype, "density"].astype(np.float64)
        return (data[ftype, "radiation_acceleration_x"] *
                data[ftype, "density_gradient_y"] -
                data[ftype, "radiation_acceleration_y"] *
                data[ftype, "density_gradient_x"]) / rho

    vrp_validators = [
        ValidateSpatial(1, [(ftype, "density"),
                            (ftype, "radiation_acceleration_x"),
                            (ftype, "radiation_acceleration_y"),
                            (ftype, "radiation_acceleration_z")])
    ]
    for ax in 'xyz':
        n = "vorticity_radiation_pressure_%s" % ax
        registry.add_field((ftype, n),
                           sampling_type="cell",
                           function=eval("_%s" % n),
                           units=unit_system["frequency"]**2,
                           validators=vrp_validators)

    create_magnitude_field(registry,
                           "vorticity_radiation_pressure",
                           unit_system["frequency"]**2,
                           ftype=ftype,
                           slice_info=slice_info,
                           validators=vrp_validators)

    def _vorticity_radiation_pressure_growth_x(field, data):
        return -data[ftype, "vorticity_stretching_x"] - \
          data[ftype, "baroclinic_vorticity_x"] \
          -data[ftype, "vorticity_radiation_pressure_x"]

    def _vorticity_radiation_pressure_growth_y(field, data):
        return -data[ftype, "vorticity_stretching_y"] - \
          data[ftype, "baroclinic_vorticity_y"] \
          -data[ftype, "vorticity_radiation_pressure_y"]

    def _vorticity_radiation_pressure_growth_z(field, data):
        return -data[ftype, "vorticity_stretching_z"] - \
          data[ftype, "baroclinic_vorticity_z"] \
          -data[ftype, "vorticity_radiation_pressure_z"]

    for ax in 'xyz':
        n = "vorticity_radiation_pressure_growth_%s" % ax
        registry.add_field((ftype, n),
                           sampling_type="cell",
                           function=eval("_%s" % n),
                           units=unit_system["frequency"]**2,
                           validators=vrp_validators)

    def _vorticity_radiation_pressure_growth_magnitude(field, data):
        result = np.sqrt(
            data[ftype, "vorticity_radiation_pressure_growth_x"]**2 +
            data[ftype, "vorticity_radiation_pressure_growth_y"]**2 +
            data[ftype, "vorticity_radiation_pressure_growth_z"]**2)
        dot = data.ds.arr(np.zeros(result.shape), "")
        for ax in "xyz":
            dot += (data[ftype, "vorticity_%s" % ax] *
                    data[ftype, "vorticity_growth_%s" % ax]).to_ndarray()
        result = np.sign(dot) * result
        return result

    registry.add_field(
        (ftype, "vorticity_radiation_pressure_growth_magnitude"),
        sampling_type="cell",
        function=_vorticity_radiation_pressure_growth_magnitude,
        units=unit_system["frequency"]**2,
        validators=vrp_validators,
        take_log=False)

    def _vorticity_radiation_pressure_growth_magnitude_absolute(field, data):
        return np.sqrt(
            data[ftype, "vorticity_radiation_pressure_growth_x"]**2 +
            data[ftype, "vorticity_radiation_pressure_growth_y"]**2 +
            data[ftype, "vorticity_radiation_pressure_growth_z"]**2)

    registry.add_field(
        (ftype, "vorticity_radiation_pressure_growth_magnitude_absolute"),
        sampling_type="cell",
        function=_vorticity_radiation_pressure_growth_magnitude_absolute,
        units="s**(-2)",
        validators=vrp_validators)

    def _vorticity_radiation_pressure_growth_timescale(field, data):
        domegax_dt = data[ftype, "vorticity_x"] / \
          data[ftype, "vorticity_radiation_pressure_growth_x"]
        domegay_dt = data[ftype, "vorticity_y"] / \
          data[ftype, "vorticity_radiation_pressure_growth_y"]
        domegaz_dt = data[ftype, "vorticity_z"] / \
          data[ftype, "vorticity_radiation_pressure_growth_z"]
        return np.sqrt(domegax_dt**2 + domegay_dt**2 + domegaz_dt**2)

    registry.add_field(
        (ftype, "vorticity_radiation_pressure_growth_timescale"),
        sampling_type="cell",
        function=_vorticity_radiation_pressure_growth_timescale,
        units=unit_system["time"],
        validators=vrp_validators)

    def _shear(field, data):
        """
        Shear is defined as [(dvx/dy + dvy/dx)^2 + (dvz/dy + dvy/dz)^2 +
                             (dvx/dz + dvz/dx)^2 ]^(0.5)
        where dvx/dy = [vx(j-1) - vx(j+1)]/[2dy]
        and is in units of s^(-1)
        (it's just like vorticity except add the derivative pairs instead
         of subtracting them)
        """
        if data.ds.dimensionality > 1:
            vx = data[ftype, "relative_velocity_x"]
            vy = data[ftype, "relative_velocity_y"]
            dvydx = ((vy[sl_right, sl_center, sl_center] -
                      vy[sl_left, sl_center, sl_center]) /
                     (div_fac * just_one(data["index", "dx"])))
            dvxdy = ((vx[sl_center, sl_right, sl_center] -
                      vx[sl_center, sl_left, sl_center]) /
                     (div_fac * just_one(data["index", "dy"])))
            f = (dvydx + dvxdy)**2.0
            del dvydx, dvxdy
        if data.ds.dimensionality > 2:
            vz = data[ftype, "relative_velocity_z"]
            dvzdy = ((vz[sl_center, sl_right, sl_center] -
                      vz[sl_center, sl_left, sl_center]) /
                     (div_fac * just_one(data["index", "dy"])))
            dvydz = ((vy[sl_center, sl_center, sl_right] -
                      vy[sl_center, sl_center, sl_left]) /
                     (div_fac * just_one(data["index", "dz"])))
            f += (dvzdy + dvydz)**2.0
            del dvzdy, dvydz
            dvxdz = ((vx[sl_center, sl_center, sl_right] -
                      vx[sl_center, sl_center, sl_left]) /
                     (div_fac * just_one(data["index", "dz"])))
            dvzdx = ((vz[sl_right, sl_center, sl_center] -
                      vz[sl_left, sl_center, sl_center]) /
                     (div_fac * just_one(data["index", "dx"])))
            f += (dvxdz + dvzdx)**2.0
            del dvxdz, dvzdx
        np.sqrt(f, out=f)
        new_field = data.ds.arr(np.zeros_like(data[ftype, "velocity_x"]),
                                f.units)
        new_field[sl_center, sl_center, sl_center] = f
        return new_field

    registry.add_field((ftype, "shear"),
                       sampling_type="cell",
                       function=_shear,
                       validators=[
                           ValidateSpatial(1, [(ftype, "velocity_x"),
                                               (ftype, "velocity_y"),
                                               (ftype, "velocity_z")]),
                           ValidateParameter('bulk_velocity')
                       ],
                       units=unit_system["frequency"])

    def _shear_criterion(field, data):
        """
        Divide by c_s to leave shear in units of length**-1, which 
        can be compared against the inverse of the local cell size (1/dx) 
        to determine if refinement should occur.
        """
        return data[ftype, "shear"] / data[ftype, "sound_speed"]

    registry.add_field((ftype, "shear_criterion"),
                       sampling_type="cell",
                       function=_shear_criterion,
                       units=unit_system["length"]**-1,
                       validators=[
                           ValidateSpatial(1, [(ftype, "sound_speed"),
                                               (ftype, "velocity_x"),
                                               (ftype, "velocity_y"),
                                               (ftype, "velocity_z")])
                       ])

    def _shear_mach(field, data):
        """
        Dimensionless shear (shear_mach) is defined nearly the same as shear, 
        except that it is scaled by the local dx/dy/dz and the local sound speed.
        So it results in a unitless quantity that is effectively measuring 
        shear in mach number.  

        In order to avoid discontinuities created by multiplying by dx/dy/dz at
        grid refinement boundaries, we also multiply by 2**GridLevel.

        Shear (Mach) = [(dvx + dvy)^2 + (dvz + dvy)^2 +
                        (dvx + dvz)^2  ]^(0.5) / c_sound
        """
        if data.ds.dimensionality > 1:
            vx = data[ftype, "relative_velocity_x"]
            vy = data[ftype, "relative_velocity_y"]
            dvydx = (vy[sl_right, sl_center, sl_center] -
                     vy[sl_left, sl_center, sl_center]) / div_fac
            dvxdy = (vx[sl_center, sl_right, sl_center] -
                     vx[sl_center, sl_left, sl_center]) / div_fac
            f = (dvydx + dvxdy)**2.0
            del dvydx, dvxdy
        if data.ds.dimensionality > 2:
            vz = data[ftype, "relative_velocity_z"]
            dvzdy = (vz[sl_center, sl_right, sl_center] -
                     vz[sl_center, sl_left, sl_center]) / div_fac
            dvydz = (vy[sl_center, sl_center, sl_right] -
                     vy[sl_center, sl_center, sl_left]) / div_fac
            f += (dvzdy + dvydz)**2.0
            del dvzdy, dvydz
            dvxdz = (vx[sl_center, sl_center, sl_right] -
                     vx[sl_center, sl_center, sl_left]) / div_fac
            dvzdx = (vz[sl_right, sl_center, sl_center] -
                     vz[sl_left, sl_center, sl_center]) / div_fac
            f += (dvxdz + dvzdx)**2.0
            del dvxdz, dvzdx
        f *= (
            2.0**data["index", "grid_level"][sl_center, sl_center, sl_center] /
            data[ftype, "sound_speed"][sl_center, sl_center, sl_center])**2.0
        np.sqrt(f, out=f)
        new_field = data.ds.arr(np.zeros_like(vx), f.units)
        new_field[sl_center, sl_center, sl_center] = f
        return new_field

    vs_fields = [(ftype, "sound_speed"), (ftype, "velocity_x"),
                 (ftype, "velocity_y"), (ftype, "velocity_z")]
    registry.add_field((ftype, "shear_mach"),
                       sampling_type="cell",
                       function=_shear_mach,
                       units="",
                       validators=[
                           ValidateSpatial(1, vs_fields),
                           ValidateParameter('bulk_velocity')
                       ])
    ValidateGridType, \
    ValidateParameter, \
    ValidateSpatial, \
    NeedsParameter

from astropy.table import Table , Column

def _Disk_H(field, data):
    center = data.get_field_parameter('center')
    z = data["z"] - center[2]
    return np.abs(z)
yt.add_field("Disk_H",
             function=_Disk_H,
             units="pc",
             take_log=False,
             validators=[ValidateParameter('center')])

def _radial_velocity(field,data):
        if data.has_field_parameter("bulk_velocity"):
                bv = data.get_field_parameter("bulk_velocity").in_units("cm/s")
        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 xv*x_hat+yv*y_hat
示例#8
0
def setup_magnetic_field_fields(registry, ftype="gas", slice_info=None):
    unit_system = registry.ds.unit_system

    axis_names = registry.ds.coordinates.axis_order

    if (ftype, "magnetic_field_%s" % axis_names[0]) not in registry:
        return

    u = registry[ftype, "magnetic_field_%s" % axis_names[0]].units

    def _magnetic_field_strength(field, data):
        B2 = (data[ftype, "magnetic_field_%s" % axis_names[0]]**2 +
              data[ftype, "magnetic_field_%s" % axis_names[1]]**2 +
              data[ftype, "magnetic_field_%s" % axis_names[2]]**2)
        return np.sqrt(B2)

    registry.add_field((ftype, "magnetic_field_strength"),
                       sampling_type="cell",
                       function=_magnetic_field_strength,
                       units=u)

    def _magnetic_energy(field, data):
        B = data[ftype, "magnetic_field_strength"]
        return 0.5 * B * B / mag_factors[B.units.dimensions]

    registry.add_field((ftype, "magnetic_energy"),
                       sampling_type="cell",
                       function=_magnetic_energy,
                       units=unit_system["pressure"])

    def _plasma_beta(field, data):
        return data[ftype, 'pressure'] / data[ftype, 'magnetic_energy']

    registry.add_field((ftype, "plasma_beta"),
                       sampling_type="cell",
                       function=_plasma_beta,
                       units="")

    def _magnetic_pressure(field, data):
        return data[ftype, 'magnetic_energy']

    registry.add_field((ftype, "magnetic_pressure"),
                       sampling_type="cell",
                       function=_magnetic_pressure,
                       units=unit_system["pressure"])

    if registry.ds.geometry == "cartesian":

        def _magnetic_field_poloidal(field, data):
            normal = data.get_field_parameter("normal")
            d = data[ftype, 'magnetic_field_x']
            Bfields = data.ds.arr([
                data[ftype, 'magnetic_field_x'],
                data[ftype, 'magnetic_field_y'], data[ftype,
                                                      'magnetic_field_z']
            ], d.units)

            theta = data["index", 'spherical_theta']
            phi = data["index", 'spherical_phi']

            return get_sph_theta_component(Bfields, theta, phi, normal)

        def _magnetic_field_toroidal(field, data):
            normal = data.get_field_parameter("normal")
            d = data[ftype, 'magnetic_field_x']
            Bfields = data.ds.arr([
                data[ftype, 'magnetic_field_x'],
                data[ftype, 'magnetic_field_y'], data[ftype,
                                                      'magnetic_field_z']
            ], d.units)

            phi = data["index", 'spherical_phi']
            return get_sph_phi_component(Bfields, phi, normal)

    elif registry.ds.geometry == "cylindrical":

        def _magnetic_field_poloidal(field, data):
            r = data["index", "r"]
            z = data["index", "z"]
            d = np.sqrt(r * r + z * z)
            return (data[ftype, "magnetic_field_r"] * (r / d) +
                    data[ftype, "magnetic_field_z"] * (z / d))

        def _magnetic_field_toroidal(field, data):
            return data[ftype, "magnetic_field_theta"]

    elif registry.ds.geometry == "spherical":

        def _magnetic_field_poloidal(field, data):
            return data[ftype, "magnetic_field_theta"]

        def _magnetic_field_toroidal(field, data):
            return data[ftype, "magnetic_field_phi"]

    else:

        # Unidentified geometry--set to None

        _magnetic_field_toroidal = None
        _magnetic_field_poloidal = None

    registry.add_field((ftype, "magnetic_field_poloidal"),
                       sampling_type="cell",
                       function=_magnetic_field_poloidal,
                       units=u,
                       validators=[ValidateParameter("normal")])

    registry.add_field((ftype, "magnetic_field_toroidal"),
                       sampling_type="cell",
                       function=_magnetic_field_toroidal,
                       units=u,
                       validators=[ValidateParameter("normal")])

    def _alfven_speed(field, data):
        B = data[ftype, 'magnetic_field_strength']
        return B / np.sqrt(
            mag_factors[B.units.dimensions] * data[ftype, 'density'])

    registry.add_field((ftype, "alfven_speed"),
                       sampling_type="cell",
                       function=_alfven_speed,
                       units=unit_system["velocity"])

    def _mach_alfven(field, data):
        return data[ftype, 'velocity_magnitude'] / data[ftype, 'alfven_speed']

    registry.add_field((ftype, "mach_alfven"),
                       sampling_type="cell",
                       function=_mach_alfven,
                       units="dimensionless")
示例#9
0
def standard_particle_fields(registry, ptype,
                             spos = "particle_position_%s",
                             svel = "particle_velocity_%s"):
    # This function will set things up based on the scalar fields and standard
    # yt field names.

    def _particle_velocity_magnitude(field, data):
        """ M{|v|} """
        bulk_velocity = data.get_field_parameter("bulk_velocity")
        if bulk_velocity is None:
            bulk_velocity = np.zeros(3)
        return np.sqrt((data[ptype, svel % 'x'] - bulk_velocity[0])**2
                     + (data[ptype, svel % 'y'] - bulk_velocity[1])**2
                     + (data[ptype, svel % 'z'] - bulk_velocity[2])**2 )
    
    registry.add_field((ptype, "particle_velocity_magnitude"),
                  function=_particle_velocity_magnitude,
                  particle_type=True,
                  take_log=False,
                  units="cm/s")

    def _particle_specific_angular_momentum(field, data):
        """
        Calculate the angular of a particle velocity.  Returns a vector for each
        particle.
        """
        if data.has_field_parameter("bulk_velocity"):
            bv = data.get_field_parameter("bulk_velocity")
        else: bv = np.zeros(3, dtype=np.float64)
        xv = data[ptype, svel % 'x'] - bv[0]
        yv = data[ptype, svel % 'y'] - bv[1]
        zv = data[ptype, svel % 'z'] - bv[2]
        center = data.get_field_parameter('center')
        coords = YTArray([data[ptype, spos % 'x'],
                           data[ptype, spos % 'y'],
                           data[ptype, spos % 'z']], dtype=np.float64)
        new_shape = tuple([3] + [1]*(len(coords.shape)-1))
        r_vec = coords - np.reshape(center,new_shape)
        v_vec = YTArray([xv,yv,zv], dtype=np.float64)
        return np.cross(r_vec, v_vec, axis=0)

    registry.add_field((ptype, "particle_specific_angular_momentum"),
              function=_particle_specific_angular_momentum,
              particle_type=True,
              units="cm**2/s",
              validators=[ValidateParameter("center")])

    def _particle_specific_angular_momentum_x(field, data):
        if data.has_field_parameter("bulk_velocity"):
            bv = data.get_field_parameter("bulk_velocity")
        else: bv = np.zeros(3, dtype=np.float64)
        center = data.get_field_parameter('center')
        y = data[ptype, spos % "y"] - center[1]
        z = data[ptype, spos % "z"] - center[2]
        yv = data[ptype, svel % "y"] - bv[1]
        zv = data[ptype, svel % "z"] - bv[2]
        return yv*z - zv*y

    registry.add_field((ptype, "particle_specific_angular_momentum_x"),
              function=_particle_specific_angular_momentum_x,
              particle_type=True,
              units="cm**2/s",
              validators=[ValidateParameter("center")])

    def _particle_specific_angular_momentum_y(field, data):
        if data.has_field_parameter("bulk_velocity"):
            bv = data.get_field_parameter("bulk_velocity")
        else: bv = np.zeros(3, dtype=np.float64)
        center = data.get_field_parameter('center')
        x = data[ptype, spos % "x"] - center[0]
        z = data[ptype, spos % "z"] - center[2]
        xv = data[ptype, svel % "x"] - bv[0]
        zv = data[ptype, svel % "z"] - bv[2]
        return -(xv*z - zv*x)

    registry.add_field((ptype, "particle_specific_angular_momentum_y"),
              function=_particle_specific_angular_momentum_y,
              particle_type=True,
              units="cm**2/s",
              validators=[ValidateParameter("center")])

    def _particle_specific_angular_momentum_z(field, data):
        if data.has_field_parameter("bulk_velocity"):
            bv = data.get_field_parameter("bulk_velocity")
        else: bv = np.zeros(3, dtype=np.float64)
        center = data.get_field_parameter('center')
        x = data[ptype, spos % "x"] - center[0]
        y = data[ptype, spos % "y"] - center[1]
        xv = data[ptype, svel % "x"] - bv[0]
        yv = data[ptype, svel % "y"] - bv[1]
        return xv*y - yv*x

    registry.add_field((ptype, "particle_specific_angular_momentum_z"),
              function=_particle_specific_angular_momentum_z,
              particle_type=True,
              units="cm**2/s",
              validators=[ValidateParameter("center")])

    create_magnitude_field(registry, "particle_specific_angular_momentum",
                           "cm**2/s", ftype=ptype, particle_type=True)
    
    def _particle_angular_momentum_x(field, data):
        return data[ptype, "particle_mass"] * \
               data[ptype, "particle_specific_angular_momentum_x"]
    registry.add_field((ptype, "particle_angular_momentum_x"),
             function=_particle_angular_momentum_x,
             units="g*cm**2/s", particle_type=True,
             validators=[ValidateParameter('center')])

    def _particle_angular_momentum_y(field, data):
        return data[ptype, "particle_mass"] * \
               data[ptype, "particle_specific_angular_momentum_y"]
    registry.add_field((ptype, "particle_angular_momentum_y"),
             function=_particle_angular_momentum_y,
             units="g*cm**2/s", particle_type=True,
             validators=[ValidateParameter('center')])

    def _particle_angular_momentum_z(field, data):
        return data[ptype, "particle_mass"] * \
               data[ptype, "particle_specific_angular_momentum_z"]
    registry.add_field((ptype, "particle_angular_momentum_z"),
             function=_particle_angular_momentum_z,
             units="g*cm**2/s", particle_type=True,
             validators=[ValidateParameter('center')])

    def _particle_angular_momentum(field, data):
        return data[ptype, "particle_mass"] \
            * data[ptype, "particle_specific_angular_momentum"]
    registry.add_field((ptype, "particle_angular_momentum"),
              function=_particle_angular_momentum,
              particle_type=True,
              units="g*cm**2/s",
              validators=[ValidateParameter("center")])

    create_magnitude_field(registry, "particle_angular_momentum",
                           "g*cm**2/s", ftype=ptype, particle_type=True)
    
    from .field_functions import \
        get_radius

    def _particle_radius(field, data):
        return get_radius(data, "particle_position_")
    registry.add_field((ptype, "particle_radius"),
              function=_particle_radius,
              validators=[ValidateParameter("center")],
              units="cm", particle_type = True,
              display_name = "Particle Radius")

    def _particle_spherical_position_radius(field, data):
        """
        Radial component of the particles' position vectors in spherical coords
        on the provided field parameters for 'normal', 'center', and 
        'bulk_velocity', 
        """
        normal = data.get_field_parameter('normal')
        center = data.get_field_parameter('center')
        bv = data.get_field_parameter("bulk_velocity")
        pos = spos
        pos = YTArray([data[ptype, pos % ax] for ax in "xyz"])
        theta = get_sph_theta(pos, center)
        phi = get_sph_phi(pos, center)
        pos = pos - np.reshape(center, (3, 1))
        sphr = get_sph_r_component(pos, theta, phi, normal)
        return sphr

    registry.add_field((ptype, "particle_spherical_position_radius"),
              function=_particle_spherical_position_radius,
              particle_type=True, units="cm",
              validators=[ValidateParameter("normal"), 
                          ValidateParameter("center")])

    def _particle_spherical_position_theta(field, data):
        """
        Theta component of the particles' position vectors in spherical coords
        on the provided field parameters for 'normal', 'center', and 
        'bulk_velocity', 
        """
        normal = data.get_field_parameter('normal')
        center = data.get_field_parameter('center')
        bv = data.get_field_parameter("bulk_velocity")
        pos = spos
        pos = YTArray([data[ptype, pos % ax] for ax in "xyz"])
        theta = get_sph_theta(pos, center)
        phi = get_sph_phi(pos, center)
        pos = pos - np.reshape(center, (3, 1))
        spht = get_sph_theta_component(pos, theta, phi, normal)
        return spht

    registry.add_field((ptype, "particle_spherical_position_theta"),
              function=_particle_spherical_position_theta,
              particle_type=True, units="cm",
              validators=[ValidateParameter("normal"), 
                          ValidateParameter("center")])

    def _particle_spherical_position_phi(field, data):
        """
        Phi component of the particles' position vectors in spherical coords
        on the provided field parameters for 'normal', 'center', and 
        'bulk_velocity', 
        """
        normal = data.get_field_parameter('normal')
        center = data.get_field_parameter('center')
        bv = data.get_field_parameter("bulk_velocity")
        pos = spos
        pos = YTArray([data[ptype, pos % ax] for ax in "xyz"])
        theta = get_sph_theta(pos, center)
        phi = get_sph_phi(pos, center)
        pos = pos - np.reshape(center, (3, 1))
        sphp = get_sph_phi_component(pos, phi, normal)
        return sphp

    registry.add_field((ptype, "particle_spherical_position_phi"),
              function=_particle_spherical_position_phi,
              particle_type=True, units="cm",
              validators=[ValidateParameter("normal"), 
                          ValidateParameter("center")])

    def _particle_spherical_velocity_radius(field, data):
        """
        Radial component of the particles' velocity vectors in spherical coords
        based on the provided field parameters for 'normal', 'center', and 
        'bulk_velocity', 
        """
        normal = data.get_field_parameter('normal')
        center = data.get_field_parameter('center')
        bv = data.get_field_parameter("bulk_velocity")
        pos = spos
        pos = YTArray([data[ptype, pos % ax] for ax in "xyz"])
        vel = svel
        vel = YTArray([data[ptype, vel % ax] for ax in "xyz"])
        theta = get_sph_theta(pos, center)
        phi = get_sph_phi(pos, center)
        pos = pos - np.reshape(center, (3, 1))
        vel = vel - np.reshape(bv, (3, 1))
        sphr = get_sph_r_component(vel, theta, phi, normal)
        return sphr

    registry.add_field((ptype, "particle_spherical_velocity_radius"),
              function=_particle_spherical_velocity_radius,
              particle_type=True, units="cm/s",
              validators=[ValidateParameter("normal"), 
                          ValidateParameter("center")])

    # This is simply aliased to "particle_spherical_velocity_radius"
    # for ease of use.
    registry.add_field((ptype, "particle_radial_velocity"),
              function=_particle_spherical_velocity_radius,
              particle_type=True, units="cm/s",
              validators=[ValidateParameter("normal"), 
                          ValidateParameter("center")])

    def _particle_spherical_velocity_theta(field, data):
        """
        Theta component of the particles' velocity vectors in spherical coords
        based on the provided field parameters for 'normal', 'center', and 
        'bulk_velocity', 
        """
        normal = data.get_field_parameter('normal')
        center = data.get_field_parameter('center')
        bv = data.get_field_parameter("bulk_velocity")
        pos = spos
        pos = YTArray([data[ptype, pos % ax] for ax in "xyz"])
        vel = svel
        vel = YTArray([data[ptype, vel % ax] for ax in "xyz"])
        theta = get_sph_theta(pos, center)
        phi = get_sph_phi(pos, center)
        pos = pos - np.reshape(center, (3, 1))
        vel = vel - np.reshape(bv, (3, 1))
        spht = get_sph_theta_component(vel, theta, phi, normal)
        return spht

    registry.add_field((ptype, "particle_spherical_velocity_theta"),
              function=_particle_spherical_velocity_theta,
              particle_type=True, units="cm/s",
              validators=[ValidateParameter("normal"), 
                          ValidateParameter("center")])

    def _particle_spherical_velocity_phi(field, data):
        """
        Phi component of the particles' velocity vectors in spherical coords
        based on the provided field parameters for 'normal', 'center', and 
        'bulk_velocity', 
        """
        normal = data.get_field_parameter('normal')
        center = data.get_field_parameter('center')
        bv = data.get_field_parameter("bulk_velocity")
        pos = YTArray([data[ptype, spos % ax] for ax in "xyz"])
        vel = YTArray([data[ptype, svel % ax] for ax in "xyz"])
        theta = get_sph_theta(pos, center)
        phi = get_sph_phi(pos, center)
        pos = pos - np.reshape(center, (3, 1))
        vel = vel - np.reshape(bv, (3, 1))
        sphp = get_sph_phi_component(vel, phi, normal)
        return sphp

    registry.add_field((ptype, "particle_spherical_velocity_phi"),
              function=_particle_spherical_velocity_phi,
              particle_type=True, units="cm/s",
              validators=[ValidateParameter("normal"), 
                          ValidateParameter("center")])
示例#10
0
    tr = data.ds.gamma * data["gas", "pressure"] / data["gas", "density"]
    return tr

def _sound_speed_rep(field, data):
    tr = data.ds.gamma * data["gas", "pressure"] / data["gas", "density"]
    return 1.0/np.sqrt(tr)

def _sound_speed_rep_2(field, data):
    tr = data.ds.gamma * data["gas", "pressure"] / data["gas", "density"]
    return 1.0/tr

yt.add_field("Disk_H",
             function=_Disk_H,
             units="pc",
             take_log=False,
             validators=[ValidateParameter('center')])
yt.add_field(("gas", "vz_squared"),function=_vz_squared,units="km**2/s**2")
yt.add_field(("gas", "vz"),function=_vz,units="km/s")
yt.add_field("sound_speed", function=_sound_speed, units=r"km/s")
yt.add_field("sound_speed_rep", function=_sound_speed_rep, units=r"s/km")
yt.add_field("sound_speed_2", function=_sound_speed_2, units=r"km**2/s**2")
yt.add_field("sound_speed_rep_2", function=_sound_speed_rep_2, units=r"s**2/km**2")
yt.add_field(("gas", "px"),function=_px,units="g/s/cm**2")
yt.add_field(("gas", "py"),function=_py,units="g/s/cm**2")
yt.add_field(("gas", "pz"),function=_pz,units="g/s/cm**2")
yt.add_field(("gas", "sturb"),function=_sturb,units="km/s",validators=vort_validators)
yt.add_field(("gas", "vturb"),function=_vturb,units="km/s",validators=vort_validators)
yt.add_field(("gas", "wturb"),function=_vturb,units="km/s",validators=vort_validators)

def Turbulence_1D(name):
    if os.path.isfile(name+'_turb_1D.npy'):
示例#11
0
def _SToverSJ(field, data):
    fprops = data.get_field_parameter("flameprops", default=None)
    #alpha = fprops.get_value(data["density"],"density jump at the end of 12C-burning zone")
    alpha = fprops.get_value(data["density"], "12C fluid expansion factor")

    return data["flamespeed"] / (data["soundspeed"] / alpha)


yt.add_field(("flash", "SToverSCJ"),
             function=_SToverSJ,
             units="",
             sampling_type="cell",
             display_name=r"$S_\mathrm{T}/S_\mathrm{CJ}$",
             validators=[
                 ValidateParameter(['flameprops'],
                                   {"flameprops": [flameprops]})
             ])


def _velocityz(field, data):
    return data["velz"]


yt.add_field(("flash", "velocityz"),
             function=_velocityz,
             units="cm/s",
             sampling_type="cell",
             display_name="z-Velocity")


def _velocityx(field, data):
示例#12
0
def standard_particle_fields(registry,
                             ptype,
                             spos="particle_position_%s",
                             svel="particle_velocity_%s"):
    unit_system = registry.ds.unit_system

    def _particle_velocity_magnitude(field, data):
        """ M{|v|} """
        return np.sqrt(data[ptype, 'relative_%s' % (svel % 'x')]**2 +
                       data[ptype, 'relative_%s' % (svel % 'y')]**2 +
                       data[ptype, 'relative_%s' % (svel % 'z')]**2)

    registry.add_field((ptype, "particle_velocity_magnitude"),
                       sampling_type="particle",
                       function=_particle_velocity_magnitude,
                       take_log=False,
                       units=unit_system["velocity"])

    def _particle_specific_angular_momentum(field, data):
        """Calculate the angular of a particle velocity.

        Returns a vector for each particle.
        """
        center = data.get_field_parameter('center')
        pos, vel, normal = get_angular_momentum_components(
            ptype, data, spos, svel)
        L, r_vec, v_vec = modify_reference_frame(center, normal, P=pos, V=vel)
        # adding in the unit registry allows us to have a reference to the
        # dataset and thus we will always get the correct units after applying
        # the cross product.
        return ucross(r_vec, v_vec, registry=data.ds.unit_registry)

    registry.add_field((ptype, "particle_specific_angular_momentum"),
                       sampling_type="particle",
                       function=_particle_specific_angular_momentum,
                       units=unit_system["specific_angular_momentum"],
                       validators=[ValidateParameter("center")])

    def _get_spec_ang_mom_comp(axi, ax, _ptype):
        def _particle_specific_angular_momentum_component(field, data):
            return data[_ptype, "particle_specific_angular_momentum"][:, axi]

        def _particle_angular_momentum_component(field, data):
            return data[_ptype, "particle_mass"] * \
                data[ptype, "particle_specific_angular_momentum_%s" % ax]
        return _particle_specific_angular_momentum_component, \
            _particle_angular_momentum_component

    for axi, ax in enumerate("xyz"):
        f, v = _get_spec_ang_mom_comp(axi, ax, ptype)
        registry.add_field(
            (ptype, "particle_specific_angular_momentum_%s" % ax),
            sampling_type="particle",
            function=f,
            units=unit_system["specific_angular_momentum"],
            validators=[ValidateParameter("center")])
        registry.add_field((ptype, "particle_angular_momentum_%s" % ax),
                           sampling_type="particle",
                           function=v,
                           units=unit_system["angular_momentum"],
                           validators=[ValidateParameter('center')])

    def _particle_angular_momentum(field, data):
        am = data[ptype, "particle_mass"] * data[
            ptype, "particle_specific_angular_momentum"].T
        return am.T

    registry.add_field((ptype, "particle_angular_momentum"),
                       sampling_type="particle",
                       function=_particle_angular_momentum,
                       units=unit_system["angular_momentum"],
                       validators=[ValidateParameter("center")])

    create_magnitude_field(registry,
                           "particle_angular_momentum",
                           unit_system["angular_momentum"],
                           ftype=ptype,
                           particle_type=True)

    def _particle_radius(field, data):
        """The spherical radius component of the particle positions

        Relative to the coordinate system defined by the *normal* vector,
        and *center* field parameters.
        """
        return get_radius(data, "particle_position_", field.name[0])

    registry.add_field((ptype, "particle_radius"),
                       sampling_type="particle",
                       function=_particle_radius,
                       units=unit_system["length"],
                       validators=[ValidateParameter("center")])

    def _relative_particle_position(field, data):
        """The cartesian particle positions in a rotated reference frame

        Relative to the coordinate system defined by the *normal* vector and
        *center* field parameters.

        Note that the orientation of the x and y axes are arbitrary.
        """
        normal = data.get_field_parameter('normal')
        center = data.get_field_parameter('center')
        pos = data.ds.arr([data[ptype, spos % ax] for ax in "xyz"]).T
        L, pos = modify_reference_frame(center, normal, P=pos)
        return pos

    def _particle_position_relative(field, data):
        if not isinstance(data, FieldDetector):
            issue_deprecation_warning(
                "The 'particle_position_relative' field has been deprecated in "
                + "favor of 'relative_particle_position'.")
        if isinstance(field.name, tuple):
            return data[field.name[0], 'relative_particle_position']
        else:
            return data['relative_particle_position']

    for name, func in zip(
        ["particle_position_relative", "relative_particle_position"],
        [_particle_position_relative, _relative_particle_position]):
        registry.add_field((ptype, name),
                           sampling_type="particle",
                           function=func,
                           units=unit_system["length"],
                           validators=[
                               ValidateParameter("normal"),
                               ValidateParameter("center")
                           ])

    def _relative_particle_velocity(field, data):
        """The vector particle velocities in an arbitrary coordinate system

        Relative to the coordinate system defined by the *normal* vector,
        *bulk_velocity* vector and *center* field parameters.

        Note that the orientation of the x and y axes are arbitrary.
        """
        normal = data.get_field_parameter('normal')
        center = data.get_field_parameter('center')
        bv = data.get_field_parameter("bulk_velocity")
        vel = data.ds.arr([
            data[ptype, svel % ax] - bv[iax] for iax, ax in enumerate("xyz")
        ]).T
        L, vel = modify_reference_frame(center, normal, V=vel)
        return vel

    def _particle_velocity_relative(field, data):
        if not isinstance(data, FieldDetector):
            issue_deprecation_warning(
                "The 'particle_velocity_relative' field has been deprecated in "
                + "favor of 'relative_particle_velocity'.")
        if isinstance(field.name, tuple):
            return data[field.name[0], 'relative_particle_velocity']
        else:
            return data['relative_particle_velocity']

    for name, func in zip(
        ["particle_velocity_relative", "relative_particle_velocity"],
        [_particle_velocity_relative, _relative_particle_velocity]):
        registry.add_field((ptype, name),
                           sampling_type="particle",
                           function=func,
                           units=unit_system["velocity"],
                           validators=[
                               ValidateParameter("normal"),
                               ValidateParameter("center")
                           ])

    def _get_coord_funcs_relative(axi, _ptype):
        def _particle_pos_rel(field, data):
            return data[_ptype, "relative_particle_position"][:, axi]

        def _particle_vel_rel(field, data):
            return data[_ptype, "relative_particle_velocity"][:, axi]

        return _particle_vel_rel, _particle_pos_rel

    for axi, ax in enumerate("xyz"):
        v, p = _get_coord_funcs_relative(axi, ptype)
        registry.add_field((ptype, "particle_velocity_relative_%s" % ax),
                           sampling_type="particle",
                           function=v,
                           units="code_velocity")
        registry.add_field((ptype, "particle_position_relative_%s" % ax),
                           sampling_type="particle",
                           function=p,
                           units="code_length")
        registry.add_field((ptype, "relative_particle_velocity_%s" % ax),
                           sampling_type="particle",
                           function=v,
                           units="code_velocity")
        registry.add_field((ptype, "relative_particle_position_%s" % ax),
                           sampling_type="particle",
                           function=p,
                           units="code_length")

    # this is just particle radius but we add it with an alias for the sake of
    # consistent naming
    registry.add_field(
        (ptype, "particle_position_spherical_radius"),
        sampling_type="particle",
        function=_particle_radius,
        units=unit_system["length"],
        validators=[ValidateParameter("normal"),
                    ValidateParameter("center")])

    def _particle_spherical_position_radius(field, data):
        """This field is deprecated and will be removed in a future release"""
        return data[ptype, 'particle_position_spherical_radius']

    registry.add_field(
        (ptype, "particle_spherical_position_radius"),
        sampling_type="particle",
        function=_particle_spherical_position_radius,
        units=unit_system["length"],
        validators=[ValidateParameter("normal"),
                    ValidateParameter("center")])

    def _particle_position_spherical_theta(field, data):
        """The spherical theta coordinate of the particle positions.

        Relative to the coordinate system defined by the *normal* vector
        and *center* field parameters.
        """
        normal = data.get_field_parameter('normal')
        pos = data['relative_particle_position'].T
        return data.ds.arr(get_sph_theta(pos, normal), "")

    registry.add_field(
        (ptype, "particle_position_spherical_theta"),
        sampling_type="particle",
        function=_particle_position_spherical_theta,
        units="",
        validators=[ValidateParameter("center"),
                    ValidateParameter("normal")])

    def _particle_spherical_position_theta(field, data):
        """This field is deprecated and will be removed in a future release"""
        return data[ptype, 'particle_position_spherical_theta']

    registry.add_field(
        (ptype, "particle_spherical_position_theta"),
        sampling_type="particle",
        function=_particle_spherical_position_theta,
        units="",
        validators=[ValidateParameter("normal"),
                    ValidateParameter("center")])

    def _particle_position_spherical_phi(field, data):
        """The spherical phi component of the particle positions

        Relative to the coordinate system defined by the *normal* vector
        and *center* field parameters.
        """
        normal = data.get_field_parameter('normal')
        pos = data['relative_particle_position'].T
        return data.ds.arr(get_sph_phi(pos, normal), "")

    registry.add_field(
        (ptype, "particle_position_spherical_phi"),
        sampling_type="particle",
        function=_particle_position_spherical_phi,
        units="",
        validators=[ValidateParameter("normal"),
                    ValidateParameter("center")])

    def _particle_spherical_position_phi(field, data):
        """This field is deprecated and will be removed in a future release"""
        return data[ptype, 'particle_position_spherical_phi']

    registry.add_field(
        (ptype, "particle_spherical_position_phi"),
        sampling_type="particle",
        function=_particle_spherical_position_phi,
        units="",
        validators=[ValidateParameter("center"),
                    ValidateParameter("normal")])

    def _particle_velocity_spherical_radius(field, data):
        """The spherical radius component of the particle velocities in an
         arbitrary coordinate system

        Relative to the coordinate system defined by the *normal* vector,
        *bulk_velocity* vector and *center* field parameters.
        """
        normal = data.get_field_parameter('normal')
        pos = data['relative_particle_position'].T
        vel = data['relative_particle_velocity'].T
        theta = get_sph_theta(pos, normal)
        phi = get_sph_phi(pos, normal)
        sphr = get_sph_r_component(vel, theta, phi, normal)
        return sphr

    registry.add_field(
        (ptype, "particle_velocity_spherical_radius"),
        sampling_type="particle",
        function=_particle_velocity_spherical_radius,
        units=unit_system["velocity"],
        validators=[ValidateParameter("normal"),
                    ValidateParameter("center")])

    def _particle_spherical_velocity_radius(field, data):
        """This field is deprecated and will be removed in a future release"""
        return data[ptype, 'particle_velocity_spherical_radius']

    registry.add_field(
        (ptype, "particle_spherical_velocity_radius"),
        sampling_type="particle",
        function=_particle_spherical_velocity_radius,
        units=unit_system["velocity"],
        validators=[ValidateParameter("normal"),
                    ValidateParameter("center")])

    # particel_velocity_spherical_radius is simply aliased to
    # "particle_radial_velocity" for convenience
    registry.add_field(
        (ptype, "particle_radial_velocity"),
        sampling_type="particle",
        function=_particle_spherical_velocity_radius,
        units=unit_system["velocity"],
        validators=[ValidateParameter("normal"),
                    ValidateParameter("center")])

    def _particle_velocity_spherical_theta(field, data):
        """The spherical theta component of the particle velocities in an
         arbitrary coordinate system

        Relative to the coordinate system defined by the *normal* vector,
        *bulk_velocity* vector and *center* field parameters.
        """
        normal = data.get_field_parameter('normal')
        pos = data['relative_particle_position'].T
        vel = data['relative_particle_velocity'].T
        theta = get_sph_theta(pos, normal)
        phi = get_sph_phi(pos, normal)
        spht = get_sph_theta_component(vel, theta, phi, normal)
        return spht

    registry.add_field(
        (ptype, "particle_velocity_spherical_theta"),
        sampling_type="particle",
        function=_particle_velocity_spherical_theta,
        units=unit_system["velocity"],
        validators=[ValidateParameter("normal"),
                    ValidateParameter("center")])

    def _particle_spherical_velocity_theta(field, data):
        """This field is deprecated and will be removed in a future release"""
        return data[ptype, 'particle_velocity_spherical_theta']

    registry.add_field(
        (ptype, "particle_spherical_velocity_theta"),
        sampling_type="particle",
        function=_particle_spherical_velocity_theta,
        units=unit_system["velocity"],
        validators=[ValidateParameter("normal"),
                    ValidateParameter("center")])

    def _particle_velocity_spherical_phi(field, data):
        """The spherical phi component of the particle velocities

        Relative to the coordinate system defined by the *normal* vector,
        *bulk_velocity* vector and *center* field parameters.
        """
        normal = data.get_field_parameter('normal')
        pos = data['relative_particle_position'].T
        vel = data['relative_particle_velocity'].T
        phi = get_sph_phi(pos, normal)
        sphp = get_sph_phi_component(vel, phi, normal)
        return sphp

    registry.add_field(
        (ptype, "particle_velocity_spherical_phi"),
        sampling_type="particle",
        function=_particle_velocity_spherical_phi,
        units=unit_system["velocity"],
        validators=[ValidateParameter("normal"),
                    ValidateParameter("center")])

    def _particle_spherical_velocity_phi(field, data):
        """This field is deprecated and will be removed in a future release"""
        return data[ptype, 'particle_spherical_velocity_theta']

    registry.add_field(
        (ptype, "particle_spherical_velocity_phi"),
        sampling_type="particle",
        function=_particle_spherical_velocity_phi,
        units=unit_system["velocity"],
        validators=[ValidateParameter("normal"),
                    ValidateParameter("center")])

    def _particle_position_cylindrical_radius(field, data):
        """The cylindrical radius component of the particle positions

        Relative to the coordinate system defined by the *normal* vector
        and *center* field parameters.
        """
        normal = data.get_field_parameter('normal')
        pos = data['relative_particle_position'].T
        return data.ds.arr(get_cyl_r(pos, normal), 'code_length')

    registry.add_field(
        (ptype, "particle_position_cylindrical_radius"),
        sampling_type="particle",
        function=_particle_position_cylindrical_radius,
        units=unit_system["length"],
        validators=[ValidateParameter("normal"),
                    ValidateParameter("center")])

    def _particle_position_cylindrical_theta(field, data):
        """The cylindrical theta component of the particle positions

        Relative to the coordinate system defined by the *normal* vector
        and *center* field parameters.
        """
        normal = data.get_field_parameter('normal')
        pos = data['relative_particle_position'].T
        return data.ds.arr(get_cyl_theta(pos, normal), "")

    registry.add_field(
        (ptype, "particle_position_cylindrical_theta"),
        sampling_type="particle",
        function=_particle_position_cylindrical_theta,
        units="",
        validators=[ValidateParameter("center"),
                    ValidateParameter("normal")])

    def _particle_position_cylindrical_z(field, data):
        """The cylindrical z component of the particle positions

        Relative to the coordinate system defined by the *normal* vector
        and *center* field parameters.
        """
        normal = data.get_field_parameter('normal')
        pos = data['relative_particle_position'].T
        return data.ds.arr(get_cyl_z(pos, normal), 'code_length')

    registry.add_field(
        (ptype, "particle_position_cylindrical_z"),
        sampling_type="particle",
        function=_particle_position_cylindrical_z,
        units=unit_system["length"],
        validators=[ValidateParameter("normal"),
                    ValidateParameter("center")])

    def _particle_velocity_cylindrical_radius(field, data):
        """The cylindrical radius component of the particle velocities

        Relative to the coordinate system defined by the *normal* vector,
        *bulk_velocity* vector and *center* field parameters.
        """
        normal = data.get_field_parameter('normal')
        pos = data['relative_particle_position'].T
        vel = data['relative_particle_velocity'].T
        theta = get_cyl_theta(pos, normal)
        cylr = get_cyl_r_component(vel, theta, normal)
        return cylr

    registry.add_field(
        (ptype, "particle_velocity_cylindrical_radius"),
        sampling_type="particle",
        function=_particle_velocity_cylindrical_radius,
        units=unit_system["velocity"],
        validators=[ValidateParameter("normal"),
                    ValidateParameter("center")])

    def _particle_velocity_cylindrical_theta(field, data):
        """The cylindrical theta component of the particle velocities

        Relative to the coordinate system defined by the *normal* vector,
        *bulk_velocity* vector and *center* field parameters.
        """
        normal = data.get_field_parameter('normal')
        pos = data['relative_particle_position'].T
        vel = data['relative_particle_velocity'].T
        theta = get_cyl_theta(pos, normal)
        cylt = get_cyl_theta_component(vel, theta, normal)
        return cylt

    registry.add_field(
        (ptype, "particle_velocity_cylindrical_theta"),
        sampling_type="particle",
        function=_particle_velocity_cylindrical_theta,
        units=unit_system["velocity"],
        validators=[ValidateParameter("normal"),
                    ValidateParameter("center")])

    def _particle_cylindrical_velocity_theta(field, data):
        """This field is deprecated and will be removed in a future release"""
        return data[ptype, 'particle_velocity_cylindrical_theta']

    registry.add_field(
        (ptype, "particle_cylindrical_velocity_theta"),
        sampling_type="particle",
        function=_particle_cylindrical_velocity_theta,
        units="cm/s",
        validators=[ValidateParameter("normal"),
                    ValidateParameter("center")])

    def _particle_velocity_cylindrical_z(field, data):
        """The cylindrical z component of the particle velocities

        Relative to the coordinate system defined by the *normal* vector,
        *bulk_velocity* vector and *center* field parameters.
        """
        normal = data.get_field_parameter('normal')
        vel = data['relative_particle_velocity'].T
        cylz = get_cyl_z_component(vel, normal)
        return cylz

    registry.add_field(
        (ptype, "particle_velocity_cylindrical_z"),
        sampling_type="particle",
        function=_particle_velocity_cylindrical_z,
        units=unit_system["velocity"],
        validators=[ValidateParameter("normal"),
                    ValidateParameter("center")])

    def _particle_cylindrical_velocity_z(field, data):
        """This field is deprecated and will be removed in a future release"""
        return data[ptype, "particle_velocity_cylindrical_z"]

    registry.add_field(
        (ptype, "particle_cylindrical_velocity_z"),
        sampling_type="particle",
        function=_particle_cylindrical_velocity_z,
        units=unit_system["velocity"],
        validators=[ValidateParameter("normal"),
                    ValidateParameter("center")])
示例#13
0
def setup_magnetic_field_fields(registry, ftype="gas", slice_info=None):
    unit_system = registry.ds.unit_system

    if (ftype, "magnetic_field_x") not in registry:
        return

    u = registry[ftype, "magnetic_field_x"].units

    def _magnetic_field_strength(field, data):
        B2 = (data[ftype, "magnetic_field_x"]**2 +
              data[ftype, "magnetic_field_y"]**2 +
              data[ftype, "magnetic_field_z"]**2)
        return np.sqrt(B2)

    registry.add_field((ftype, "magnetic_field_strength"),
                       function=_magnetic_field_strength,
                       units=u)

    def _magnetic_energy(field, data):
        B = data[ftype, "magnetic_field_strength"]
        return 0.5 * B * B / mag_factors[B.units.dimensions]

    registry.add_field((ftype, "magnetic_energy"),
                       function=_magnetic_energy,
                       units=unit_system["pressure"])

    def _plasma_beta(field, data):
        return data[ftype, 'pressure'] / data[ftype, 'magnetic_energy']

    registry.add_field((ftype, "plasma_beta"), function=_plasma_beta, units="")

    def _magnetic_pressure(field, data):
        return data[ftype, 'magnetic_energy']

    registry.add_field((ftype, "magnetic_pressure"),
                       function=_magnetic_pressure,
                       units=unit_system["pressure"])

    def _magnetic_field_poloidal(field, data):
        normal = data.get_field_parameter("normal")
        d = data[ftype, 'magnetic_field_x']
        Bfields = data.ds.arr([
            data[ftype, 'magnetic_field_x'], data[ftype, 'magnetic_field_y'],
            data[ftype, 'magnetic_field_z']
        ], d.units)

        theta = data["index", 'spherical_theta']
        phi = data["index", 'spherical_phi']

        return get_sph_theta_component(Bfields, theta, phi, normal)

    registry.add_field((ftype, "magnetic_field_poloidal"),
                       function=_magnetic_field_poloidal,
                       units=u,
                       validators=[ValidateParameter("normal")])

    def _magnetic_field_toroidal(field, data):
        normal = data.get_field_parameter("normal")
        d = data[ftype, 'magnetic_field_x']
        Bfields = data.ds.arr([
            data[ftype, 'magnetic_field_x'], data[ftype, 'magnetic_field_y'],
            data[ftype, 'magnetic_field_z']
        ], d.units)

        phi = data["index", 'spherical_phi']
        return get_sph_phi_component(Bfields, phi, normal)

    registry.add_field((ftype, "magnetic_field_toroidal"),
                       function=_magnetic_field_toroidal,
                       units=u,
                       validators=[ValidateParameter("normal")])

    def _alfven_speed(field, data):
        B = data[ftype, 'magnetic_field_strength']
        return B / np.sqrt(
            mag_factors[B.units.dimensions] * data[ftype, 'density'])

    registry.add_field((ftype, "alfven_speed"),
                       function=_alfven_speed,
                       units=unit_system["velocity"])

    def _mach_alfven(field, data):
        return data[ftype, 'velocity_magnitude'] / data[ftype, 'alfven_speed']

    registry.add_field((ftype, "mach_alfven"),
                       function=_mach_alfven,
                       units="dimensionless")
示例#14
0
def setup_magnetic_field_fields(registry, ftype="gas", slice_info=None):
    unit_system = registry.ds.unit_system

    axis_names = registry.ds.coordinates.axis_order

    if (ftype, "magnetic_field_%s" % axis_names[0]) not in registry:
        return

    u = registry[ftype, "magnetic_field_%s" % axis_names[0]].units

    def _magnetic_field_strength(field, data):
        xm = "relative_magnetic_field_%s" % axis_names[0]
        ym = "relative_magnetic_field_%s" % axis_names[1]
        zm = "relative_magnetic_field_%s" % axis_names[2]

        B2 = (data[ftype, xm])**2 + (data[ftype, ym])**2 + (data[ftype, zm])**2

        return handle_mks_cgs(np.sqrt(B2), field.units)

    registry.add_field((ftype, "magnetic_field_strength"),
                       sampling_type="cell",
                       function=_magnetic_field_strength,
                       validators=[ValidateParameter('bulk_magnetic_field')],
                       units=u)

    def _magnetic_energy(field, data):
        B = data[ftype, "magnetic_field_strength"]
        return 0.5 * B * B / mag_factors[B.units.dimensions]

    registry.add_field((ftype, "magnetic_energy"),
                       sampling_type="cell",
                       function=_magnetic_energy,
                       units=unit_system["pressure"])

    def _plasma_beta(field, data):
        return data[ftype, 'pressure'] / data[ftype, 'magnetic_energy']

    registry.add_field((ftype, "plasma_beta"),
                       sampling_type="cell",
                       function=_plasma_beta,
                       units="")

    def _magnetic_pressure(field, data):
        return data[ftype, 'magnetic_energy']

    registry.add_field((ftype, "magnetic_pressure"),
                       sampling_type="cell",
                       function=_magnetic_pressure,
                       units=unit_system["pressure"])

    if registry.ds.geometry == "cartesian":

        def _magnetic_field_poloidal(field, data):
            normal = data.get_field_parameter("normal")

            Bfields = ustack([
                data[ftype, 'relative_magnetic_field_x'],
                data[ftype, 'relative_magnetic_field_y'],
                data[ftype, 'relative_magnetic_field_z']
            ])

            theta = data["index", 'spherical_theta']
            phi = data["index", 'spherical_phi']

            return get_sph_theta_component(Bfields, theta, phi, normal)

        def _magnetic_field_toroidal(field, data):
            normal = data.get_field_parameter("normal")

            Bfields = ustack([
                data[ftype, 'relative_magnetic_field_x'],
                data[ftype, 'relative_magnetic_field_y'],
                data[ftype, 'relative_magnetic_field_z']
            ])

            phi = data["index", 'spherical_phi']
            return get_sph_phi_component(Bfields, phi, normal)

    elif registry.ds.geometry == "cylindrical":

        def _magnetic_field_poloidal(field, data):
            bm = handle_mks_cgs(
                data.get_field_parameter("bulk_magnetic_field"), field.units)
            r = data["index", "r"]
            z = data["index", "z"]
            d = np.sqrt(r * r + z * z)
            rax = axis_names.find('r')
            zax = axis_names.find('z')
            return ((data[ftype, "magnetic_field_r"] - bm[rax]) * (r / d) +
                    (data[ftype, "magnetic_field_z"] - bm[zax]) * (z / d))

        def _magnetic_field_toroidal(field, data):
            ax = axis_names.find('theta')
            bm = handle_mks_cgs(
                data.get_field_parameter("bulk_magnetic_field"), field.units)
            return data[ftype, "magnetic_field_theta"] - bm[ax]

    elif registry.ds.geometry == "spherical":

        def _magnetic_field_poloidal(field, data):
            ax = axis_names.find('theta')
            bm = handle_mks_cgs(
                data.get_field_parameter("bulk_magnetic_field"), field.units)
            return data[ftype, "magnetic_field_theta"] - bm[ax]

        def _magnetic_field_toroidal(field, data):
            ax = axis_names.find('phi')
            bm = handle_mks_cgs(
                data.get_field_parameter("bulk_magnetic_field"), field.units)
            return data[ftype, "magnetic_field_phi"] - bm[ax]

    else:

        # Unidentified geometry--set to None

        _magnetic_field_toroidal = None
        _magnetic_field_poloidal = None

    registry.add_field((ftype, "magnetic_field_poloidal"),
                       sampling_type="cell",
                       function=_magnetic_field_poloidal,
                       units=u,
                       validators=[
                           ValidateParameter("normal"),
                           ValidateParameter("bulk_magnetic_field")
                       ])

    registry.add_field((ftype, "magnetic_field_toroidal"),
                       sampling_type="cell",
                       function=_magnetic_field_toroidal,
                       units=u,
                       validators=[
                           ValidateParameter("normal"),
                           ValidateParameter("bulk_magnetic_field")
                       ])

    def _alfven_speed(field, data):
        B = data[ftype, 'magnetic_field_strength']
        return B / np.sqrt(
            mag_factors[B.units.dimensions] * data[ftype, 'density'])

    registry.add_field((ftype, "alfven_speed"),
                       sampling_type="cell",
                       function=_alfven_speed,
                       units=unit_system["velocity"])

    def _mach_alfven(field, data):
        return data[ftype, 'velocity_magnitude'] / data[ftype, 'alfven_speed']

    registry.add_field((ftype, "mach_alfven"),
                       sampling_type="cell",
                       function=_mach_alfven,
                       units="dimensionless")
示例#15
0
def standard_particle_fields(
    registry, ptype, spos="particle_position_%s", svel="particle_velocity_%s"
):
    unit_system = registry.ds.unit_system

    def _particle_velocity_magnitude(field, data):
        """ M{|v|} """
        return np.sqrt(
            data[ptype, f"relative_{svel % 'x'}"] ** 2
            + data[ptype, f"relative_{svel % 'y'}"] ** 2
            + data[ptype, f"relative_{svel % 'z'}"] ** 2
        )

    registry.add_field(
        (ptype, "particle_velocity_magnitude"),
        sampling_type="particle",
        function=_particle_velocity_magnitude,
        take_log=False,
        units=unit_system["velocity"],
    )

    def _particle_specific_angular_momentum(field, data):
        """Calculate the angular of a particle velocity.

        Returns a vector for each particle.
        """
        center = data.get_field_parameter("center")
        pos, vel, normal = get_angular_momentum_components(ptype, data, spos, svel)
        L, r_vec, v_vec = modify_reference_frame(center, normal, P=pos, V=vel)
        # adding in the unit registry allows us to have a reference to the
        # dataset and thus we will always get the correct units after applying
        # the cross product.
        return ucross(r_vec, v_vec, registry=data.ds.unit_registry)

    registry.add_field(
        (ptype, "particle_specific_angular_momentum"),
        sampling_type="particle",
        function=_particle_specific_angular_momentum,
        units=unit_system["specific_angular_momentum"],
        validators=[ValidateParameter("center")],
    )

    def _get_spec_ang_mom_comp(axi, ax, _ptype):
        def _particle_specific_angular_momentum_component(field, data):
            return data[_ptype, "particle_specific_angular_momentum"][:, axi]

        def _particle_angular_momentum_component(field, data):
            return (
                data[_ptype, "particle_mass"]
                * data[ptype, f"particle_specific_angular_momentum_{ax}"]
            )

        return (
            _particle_specific_angular_momentum_component,
            _particle_angular_momentum_component,
        )

    for axi, ax in enumerate("xyz"):
        f, v = _get_spec_ang_mom_comp(axi, ax, ptype)
        registry.add_field(
            (ptype, f"particle_specific_angular_momentum_{ax}"),
            sampling_type="particle",
            function=f,
            units=unit_system["specific_angular_momentum"],
            validators=[ValidateParameter("center")],
        )
        registry.add_field(
            (ptype, f"particle_angular_momentum_{ax}"),
            sampling_type="particle",
            function=v,
            units=unit_system["angular_momentum"],
            validators=[ValidateParameter("center")],
        )

    def _particle_angular_momentum(field, data):
        am = (
            data[ptype, "particle_mass"]
            * data[ptype, "particle_specific_angular_momentum"].T
        )
        return am.T

    registry.add_field(
        (ptype, "particle_angular_momentum"),
        sampling_type="particle",
        function=_particle_angular_momentum,
        units=unit_system["angular_momentum"],
        validators=[ValidateParameter("center")],
    )

    create_magnitude_field(
        registry,
        "particle_angular_momentum",
        unit_system["angular_momentum"],
        sampling_type="particle",
        ftype=ptype,
    )

    def _particle_radius(field, data):
        """The spherical radius component of the particle positions

        Relative to the coordinate system defined by the *normal* vector,
        and *center* field parameters.
        """
        return get_radius(data, "particle_position_", field.name[0])

    registry.add_field(
        (ptype, "particle_radius"),
        sampling_type="particle",
        function=_particle_radius,
        units=unit_system["length"],
        validators=[ValidateParameter("center")],
    )

    def _relative_particle_position(field, data):
        """The cartesian particle positions in a rotated reference frame

        Relative to the coordinate system defined by *center* field parameter.

        Note that the orientation of the x and y axes are arbitrary.
        """
        field_names = [(ptype, f"particle_position_{ax}") for ax in "xyz"]
        return obtain_position_vector(data, field_names=field_names).T

    registry.add_field(
        (ptype, "relative_particle_position"),
        sampling_type="particle",
        function=_relative_particle_position,
        units=unit_system["length"],
        validators=[ValidateParameter("normal"), ValidateParameter("center")],
    )

    def _relative_particle_velocity(field, data):
        """The vector particle velocities in an arbitrary coordinate system

        Relative to the coordinate system defined by the *bulk_velocity*
        vector field parameter.

        Note that the orientation of the x and y axes are arbitrary.
        """
        field_names = [(ptype, f"particle_velocity_{ax}") for ax in "xyz"]
        return obtain_relative_velocity_vector(data, field_names=field_names).T

    registry.add_field(
        (ptype, "relative_particle_velocity"),
        sampling_type="particle",
        function=_relative_particle_velocity,
        units=unit_system["velocity"],
        validators=[ValidateParameter("normal"), ValidateParameter("center")],
    )

    def _get_coord_funcs_relative(axi, _ptype):
        def _particle_pos_rel(field, data):
            return data[_ptype, "relative_particle_position"][:, axi]

        def _particle_vel_rel(field, data):
            return data[_ptype, "relative_particle_velocity"][:, axi]

        return _particle_vel_rel, _particle_pos_rel

    for axi, ax in enumerate("xyz"):
        v, p = _get_coord_funcs_relative(axi, ptype)
        registry.add_field(
            (ptype, f"particle_velocity_relative_{ax}"),
            sampling_type="particle",
            function=v,
            units="code_velocity",
        )
        registry.add_field(
            (ptype, f"particle_position_relative_{ax}"),
            sampling_type="particle",
            function=p,
            units="code_length",
        )
        registry.add_field(
            (ptype, f"relative_particle_velocity_{ax}"),
            sampling_type="particle",
            function=v,
            units="code_velocity",
        )
        registry.add_field(
            (ptype, f"relative_particle_position_{ax}"),
            sampling_type="particle",
            function=p,
            units="code_length",
        )

    # this is just particle radius but we add it with an alias for the sake of
    # consistent naming
    registry.add_field(
        (ptype, "particle_position_spherical_radius"),
        sampling_type="particle",
        function=_particle_radius,
        units=unit_system["length"],
        validators=[ValidateParameter("normal"), ValidateParameter("center")],
    )

    registry.alias(
        (ptype, "particle_spherical_position_radius"),
        (ptype, "particle_position_spherical_radius"),
        deprecate=("4.0.0", "4.1.0"),
    )

    def _particle_position_spherical_theta(field, data):
        """The spherical theta coordinate of the particle positions.

        Relative to the coordinate system defined by the *normal* vector
        and *center* field parameters.
        """
        normal = data.get_field_parameter("normal")
        pos = data["relative_particle_position"].T
        return data.ds.arr(get_sph_theta(pos, normal), "")

    registry.add_field(
        (ptype, "particle_position_spherical_theta"),
        sampling_type="particle",
        function=_particle_position_spherical_theta,
        units="",
        validators=[ValidateParameter("center"), ValidateParameter("normal")],
    )

    registry.alias(
        (ptype, "particle_spherical_position_theta"),
        (ptype, "particle_position_spherical_theta"),
        deprecate=("4.0.0", "4.1.0"),
    )

    def _particle_position_spherical_phi(field, data):
        """The spherical phi component of the particle positions

        Relative to the coordinate system defined by the *normal* vector
        and *center* field parameters.
        """
        normal = data.get_field_parameter("normal")
        pos = data["relative_particle_position"].T
        return data.ds.arr(get_sph_phi(pos, normal), "")

    registry.add_field(
        (ptype, "particle_position_spherical_phi"),
        sampling_type="particle",
        function=_particle_position_spherical_phi,
        units="",
        validators=[ValidateParameter("normal"), ValidateParameter("center")],
    )

    registry.alias(
        (ptype, "particle_spherical_position_phi"),
        (ptype, "particle_position_spherical_phi"),
        deprecate=("4.0.0", "4.1.0"),
    )

    def _particle_velocity_spherical_radius(field, data):
        """The spherical radius component of the particle velocities in an
         arbitrary coordinate system

        Relative to the coordinate system defined by the *normal* vector,
        *bulk_velocity* vector and *center* field parameters.
        """
        normal = data.get_field_parameter("normal")
        pos = data["relative_particle_position"].T
        vel = data["relative_particle_velocity"].T
        theta = get_sph_theta(pos, normal)
        phi = get_sph_phi(pos, normal)
        sphr = get_sph_r_component(vel, theta, phi, normal)
        return sphr

    registry.add_field(
        (ptype, "particle_velocity_spherical_radius"),
        sampling_type="particle",
        function=_particle_velocity_spherical_radius,
        units=unit_system["velocity"],
        validators=[ValidateParameter("normal"), ValidateParameter("center")],
    )

    registry.alias(
        (ptype, "particle_spherical_velocity_radius"),
        (ptype, "particle_velocity_spherical_radius"),
        deprecate=("4.0.0", "4.1.0"),
    )

    registry.alias(
        (ptype, "particle_radial_velocity"),
        (ptype, "particle_velocity_spherical_radius"),
    )

    def _particle_velocity_spherical_theta(field, data):
        """The spherical theta component of the particle velocities in an
         arbitrary coordinate system

        Relative to the coordinate system defined by the *normal* vector,
        *bulk_velocity* vector and *center* field parameters.
        """
        normal = data.get_field_parameter("normal")
        pos = data["relative_particle_position"].T
        vel = data["relative_particle_velocity"].T
        theta = get_sph_theta(pos, normal)
        phi = get_sph_phi(pos, normal)
        spht = get_sph_theta_component(vel, theta, phi, normal)
        return spht

    registry.add_field(
        (ptype, "particle_velocity_spherical_theta"),
        sampling_type="particle",
        function=_particle_velocity_spherical_theta,
        units=unit_system["velocity"],
        validators=[ValidateParameter("normal"), ValidateParameter("center")],
    )

    registry.alias(
        (ptype, "particle_spherical_velocity_theta"),
        (ptype, "particle_velocity_spherical_theta"),
        deprecate=("4.0.0", "4.1.0"),
    )

    def _particle_velocity_spherical_phi(field, data):
        """The spherical phi component of the particle velocities

        Relative to the coordinate system defined by the *normal* vector,
        *bulk_velocity* vector and *center* field parameters.
        """
        normal = data.get_field_parameter("normal")
        pos = data["relative_particle_position"].T
        vel = data["relative_particle_velocity"].T
        phi = get_sph_phi(pos, normal)
        sphp = get_sph_phi_component(vel, phi, normal)
        return sphp

    registry.add_field(
        (ptype, "particle_velocity_spherical_phi"),
        sampling_type="particle",
        function=_particle_velocity_spherical_phi,
        units=unit_system["velocity"],
        validators=[ValidateParameter("normal"), ValidateParameter("center")],
    )

    registry.alias(
        (ptype, "particle_spherical_velocity_phi"),
        (ptype, "particle_velocity_spherical_phi"),
        deprecate=("4.0.0", "4.1.0"),
    )

    def _particle_position_cylindrical_radius(field, data):
        """The cylindrical radius component of the particle positions

        Relative to the coordinate system defined by the *normal* vector
        and *center* field parameters.
        """
        normal = data.get_field_parameter("normal")
        pos = data["relative_particle_position"].T
        pos.convert_to_units("code_length")
        return data.ds.arr(get_cyl_r(pos, normal), "code_length")

    registry.add_field(
        (ptype, "particle_position_cylindrical_radius"),
        sampling_type="particle",
        function=_particle_position_cylindrical_radius,
        units=unit_system["length"],
        validators=[ValidateParameter("normal"), ValidateParameter("center")],
    )

    def _particle_position_cylindrical_theta(field, data):
        """The cylindrical theta component of the particle positions

        Relative to the coordinate system defined by the *normal* vector
        and *center* field parameters.
        """
        normal = data.get_field_parameter("normal")
        pos = data["relative_particle_position"].T
        return data.ds.arr(get_cyl_theta(pos, normal), "")

    registry.add_field(
        (ptype, "particle_position_cylindrical_theta"),
        sampling_type="particle",
        function=_particle_position_cylindrical_theta,
        units="",
        validators=[ValidateParameter("center"), ValidateParameter("normal")],
    )

    def _particle_position_cylindrical_z(field, data):
        """The cylindrical z component of the particle positions

        Relative to the coordinate system defined by the *normal* vector
        and *center* field parameters.
        """
        normal = data.get_field_parameter("normal")
        pos = data["relative_particle_position"].T
        pos.convert_to_units("code_length")
        return data.ds.arr(get_cyl_z(pos, normal), "code_length")

    registry.add_field(
        (ptype, "particle_position_cylindrical_z"),
        sampling_type="particle",
        function=_particle_position_cylindrical_z,
        units=unit_system["length"],
        validators=[ValidateParameter("normal"), ValidateParameter("center")],
    )

    def _particle_velocity_cylindrical_radius(field, data):
        """The cylindrical radius component of the particle velocities

        Relative to the coordinate system defined by the *normal* vector,
        *bulk_velocity* vector and *center* field parameters.
        """
        normal = data.get_field_parameter("normal")
        pos = data["relative_particle_position"].T
        vel = data["relative_particle_velocity"].T
        theta = get_cyl_theta(pos, normal)
        cylr = get_cyl_r_component(vel, theta, normal)
        return cylr

    registry.add_field(
        (ptype, "particle_velocity_cylindrical_radius"),
        sampling_type="particle",
        function=_particle_velocity_cylindrical_radius,
        units=unit_system["velocity"],
        validators=[ValidateParameter("normal"), ValidateParameter("center")],
    )

    def _particle_velocity_cylindrical_theta(field, data):
        """The cylindrical theta component of the particle velocities

        Relative to the coordinate system defined by the *normal* vector,
        *bulk_velocity* vector and *center* field parameters.
        """
        normal = data.get_field_parameter("normal")
        pos = data["relative_particle_position"].T
        vel = data["relative_particle_velocity"].T
        theta = get_cyl_theta(pos, normal)
        cylt = get_cyl_theta_component(vel, theta, normal)
        return cylt

    registry.add_field(
        (ptype, "particle_velocity_cylindrical_theta"),
        sampling_type="particle",
        function=_particle_velocity_cylindrical_theta,
        units=unit_system["velocity"],
        validators=[ValidateParameter("normal"), ValidateParameter("center")],
    )

    registry.alias(
        (ptype, "particle_cylindrical_velocity_theta"),
        (ptype, "particle_velocity_cylindrical_theta"),
        deprecate=("4.0.0", "4.1.0"),
    )

    def _particle_velocity_cylindrical_z(field, data):
        """The cylindrical z component of the particle velocities

        Relative to the coordinate system defined by the *normal* vector,
        *bulk_velocity* vector and *center* field parameters.
        """
        normal = data.get_field_parameter("normal")
        vel = data["relative_particle_velocity"].T
        cylz = get_cyl_z_component(vel, normal)
        return cylz

    registry.add_field(
        (ptype, "particle_velocity_cylindrical_z"),
        sampling_type="particle",
        function=_particle_velocity_cylindrical_z,
        units=unit_system["velocity"],
        validators=[ValidateParameter("normal"), ValidateParameter("center")],
    )

    registry.alias(
        (ptype, "particle_cylindrical_velocity_z"),
        (ptype, "particle_velocity_cylindrical_z"),
        deprecate=("4.0.0", "4.1.0"),
    )
示例#16
0
def standard_particle_fields(registry,
                             ptype,
                             spos="particle_position_%s",
                             svel="particle_velocity_%s"):
    unit_system = registry.ds.unit_system

    # This function will set things up based on the scalar fields and standard
    # yt field names.
    # data.get_field_parameter("bulk_velocity") defaults to YTArray([0,0,0] cm/s)

    def _particle_velocity_magnitude(field, data):
        """ M{|v|} """
        bulk_velocity = data.get_field_parameter("bulk_velocity")
        return np.sqrt((data[ptype, svel % 'x'] - bulk_velocity[0])**2 +
                       (data[ptype, svel % 'y'] - bulk_velocity[1])**2 +
                       (data[ptype, svel % 'z'] - bulk_velocity[2])**2)

    registry.add_field((ptype, "particle_velocity_magnitude"),
                       function=_particle_velocity_magnitude,
                       particle_type=True,
                       take_log=False,
                       units=unit_system["velocity"])

    def _particle_specific_angular_momentum(field, data):
        """
        Calculate the angular of a particle velocity.  Returns a vector for each
        particle.
        """
        center = data.get_field_parameter('center')
        pos, vel, normal, bv = get_angular_momentum_components(
            ptype, data, spos, svel)
        L, r_vec, v_vec = modify_reference_frame(center, normal, P=pos, V=vel)
        # adding in the unit registry allows us to have a reference to the dataset
        # and thus we will always get the correct units after applying the cross product.
        return -ucross(r_vec, v_vec, registry=data.ds.unit_registry)

    registry.add_field((ptype, "particle_specific_angular_momentum"),
                       function=_particle_specific_angular_momentum,
                       particle_type=True,
                       units=unit_system["specific_angular_momentum"],
                       validators=[ValidateParameter("center")])

    def _get_spec_ang_mom_comp(axi, ax, _ptype):
        def _particle_specific_angular_momentum_component(field, data):
            return data[_ptype, "particle_specific_angular_momentum"][:, axi]

        def _particle_angular_momentum_component(field, data):
            return data[_ptype, "particle_mass"] * \
                data[ptype, "particle_specific_angular_momentum_%s" % ax]
        return _particle_specific_angular_momentum_component, \
            _particle_angular_momentum_component

    for axi, ax in enumerate("xyz"):
        f, v = _get_spec_ang_mom_comp(axi, ax, ptype)
        registry.add_field(
            (ptype, "particle_specific_angular_momentum_%s" % ax),
            particle_type=True,
            function=f,
            units=unit_system["specific_angular_momentum"],
            validators=[ValidateParameter("center")])
        registry.add_field((ptype, "particle_angular_momentum_%s" % ax),
                           function=v,
                           units=unit_system["angular_momentum"],
                           particle_type=True,
                           validators=[ValidateParameter('center')])

    def _particle_angular_momentum(field, data):
        am = data[ptype, "particle_mass"] * data[
            ptype, "particle_specific_angular_momentum"].T
        return am.T

    registry.add_field((ptype, "particle_angular_momentum"),
                       function=_particle_angular_momentum,
                       particle_type=True,
                       units=unit_system["angular_momentum"],
                       validators=[ValidateParameter("center")])

    create_magnitude_field(registry,
                           "particle_angular_momentum",
                           unit_system["angular_momentum"],
                           ftype=ptype,
                           particle_type=True)

    def _particle_radius(field, data):
        """The spherical radius component of the particle positions

        Relative to the coordinate system defined by the *normal* vector,
        and *center* field parameters.
        """
        return get_radius(data, "particle_position_")

    registry.add_field((ptype, "particle_radius"),
                       function=_particle_radius,
                       units=unit_system["length"],
                       particle_type=True,
                       validators=[ValidateParameter("center")])

    def _particle_position_relative(field, data):
        """The cartesian particle positions in a rotated reference frame

        Relative to the coordinate system defined by the *normal* vector and
        *center* field parameters.

        Note that the orientation of the x and y axes are arbitrary.
        """
        normal = data.get_field_parameter('normal')
        center = data.get_field_parameter('center')
        pos = data.ds.arr([data[ptype, spos % ax] for ax in "xyz"]).T
        L, pos = modify_reference_frame(center, normal, P=pos)
        return pos

    registry.add_field(
        (ptype, "particle_position_relative"),
        function=_particle_position_relative,
        particle_type=True,
        units=unit_system["length"],
        validators=[ValidateParameter("normal"),
                    ValidateParameter("center")])

    def _particle_velocity_relative(field, data):
        """The vector particle velocities in an arbitrary coordinate system

        Relative to the coordinate system defined by the *normal* vector,
        *bulk_velocity* vector and *center* field parameters.

        Note that the orientation of the x and y axes are arbitrary.
        """
        normal = data.get_field_parameter('normal')
        center = data.get_field_parameter('center')
        bv = data.get_field_parameter("bulk_velocity")
        vel = data.ds.arr([
            data[ptype, svel % ax] - bv[iax] for iax, ax in enumerate("xyz")
        ]).T
        L, vel = modify_reference_frame(center, normal, V=vel)
        return vel

    registry.add_field(
        (ptype, "particle_velocity_relative"),
        function=_particle_velocity_relative,
        particle_type=True,
        units=unit_system["velocity"],
        validators=[ValidateParameter("normal"),
                    ValidateParameter("center")])

    def _get_coord_funcs_relative(axi, _ptype):
        def _particle_pos_rel(field, data):
            return data[_ptype, "particle_position_relative"][:, axi]

        def _particle_vel_rel(field, data):
            return data[_ptype, "particle_velocity_relative"][:, axi]

        return _particle_vel_rel, _particle_pos_rel

    for axi, ax in enumerate("xyz"):
        v, p = _get_coord_funcs_relative(axi, ptype)
        registry.add_field((ptype, "particle_velocity_relative_%s" % ax),
                           particle_type=True,
                           function=v,
                           units="code_velocity")
        registry.add_field((ptype, "particle_position_relative_%s" % ax),
                           particle_type=True,
                           function=p,
                           units="code_length")

    # this is just particle radius but we add it with an alias for the sake of
    # consistent naming
    registry.add_field(
        (ptype, "particle_position_spherical_radius"),
        function=_particle_radius,
        particle_type=True,
        units=unit_system["length"],
        validators=[ValidateParameter("normal"),
                    ValidateParameter("center")])

    def _particle_spherical_position_radius(field, data):
        """This field is deprecated and will be removed in a future release"""
        return data[ptype, 'particle_position_spherical_radius']

    registry.add_field(
        (ptype, "particle_spherical_position_radius"),
        function=_particle_spherical_position_radius,
        particle_type=True,
        units=unit_system["length"],
        validators=[ValidateParameter("normal"),
                    ValidateParameter("center")])

    def _particle_position_spherical_theta(field, data):
        """The spherical theta coordinate of the particle positions.

        Relative to the coordinate system defined by the *normal* vector
        and *center* field parameters.
        """
        normal = data.get_field_parameter("normal")
        center = data.get_field_parameter("center")
        pos = data.ds.arr([data[ptype, spos % ax] for ax in "xyz"])
        pos = pos - np.reshape(center, (3, 1))
        return data.ds.arr(get_sph_theta(pos, normal), "")

    registry.add_field(
        (ptype, "particle_position_spherical_theta"),
        function=_particle_position_spherical_theta,
        particle_type=True,
        units="",
        validators=[ValidateParameter("center"),
                    ValidateParameter("normal")])

    def _particle_spherical_position_theta(field, data):
        """This field is deprecated and will be removed in a future release"""
        return data[ptype, 'particle_position_spherical_theta']

    registry.add_field(
        (ptype, "particle_spherical_position_theta"),
        function=_particle_spherical_position_theta,
        particle_type=True,
        units="",
        validators=[ValidateParameter("normal"),
                    ValidateParameter("center")])

    def _particle_position_spherical_phi(field, data):
        """The spherical phi component of the particle positions

        Relative to the coordinate system defined by the *normal* vector
        and *center* field parameters.
        """
        normal = data.get_field_parameter("normal")
        center = data.get_field_parameter("center")
        pos = data.ds.arr([data[ptype, spos % ax] for ax in "xyz"])
        pos = pos - np.reshape(center, (3, 1))
        return data.ds.arr(get_sph_phi(pos, normal), "")

    registry.add_field(
        (ptype, "particle_position_spherical_phi"),
        function=_particle_position_spherical_phi,
        particle_type=True,
        units="",
        validators=[ValidateParameter("normal"),
                    ValidateParameter("center")])

    def _particle_spherical_position_phi(field, data):
        """This field is deprecated and will be removed in a future release"""
        return data[ptype, 'particle_position_spherical_phi']

    registry.add_field(
        (ptype, "particle_spherical_position_phi"),
        function=_particle_spherical_position_phi,
        particle_type=True,
        units="",
        validators=[ValidateParameter("center"),
                    ValidateParameter("normal")])

    def _particle_velocity_spherical_radius(field, data):
        """The spherical radius component of the particle velocities in an
         arbitrary coordinate system

        Relative to the coordinate system defined by the *normal* vector,
        *bulk_velocity* vector and *center* field parameters.
        """
        normal = data.get_field_parameter('normal')
        center = data.get_field_parameter('center')
        bv = data.get_field_parameter("bulk_velocity")
        pos = data.ds.arr([data[ptype, spos % ax] for ax in "xyz"])
        vel = data.ds.arr([data[ptype, svel % ax] for ax in "xyz"])
        pos = pos - np.reshape(center, (3, 1))
        vel = vel - np.reshape(bv, (3, 1))
        theta = get_sph_theta(pos, normal)
        phi = get_sph_phi(pos, normal)
        sphr = get_sph_r_component(vel, theta, phi, normal)
        return sphr

    registry.add_field(
        (ptype, "particle_velocity_spherical_radius"),
        function=_particle_velocity_spherical_radius,
        particle_type=True,
        units=unit_system["velocity"],
        validators=[ValidateParameter("normal"),
                    ValidateParameter("center")])

    def _particle_spherical_velocity_radius(field, data):
        """This field is deprecated and will be removed in a future release"""
        return data[ptype, 'particle_velocity_spherical_radius']

    registry.add_field(
        (ptype, "particle_spherical_velocity_radius"),
        function=_particle_spherical_velocity_radius,
        particle_type=True,
        units=unit_system["velocity"],
        validators=[ValidateParameter("normal"),
                    ValidateParameter("center")])

    # particel_velocity_spherical_radius is simply aliased to
    # "particle_radial_velocity" for convenience
    registry.add_field(
        (ptype, "particle_radial_velocity"),
        function=_particle_spherical_velocity_radius,
        particle_type=True,
        units=unit_system["velocity"],
        validators=[ValidateParameter("normal"),
                    ValidateParameter("center")])

    def _particle_velocity_spherical_theta(field, data):
        """The spherical theta component of the particle velocities in an
         arbitrary coordinate system

        Relative to the coordinate system defined by the *normal* vector,
        *bulk_velocity* vector and *center* field parameters.
        """
        normal = data.get_field_parameter('normal')
        center = data.get_field_parameter('center')
        bv = data.get_field_parameter("bulk_velocity")
        pos = data.ds.arr([data[ptype, spos % ax] for ax in "xyz"])
        vel = data.ds.arr([data[ptype, svel % ax] for ax in "xyz"])
        pos = pos - np.reshape(center, (3, 1))
        vel = vel - np.reshape(bv, (3, 1))
        theta = get_sph_theta(pos, normal)
        phi = get_sph_phi(pos, normal)
        spht = get_sph_theta_component(vel, theta, phi, normal)
        return spht

    registry.add_field(
        (ptype, "particle_velocity_spherical_theta"),
        function=_particle_velocity_spherical_theta,
        particle_type=True,
        units=unit_system["velocity"],
        validators=[ValidateParameter("normal"),
                    ValidateParameter("center")])

    def _particle_spherical_velocity_theta(field, data):
        """This field is deprecated and will be removed in a future release"""
        return data[ptype, 'particle_velocity_spherical_theta']

    registry.add_field(
        (ptype, "particle_spherical_velocity_theta"),
        function=_particle_spherical_velocity_theta,
        particle_type=True,
        units=unit_system["velocity"],
        validators=[ValidateParameter("normal"),
                    ValidateParameter("center")])

    def _particle_velocity_spherical_phi(field, data):
        """The spherical phi component of the particle velocities

        Relative to the coordinate system defined by the *normal* vector,
        *bulk_velocity* vector and *center* field parameters.
        """
        normal = data.get_field_parameter('normal')
        center = data.get_field_parameter('center')
        bv = data.get_field_parameter("bulk_velocity")
        pos = data.ds.arr([data[ptype, spos % ax] for ax in "xyz"])
        vel = data.ds.arr([data[ptype, svel % ax] for ax in "xyz"])
        phi = get_sph_phi(pos, normal)
        pos = pos - np.reshape(center, (3, 1))
        vel = vel - np.reshape(bv, (3, 1))
        sphp = get_sph_phi_component(vel, phi, normal)
        return sphp

    registry.add_field(
        (ptype, "particle_velocity_spherical_phi"),
        function=_particle_velocity_spherical_phi,
        particle_type=True,
        units=unit_system["velocity"],
        validators=[ValidateParameter("normal"),
                    ValidateParameter("center")])

    def _particle_spherical_velocity_phi(field, data):
        """This field is deprecated and will be removed in a future release"""
        return data[ptype, 'particle_spherical_velocity_theta']

    registry.add_field(
        (ptype, "particle_spherical_velocity_phi"),
        function=_particle_spherical_velocity_phi,
        particle_type=True,
        units=unit_system["velocity"],
        validators=[ValidateParameter("normal"),
                    ValidateParameter("center")])

    def _particle_position_cylindrical_radius(field, data):
        """The cylindrical radius component of the particle positions

        Relative to the coordinate system defined by the *normal* vector
        and *center* field parameters.
        """
        normal = data.get_field_parameter("normal")
        center = data.get_field_parameter('center')
        pos = data.ds.arr([data[ptype, spos % ax] for ax in "xyz"])
        pos = pos - np.reshape(center, (3, 1))
        return data.ds.arr(get_cyl_r(pos, normal), 'code_length')

    registry.add_field(
        (ptype, "particle_position_cylindrical_radius"),
        function=_particle_position_cylindrical_radius,
        units=unit_system["length"],
        particle_type=True,
        validators=[ValidateParameter("normal"),
                    ValidateParameter("center")])

    def _particle_position_cylindrical_theta(field, data):
        """The cylindrical theta component of the particle positions

        Relative to the coordinate system defined by the *normal* vector
        and *center* field parameters.
        """
        normal = data.get_field_parameter("normal")
        center = data.get_field_parameter('center')
        pos = data.ds.arr([data[ptype, spos % ax] for ax in "xyz"])
        pos = pos - np.reshape(center, (3, 1))
        return data.ds.arr(get_cyl_theta(pos, normal), "")

    registry.add_field(
        (ptype, "particle_position_cylindrical_theta"),
        function=_particle_position_cylindrical_theta,
        particle_type=True,
        units="",
        validators=[ValidateParameter("center"),
                    ValidateParameter("normal")])

    def _particle_position_cylindrical_z(field, data):
        """The cylindrical z component of the particle positions

        Relative to the coordinate system defined by the *normal* vector
        and *center* field parameters.
        """
        normal = data.get_field_parameter("normal")
        center = data.get_field_parameter('center')
        pos = data.ds.arr([data[ptype, spos % ax] for ax in "xyz"])
        pos = pos - np.reshape(center, (3, 1))
        return data.ds.arr(get_cyl_z(pos, normal), 'code_length')

    registry.add_field(
        (ptype, "particle_position_cylindrical_z"),
        function=_particle_position_cylindrical_z,
        units=unit_system["length"],
        particle_type=True,
        validators=[ValidateParameter("normal"),
                    ValidateParameter("center")])

    def _particle_velocity_cylindrical_radius(field, data):
        """The cylindrical radius component of the particle velocities

        Relative to the coordinate system defined by the *normal* vector,
        *bulk_velocity* vector and *center* field parameters.
        """
        normal = data.get_field_parameter('normal')
        center = data.get_field_parameter('center')
        bv = data.get_field_parameter("bulk_velocity")
        pos = data.ds.arr([data[ptype, spos % ax] for ax in "xyz"])
        vel = data.ds.arr([data[ptype, svel % ax] for ax in "xyz"])
        pos = pos - np.reshape(center, (3, 1))
        vel = vel - np.reshape(bv, (3, 1))
        theta = get_cyl_theta(pos, normal)
        cylr = get_cyl_r_component(vel, theta, normal)
        return cylr

    registry.add_field(
        (ptype, "particle_velocity_cylindrical_radius"),
        function=_particle_velocity_cylindrical_radius,
        particle_type=True,
        units=unit_system["velocity"],
        validators=[ValidateParameter("normal"),
                    ValidateParameter("center")])

    def _particle_velocity_cylindrical_theta(field, data):
        """The cylindrical theta component of the particle velocities

        Relative to the coordinate system defined by the *normal* vector,
        *bulk_velocity* vector and *center* field parameters.
        """
        normal = data.get_field_parameter('normal')
        center = data.get_field_parameter('center')
        bv = data.get_field_parameter("bulk_velocity")
        pos = data.ds.arr([data[ptype, spos % ax] for ax in "xyz"])
        vel = data.ds.arr([data[ptype, svel % ax] for ax in "xyz"])
        pos = pos - np.reshape(center, (3, 1))
        vel = vel - np.reshape(bv, (3, 1))
        theta = get_cyl_theta(pos, normal)
        cylt = get_cyl_theta_component(vel, theta, normal)
        return cylt

    registry.add_field(
        (ptype, "particle_velocity_cylindrical_theta"),
        function=_particle_velocity_cylindrical_theta,
        particle_type=True,
        units=unit_system["velocity"],
        validators=[ValidateParameter("normal"),
                    ValidateParameter("center")])

    def _particle_cylindrical_velocity_theta(field, data):
        """This field is deprecated and will be removed in a future release"""
        return data[ptype, 'particle_velocity_cylindrical_theta']

    registry.add_field(
        (ptype, "particle_cylindrical_velocity_theta"),
        function=_particle_cylindrical_velocity_theta,
        particle_type=True,
        units="cm/s",
        validators=[ValidateParameter("normal"),
                    ValidateParameter("center")])

    def _particle_velocity_cylindrical_z(field, data):
        """The cylindrical z component of the particle velocities

        Relative to the coordinate system defined by the *normal* vector,
        *bulk_velocity* vector and *center* field parameters.
        """
        normal = data.get_field_parameter('normal')
        center = data.get_field_parameter('center')
        bv = data.get_field_parameter("bulk_velocity")
        pos = data.ds.arr([data[ptype, spos % ax] for ax in "xyz"])
        vel = data.ds.arr([data[ptype, svel % ax] for ax in "xyz"])
        pos = pos - np.reshape(center, (3, 1))
        vel = vel - np.reshape(bv, (3, 1))
        cylz = get_cyl_z_component(vel, normal)
        return cylz

    registry.add_field(
        (ptype, "particle_velocity_cylindrical_z"),
        function=_particle_velocity_cylindrical_z,
        particle_type=True,
        units=unit_system["velocity"],
        validators=[ValidateParameter("normal"),
                    ValidateParameter("center")])

    def _particle_cylindrical_velocity_z(field, data):
        """This field is deprecated and will be removed in a future release"""
        return data[ptype, "particle_velocity_cylindrical_z"]

    registry.add_field(
        (ptype, "particle_cylindrical_velocity_z"),
        function=_particle_cylindrical_velocity_z,
        particle_type=True,
        units=unit_system["velocity"],
        validators=[ValidateParameter("normal"),
                    ValidateParameter("center")])
示例#17
0
    mass = data[('particle_mass')].in_units('Msun')
    age = np.array(data[('age')].in_units('Myr'))
    tdyn = np.array(data[('dynamical_time')].in_units('Myr'))

    T = (age) / tdyn
    T[np.where(T > 100)] = 100
    f = (1 - fej * (1 - (1 + T) * np.exp(-T)))
    mass = mass / f
    return mass


yt.add_field("Disk_H",
             function=_Disk_H,
             units="pc",
             take_log=False,
             validators=[ValidateParameter('center')])
yt.add_field("Disk_Radius",
             function=_Disk_Radius,
             units="cm",
             take_log=False,
             validators=[ValidateParameter('center')])
yt.add_field(("gas", "vz_squared"), function=_vz_squared, units="km**2/s**2")
yt.add_field(("gas", "vz"), function=_vz, units="km/s")
yt.add_field("sound_speed", function=_sound_speed, units=r"km/s")
yt.add_field("sound_speed_rep", function=_sound_speed_rep, units=r"s/km")
yt.add_field("sound_speed_2", function=_sound_speed_2, units=r"km**2/s**2")
yt.add_field("sound_speed_rep_2",
             function=_sound_speed_rep_2,
             units=r"s**2/km**2")
yt.add_field(("gas", "px"), function=_px, units="g/s/cm**2")
yt.add_field(("gas", "py"), function=_py, units="g/s/cm**2")