How to use the yt.units.unit_object.Unit function in yt

To help you get started, we’ve selected a few yt examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github yt-project / unyt / tests / test_unit_systems.py View on Github external
def test_unit_systems():
    goofy_unit_system = UnitSystem("goofy", "ly", "lbm", "hr", temperature_unit="R",
                                   angle_unit="arcsec", current_mks_unit="mA")
    assert goofy_unit_system["temperature"] == Unit("R")
    assert goofy_unit_system[dimensions.solid_angle] == Unit("arcsec**2")
    assert goofy_unit_system["energy"] == Unit("lbm*ly**2/hr**2")
    goofy_unit_system["energy"] = "eV"
    assert goofy_unit_system["energy"] == Unit("eV")
    assert goofy_unit_system["magnetic_field_mks"] == Unit("lbm/(hr**2*mA)")
    assert "goofy" in unit_system_registry
github yt-project / unyt / tests / test_units.py View on Github external
def test_create_from_string():
    """
    Create units with strings and check attributes.

    """

    u1 = Unit("g * cm**2 * s**-2")
    assert_true(u1.dimensions == energy)
    assert_true(u1.base_value == 1.0)

    # make sure order doesn't matter
    u2 = Unit("cm**2 * s**-2 * g")
    assert_true(u2.dimensions == energy)
    assert_true(u2.base_value == 1.0)

    # Test rationals
    u3 = Unit("g**0.5 * cm**-0.5 * s**-1")
    assert_true(u3.dimensions == magnetic_field)
    assert_true(u3.base_value == 1.0)

    # sqrt functions
    u4 = Unit("sqrt(g)/sqrt(cm)/s")
    assert_true(u4.dimensions == magnetic_field)
    assert_true(u4.base_value == 1.0)

    # commutative sqrt function
    u5 = Unit("sqrt(g/cm)/s")
    assert_true(u5.dimensions == magnetic_field)
github yt-project / unyt / tests / test_units.py View on Github external
def test_is_code_unit():
    ds = fake_random_ds(64, nprocs=1)
    u1 = Unit('code_mass', registry=ds.unit_registry)
    u2 = Unit('code_mass/code_length', registry=ds.unit_registry)
    u3 = Unit('code_velocity*code_mass**2', registry=ds.unit_registry)
    u4 = Unit('code_time*code_mass**0.5', registry=ds.unit_registry)
    u5 = Unit('code_mass*g', registry=ds.unit_registry)
    u6 = Unit('g/cm**3')

    assert_true(u1.is_code_unit)
    assert_true(u2.is_code_unit)
    assert_true(u3.is_code_unit)
    assert_true(u4.is_code_unit)
    assert_true(not u5.is_code_unit)
    assert_true(not u6.is_code_unit)
github yt-project / unyt / tests / test_units.py View on Github external
def test_division():
    """
    Divide two units.

    """
    pc_cgs = cm_per_pc
    km_cgs = cm_per_km

    # Create symbols
    pc_sym = Symbol("pc", positive=True)
    km_sym = Symbol("km", positive=True)
    s_sym = Symbol("s", positive=True)

    # Create units
    u1 = Unit("pc")
    u2 = Unit("km * s")

    u3 = u1 / u2

    assert_true(u3.expr == pc_sym / (km_sym * s_sym))
    assert_allclose_units(u3.base_value, pc_cgs / km_cgs, 1e-12)
    assert_true(u3.dimensions == 1 / time)
github yt-project / yt / yt / visualization / plot_container.py View on Github external
cm = Unit('cm').expr
            if str(un).endswith('cm') and cm not in un_unit.expr.atoms():
                comoving = True
                un = un[:-2]
            # no length units besides code_length end in h so this is safe
            if h_power == -1:
                hinv = True
            elif h_power != 0:
                # It doesn't make sense to scale a position by anything
                # other than h**-1
                raise RuntimeError
            if un not in ['1', 'u', 'unitary']:
                if un in formatted_length_unit_names:
                    un = formatted_length_unit_names[un]
                else:
                    un = Unit(un, registry=self.ds.unit_registry)
                    un = un.latex_representation()
                    if hinv:
                        un = un + '\,h^{-1}'
                    if comoving:
                        un = un + '\,(1+z)^{-1}'
                    pp = un[0]
                    if pp in latex_prefixes:
                        symbol_wo_prefix = un[1:]
                        if symbol_wo_prefix in prefixable_units:
                            un = un.replace(
                                pp, "{"+latex_prefixes[pp]+"}", 1)
                axes_unit_labels[i] = '\ \ ('+un+')'
        return axes_unit_labels
