def test_latex_repr(): registry = UnitRegistry() # create a fake comoving unit registry.add( "pccm", registry.lut["pc"][0] / (1 + 2), length, "\\rm{pc}/(1+z)", prefixable=True, ) test_unit = Unit("Mpccm", registry=registry) assert_almost_equal(test_unit.base_value, m_per_mpc / 3) assert_equal(test_unit.latex_repr, r"\rm{Mpc}/(1+z)") test_unit = Unit("cm**-3", base_value=1.0, registry=registry) assert_equal(test_unit.latex_repr, "\\frac{1}{\\rm{cm}^{3}}") test_unit = Unit("m_geom/l_geom**3") assert_equal(test_unit.latex_repr, "\\frac{1}{\\rm{M}_\\odot^{2}}") test_unit = Unit("1e9*cm") assert_equal(test_unit.latex_repr, "1.0 \\times 10^{9}\\ \\rm{cm}") test_unit = Unit("1.0*cm") assert_equal(test_unit.latex_repr, "\\rm{cm}")
def test_create_from_expr(): """ Create units from sympy Exprs and check attributes. """ pc_mks = m_per_pc yr_mks = sec_per_year # Symbol expr s1 = Symbol("pc", positive=True) s2 = Symbol("yr", positive=True) # Mul expr s3 = s1 * s2 # Pow expr s4 = s1**2 * s2**(-1) u1 = Unit(s1) u2 = Unit(s2) u3 = Unit(s3) u4 = Unit(s4) assert u1.expr == s1 assert u2.expr == s2 assert u3.expr == s3 assert u4.expr == s4 assert_allclose_units(u1.base_value, pc_mks, 1e-12) assert_allclose_units(u2.base_value, yr_mks, 1e-12) assert_allclose_units(u3.base_value, pc_mks * yr_mks, 1e-12) assert_allclose_units(u4.base_value, pc_mks**2 / yr_mks, 1e-12) assert u1.dimensions == length assert u2.dimensions == time assert u3.dimensions == length * time assert u4.dimensions == length**2 / time
def test_invalid_operations(): u1 = Unit('cm') u2 = Unit('m') with pytest.raises(InvalidUnitOperation): u1 + u2 with pytest.raises(InvalidUnitOperation): u1 += u2 with pytest.raises(InvalidUnitOperation): 1 + u1 with pytest.raises(InvalidUnitOperation): u1 + 1 with pytest.raises(InvalidUnitOperation): u1 - u2 with pytest.raises(InvalidUnitOperation): u1 -= u2 with pytest.raises(InvalidUnitOperation): 1 - u1 with pytest.raises(InvalidUnitOperation): u1 - 1 with pytest.raises(InvalidUnitOperation): u1 *= u2 with pytest.raises(InvalidUnitOperation): u1 * 'hello!' with pytest.raises(InvalidUnitOperation): u1 /= u2 with pytest.raises(InvalidUnitOperation): u1 / 'hello!'
def test_latex_repr(): registry = UnitRegistry() # create a fake comoving unit registry.add('pccm', registry.lut['pc'][0] / (1 + 2), length, "\\rm{pc}/(1+z)", prefixable=True) test_unit = Unit('Mpccm', registry=registry) assert_almost_equal(test_unit.base_value, m_per_mpc / 3) assert_equal(test_unit.latex_repr, r'\rm{Mpc}/(1+z)') test_unit = Unit('cm**-3', base_value=1.0, registry=registry) assert_equal(test_unit.latex_repr, '\\frac{1}{\\rm{cm}^{3}}') test_unit = Unit('m_geom/l_geom**3') assert_equal(test_unit.latex_repr, '\\frac{1}{M_\\odot^{2}}') test_unit = Unit('1e9*cm') assert_equal(test_unit.latex_repr, '1.0 \\times 10^{9}\\ \\rm{cm}') test_unit = Unit('1.0*cm') assert_equal(test_unit.latex_repr, '\\rm{cm}')
def test_invalid_operations(): u1 = Unit("cm") u2 = Unit("m") with pytest.raises(InvalidUnitOperation): u1 + u2 with pytest.raises(InvalidUnitOperation): u1 += u2 with pytest.raises(InvalidUnitOperation): 1 + u1 with pytest.raises(InvalidUnitOperation): u1 + 1 with pytest.raises(InvalidUnitOperation): u1 - u2 with pytest.raises(InvalidUnitOperation): u1 -= u2 with pytest.raises(InvalidUnitOperation): 1 - u1 with pytest.raises(InvalidUnitOperation): u1 - 1 with pytest.raises(InvalidUnitOperation): u1 *= u2 with pytest.raises(InvalidUnitOperation): u1 * "hello!" with pytest.raises(InvalidUnitOperation): u1 /= u2 with pytest.raises(InvalidUnitOperation): u1 / "hello!"
def test_old_registry_multiple_load(): # See Issue #157 for details reg1 = UnitRegistry() reg1.add("code_length", 1.0, length) reg1.add("code_mass", 1.0, mass) reg1.add("code_time", 1.0, time) reg1.add("code_temperature", 1.0, temperature) UnitSystem( reg1.unit_system_id, "code_length", "code_mass", "code_time", "code_temperature", registry=reg1, ) cm = Unit("code_mass", registry=reg1) cl = Unit("code_length", registry=reg1) (cm / cl).latex_representation() with open(OLD_JSON_PATH) as f: json_data = f.read() reg2 = UnitRegistry.from_json(json_data) UnitSystem( reg2.unit_system_id, "code_length", "code_mass", "code_time", "code_temperature", registry=reg2, )
def test_multiplication(): """ Multiply two units. """ msun_mks = mass_sun_kg pc_mks = m_per_pc # Create symbols msun_sym = Symbol("Msun", positive=True) pc_sym = Symbol("pc", positive=True) s_sym = Symbol("s", positive=True) # Create units u1 = Unit("Msun") u2 = Unit("pc") # Mul operation u3 = u1 * u2 assert u3.expr == msun_sym * pc_sym assert_allclose_units(u3.base_value, msun_mks * pc_mks, 1e-12) assert u3.dimensions == mass * length # Pow and Mul operations u4 = Unit("pc**2") u5 = Unit("Msun * s") u6 = u4 * u5 assert u6.expr == pc_sym**2 * msun_sym * s_sym assert_allclose_units(u6.base_value, pc_mks**2 * msun_mks, 1e-12) assert u6.dimensions == length**2 * mass * time
def test_temperature_offsets(): u1 = Unit('degC') u2 = Unit('degF') with pytest.raises(InvalidUnitOperation): operator.mul(u1, u2) with pytest.raises(InvalidUnitOperation): operator.truediv(u1, u2)
def test_equal_has_same_hash(): a = Unit("m") b = Unit("m") c = Unit("m*s/s") assert a == b assert b == c assert hash(a) == hash(b) assert hash(b) == hash(c)
def test_equality(): """ Check unit equality with different symbols, but same dimensions and base_value. """ u1 = Unit("km * s**-1") u2 = Unit("m * ms**-1") assert u1 == u2
def test_degF(): assert Unit("degree_fahrenheit") == Unit("degF") assert Unit("degree_Fahrenheit") == Unit("degF") assert Unit("Fahrenheit") == Unit("degF") assert Unit("°F") == Unit("degF") a = 1 * Unit("degF") assert str(a) == "1 °F"
def test_degC(): assert Unit("degree_celsius") == Unit("degC") assert Unit("degree_Celsius") == Unit("degC") assert Unit("Celsius") == Unit("degC") assert Unit("°C") == Unit("degC") a = 1 * Unit("degC") assert str(a) == "1 °C"
def test_prefixable_units(): ureg = UnitRegistry() pu = ureg.prefixable_units assert 'm' in pu assert 'pc' in pu assert 'mol' in pu ureg.add('foobar', 1.0, length, prefixable=True) assert 'foobar' in ureg.prefixable_units mfoobar = Unit('mfoobar', registry=ureg) foobar = Unit('foobar', registry=ureg) assert (1 * foobar) / (1 * mfoobar) == 1000
def test_prefixable_units(): ureg = UnitRegistry() pu = ureg.prefixable_units assert "m" in pu assert "pc" in pu assert "mol" in pu ureg.add("foobar", 1.0, length, prefixable=True) assert "foobar" in ureg.prefixable_units mfoobar = Unit("mfoobar", registry=ureg) foobar = Unit("foobar", registry=ureg) assert (1 * foobar) / (1 * mfoobar) == 1000
def __getattr__(self, item): if item in self._cache: return self._cache[item] if hasattr(globals(), item): ret = Unit(globals()[item].expr, registry=self._registry) elif item in self._registry: ret = Unit(item, registry=self._registry) else: raise AttributeError(item) self._cache[item] = ret return ret
def test_bel_neper(): assert Unit("B").dimensions == Unit("Np").dimensions a = 1 * Unit("B") / (np.log(10) / 2) assert_allclose_units(a.to("Np"), 1 * Unit("Np")) a = 2 * Unit("B") b = 20 * Unit("decibel") assert (a == b).all() c = 2 * Unit("Np") d = 20 * Unit("decineper") assert (c == d).all() assert Unit("dB")**1 == Unit("dB")
def test_unit_systems(): goofy_unit_system = UnitSystem( "goofy", "ly", "lbm", "hr", temperature_unit="R", angle_unit="arcsec", current_mks_unit="mA", luminous_intensity_unit="cd") 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
def test_percent(): a = 300 * Unit("percent") b = 3.0 * Unit("dimensionless") c = 300.0 * Unit("%") d = 300.0 * Unit("V*%/V") assert a == b assert str(a) == "300 %" assert repr(a) == "unyt_quantity(300, '%')" assert a == c assert c == d
def __getitem__(self, key): from unyt.unit_object import Unit if isinstance(key, str): key = getattr(dimensions, key) um = self.units_map if key not in um or um[key] is None: if cmks in key.free_symbols and self.units_map[cmks] is None: raise MissingMKSCurrent(self.name) units = _get_system_unit_string(key, self.units_map) self.units_map[key] = parse_unyt_expr(units) return Unit(units, registry=self.registry) return Unit(self.units_map[key], registry=self.registry)
def test_solar_unit_name_alternatives(): import unyt from unyt import Unit # check that m_sun, m_Sun, M_sun, M_Sun, msun, and Msun all work for lower_name_prefix in "mrltz": base_name = lower_name_prefix + "sun" for name_prefix in [lower_name_prefix, lower_name_prefix.upper()]: alternative_names = [name_prefix + suf for suf in ["sun", "_sun", "_Sun"]] for name in alternative_names: assert Unit(name) == Unit(base_name) assert hasattr(unyt, name) # only solar mass units are in physical constants if lower_name_prefix == "m": assert hasattr(unyt.physical_constants, name)
def test_create_fail_on_unknown_symbol(): """ Fail to create unit with unknown symbol, without base_value and dimensions. """ with pytest.raises(UnitParseError): Unit(Symbol("jigawatts"))
def add_symbols(namespace, registry): """Adds the unit symbols from :mod:`unyt.unit_symbols` to a namespace Parameters ---------- namespace : dict The dict to insert unit symbols into. The keys will be string unit names and values will be the corresponding unit objects. registry : :class:`unyt.unit_registry.UnitRegistry` The registry to create units from. Note that if you would like to use a custom unit system, ensure your registry was created using that unit system. Example ------- >>> from unyt.unit_registry import UnitRegistry >>> class MyClass(): ... def __init__(self): ... self.reg = UnitRegistry() ... add_symbols(vars(self), self.reg) >>> foo = MyClass() >>> foo.kilometer km >>> foo.joule J """ from unyt.unit_object import Unit for canonical_name, alt_names in name_alternatives.items(): for alt_name in alt_names: namespace[alt_name] = Unit(canonical_name, registry=registry)
def test_power(): """ Take units to some power. """ from sympy import nsimplify from unyt import dimensionless pc_mks = m_per_pc mK_mks = 1e-3 u1_dims = mass * length**2 * time**-3 * temperature**4 u1 = Unit("kg * pc**2 * s**-3 * mK**4") u2 = u1**2 assert u2.dimensions == u1_dims**2 assert_allclose_units(u2.base_value, (pc_mks**2 * mK_mks**4)**2, 1e-12) u3 = u1**(-1.0 / 3) assert u3.dimensions == nsimplify(u1_dims**(-1.0 / 3)) assert_allclose_units(u3.base_value, (pc_mks**2 * mK_mks**4)**(-1.0 / 3), 1e-12) assert u1**0.0 == dimensionless
def test_create_with_duplicate_dimensions(): """ Create units with overlapping dimensions. Ex: km/Mpc. """ u1 = Unit("J * s**-1") u2 = Unit("km/s/Mpc") km_mks = m_per_km Mpc_mks = m_per_mpc assert u1.base_value == 1 assert u1.dimensions == power assert_allclose_units(u2.base_value, km_mks / Mpc_mks, 1e-12) assert u2.dimensions == rate
def test_creation_from_ytarray(): u1 = Unit(electrostatic_unit) assert_equal(str(u1), 'esu') assert_equal(u1, Unit('esu')) assert_equal(u1, electrostatic_unit.units) u2 = Unit(elementary_charge_cgs) assert_equal(str(u2), '4.8032056e-10*esu') assert_equal(u2, Unit('4.8032056e-10*esu')) assert_equal(u1, elementary_charge_cgs.units) assert_allclose((u1 / u2).base_value, electrostatic_unit / elementary_charge_cgs) with pytest.raises(UnitParseError): Unit([1, 2, 3] * elementary_charge_cgs)
def test_create_fail_on_bad_symbol_type(): """ Fail to create unit with bad symbol type. """ with pytest.raises(UnitParseError): Unit([1]) # something other than Expr and str
def test_create_fail_on_bad_dimensions_type(): """ Fail to create unit with bad dimensions type. """ with pytest.raises(UnitParseError): Unit("a", base_value=1, dimensions="(mass)")
def test_create_fail_on_base_value_type(): """ Fail to create unit with bad base_value type. """ with pytest.raises(UnitParseError): Unit("a", base_value="a", dimensions=(mass / time))
def test_string_representation(): """ Check unit string representation. """ pc = Unit("pc") Myr = Unit("Myr") speed = pc / Myr dimensionless = Unit() assert str(pc) == "pc" assert str(Myr) == "Myr" assert str(speed) == "pc/Myr" assert repr(speed) == "pc/Myr" assert str(dimensionless) == "dimensionless" assert repr(dimensionless) == "(dimensionless)"
def test_create_fail_on_dimensions_content(): """ Fail to create unit with bad dimensions expr. """ a = Symbol("a") with pytest.raises(UnitParseError): Unit("a", base_value=1, dimensions=a)