github yt-project / yt / yt / units / unit_object.py View on Github external
dimensions=self.dimensions, registry=self.registry)
        if unit_system == "cgs":
            if current_mks in self.dimensions.free_symbols:
                raise YTUnitsNotReducible(self, "cgs")
            return yt_base_unit
        else:
            if hasattr(unit_system, "unit_registry"):
                unit_system = unit_system.unit_registry.unit_system_id
            elif unit_system == "code":
                unit_system = self.registry.unit_system_id
            unit_system = unit_system_registry[str(unit_system)]
            units_string = _get_system_unit_string(self.dimensions, unit_system.base_units)
            u = Unit(units_string, registry=self.registry)
            base_value = get_conversion_factor(self, yt_base_unit)[0]
            base_value /= get_conversion_factor(self, u)[0]
            return Unit(units_string, base_value=base_value,
                        dimensions=self.dimensions, registry=self.registry)
github yt-project / yt / yt / data_objects / profiles.py View on Github external
def _sanitize_min_max_units(amin, amax, finfo, registry):
    # returns a copy of amin and amax, converted to finfo's output units
    umin = getattr(amin, 'units', None)
    umax = getattr(amax, 'units', None)
    if umin is None:
        umin = Unit(finfo.output_units, registry=registry)
        rmin = YTQuantity(amin, umin)
    else:
        rmin = amin.in_units(finfo.output_units)
    if umax is None:
        umax = Unit(finfo.output_units, registry=registry)
        rmax = YTQuantity(amax, umax)
    else:
        rmax = amax.in_units(finfo.output_units)
    return rmin, rmax
github yt-project / yt / yt / visualization / volume_rendering / off_axis_projection.py View on Github external
bounds,
                    center.to('code_length').d,
                    width.to('code_length').d,
                    chunk[item].in_units(ounits),
                    buf,
                    normal_vector,
                    north)

            # Assure that the path length unit is in the default length units
            # for the dataset by scaling the units of the smoothing length
            path_length_unit = data_source.ds._get_field_info((ptype, 'smoothing_length')).units
            path_length_unit = Unit(path_length_unit, registry=data_source.ds.unit_registry)
            default_path_length_unit = data_source.ds.unit_system['length']
            buf *= data_source.ds.quan(1, path_length_unit).in_units(default_path_length_unit)
            item_unit = data_source.ds._get_field_info(item).units
            item_unit = Unit(item_unit, registry=data_source.ds.unit_registry)
            funits = item_unit * default_path_length_unit

        else:
            # if there is a weight field, take two projections:
            # one of field*weight, the other of just weight, and divide them
            weight_buff = np.zeros((resolution[0], resolution[1]), dtype='float64')
            wounits = data_source.ds.field_info[weight].output_units

            for chunk in data_source.chunks([], 'io'):
                off_axis_projection_SPH(
                    chunk[ptype, "particle_position_x"].to('code_length').d,
                    chunk[ptype, "particle_position_y"].to('code_length').d,
                    chunk[ptype, "particle_position_z"].to('code_length').d,
                    chunk[ptype, "particle_mass"].to('code_mass').d,
                    chunk[ptype, "density"].to('code_density').d,
                    chunk[ptype, "smoothing_length"].to('code_length').d,
github yt-project / yt / yt / units / yt_array.py View on Github external
Parameters
        ----------
        unit : string
            The unit that you wish to convert to.
        equiv : string
            The equivalence you wish to use. To see which equivalencies are
            supported for this unitful quantity, try the
            :meth:`list_equivalencies` method.

        Examples
        --------
        >>> a = yt.YTArray(1.0e7,"K")
        >>> a.to_equivalent("keV", "thermal")
        """
        conv_unit = Unit(unit, registry=self.units.registry)
        if self.units.same_dimensions_as(conv_unit):
            return self.in_units(conv_unit)
        this_equiv = equivalence_registry[equiv]()
        oneway_or_equivalent = (
            conv_unit.has_equivalent(equiv) or this_equiv._one_way)
        if self.has_equivalent(equiv) and oneway_or_equivalent:
            new_arr = this_equiv.convert(
                self, conv_unit.dimensions, **kwargs)
            if isinstance(new_arr, tuple):
                try:
                    return type(self)(new_arr[0], new_arr[1]).in_units(unit)
                except YTUnitConversionError:
                    raise YTInvalidUnitEquivalence(equiv, self.units, unit)
            else:
                return new_arr.in_units(unit)
        else:
github yt-project / yt / yt / units / yt_array.py View on Github external
super(YTArray, self).__setstate__(state[1:])
        try:
            unit, lut = state[0]
        except TypeError:
            # this case happens when we try to load an old pickle file
            # created before we serialized the unit symbol lookup table
            # into the pickle file
            unit, lut = str(state[0]), default_unit_symbol_lut.copy()
        # need to fix up the lut if the pickle was saved prior to PR #1728
        # when the pickle format changed
        if len(lut['m']) == 2:
            lut.update(default_unit_symbol_lut)
            for k, v in [(k, v) for k, v in lut.items() if len(v) == 2]:
                lut[k] = v + (0.0, r'\rm{' + k.replace('_', '\ ') + '}')
        registry = UnitRegistry(lut=lut, add_default_symbols=False)
        self.units = Unit(unit, registry=registry)