def test_issue44(self): x = 4.0 * ureg.dimensionless np.sqrt(x) helpers.assert_quantity_almost_equal( np.sqrt([4.0] * ureg.dimensionless), [2.0] * ureg.dimensionless) helpers.assert_quantity_almost_equal(np.sqrt(4.0 * ureg.dimensionless), 2.0 * ureg.dimensionless)
def test_exponentiation(self, input_tuple, expected): self.ureg.default_as_delta = False in1, in2 = input_tuple if type(in1) is tuple and type(in2) is tuple: in1, in2 = self.QP_(*in1), self.QP_(*in2) elif not type(in1) is tuple and type(in2) is tuple: in1, in2 = self.NON_INT_TYPE(in1), self.QP_(*in2) else: in1, in2 = self.QP_(*in1), self.NON_INT_TYPE(in2) input_tuple = in1, in2 expected_copy = expected[:] for i, mode in enumerate([False, True]): self.ureg.autoconvert_offset_to_baseunit = mode if expected_copy[i] == "error": with pytest.raises( (OffsetUnitCalculusError, DimensionalityError)): op.pow(in1, in2) else: if type(expected_copy[i]) is tuple: expected = self.QP_(*expected_copy[i]) assert op.pow(in1, in2).units == expected.units else: expected = expected_copy[i] helpers.assert_quantity_almost_equal(op.pow(in1, in2), expected)
def test_volts(self): from pint.util import infer_base_unit r = Q(1, "V") * Q(1, "mV") / Q(1, "kV") b = infer_base_unit(r) assert b == Q(1, "V").units helpers.assert_quantity_almost_equal(r, Q(1, "uV"))
def test_propagate_product(self): v1, u1 = self.Q_(8.0, "s"), self.Q_(0.7, "s") v2, u2 = self.Q_(5.0, "s"), self.Q_(0.6, "s") v2, u3 = self.Q_(-5.0, "s"), self.Q_(0.6, "s") m1 = v1.plus_minus(u1) m2 = v2.plus_minus(u2) m3 = v2.plus_minus(u3) m4 = (2.3 * self.ureg.meter).plus_minus(0.1) m5 = (1.4 * self.ureg.meter).plus_minus(0.2) for ml, mr in zip((m1, m1, m1, m3, m4), (m1, m2, m3, m3, m5)): r = ml * mr helpers.assert_quantity_almost_equal( r.value.magnitude, ml.value.magnitude * mr.value.magnitude ) assert r.value.units == ml.value.units * mr.value.units for ml, mr in zip((m1, m1, m1, m3, m4), (m1, m2, m3, m3, m5)): r = ml / mr helpers.assert_quantity_almost_equal( r.value.magnitude, ml.value.magnitude / mr.value.magnitude ) assert r.value.units == ml.value.units / mr.value.units
def _test_inplace(self, operator, value1, value2, expected_result, unit=None): if isinstance(value1, str): value1 = self.Q_(value1) if isinstance(value2, str): value2 = self.Q_(value2) if isinstance(expected_result, str): expected_result = self.Q_(expected_result) if unit is not None: value1 = value1 * unit value2 = value2 * unit expected_result = expected_result * unit value1 = copy.copy(value1) value2 = copy.copy(value2) id1 = id(value1) id2 = id(value2) value1 = operator(value1, value2) value2_cpy = copy.copy(value2) helpers.assert_quantity_almost_equal(value1, expected_result) assert id1 == id(value1) helpers.assert_quantity_almost_equal(value2, value2_cpy) assert id2 == id(value2)
def test_spectroscopy(self): ureg = self.ureg eq = (532.0 * ureg.nm, 563.5 * ureg.terahertz, 2.33053 * ureg.eV) with ureg.context("sp"): from pint.util import find_shortest_path for a, b in itertools.product(eq, eq): for x in range(2): if x == 1: a = a.to_base_units() b = b.to_base_units() da, db = Context.__keytransform__(a.dimensionality, b.dimensionality) p = find_shortest_path(ureg._active_ctx.graph, da, db) assert p msg = "{} <-> {}".format(a, b) # assertAlmostEqualRelError converts second to first helpers.assert_quantity_almost_equal(b, a, rtol=0.01, msg=msg) for a, b in itertools.product(eq, eq): helpers.assert_quantity_almost_equal(a.to(b.units, "sp"), b, rtol=0.01)
def test_issue45(self): import math helpers.assert_quantity_almost_equal( math.sqrt(4 * ureg.m / ureg.cm), math.sqrt(4 * 100) ) helpers.assert_quantity_almost_equal(float(ureg.V / ureg.mV), 1000.0)
def _test1(self, func, ok_with, raise_with=(), output_units="same", results=None, rtol=1e-6): """Test function that takes a single argument and returns Quantity. Parameters ---------- func : function callable. ok_with : iterables of values that work fine. raise_with : iterables of values that raise exceptions. (Default value = ()) output_units : units to be used when building results. 'same': ok_with[n].units (default). is float: ok_with[n].units ** output_units. None: no output units, the result should be an ndarray. Other value will be parsed as unit. results : iterable of results. If None, the result will be obtained by applying func to each ok_with value (Default value = None) rtol : relative tolerance. (Default value = 1e-6) Returns ------- """ if results is None: results = [None] * len(ok_with) for x1, res in zip(ok_with, results): err_msg = "At {} with {}".format(func.__name__, x1) if output_units == "same": ou = x1.units elif isinstance(output_units, (int, float)): ou = x1.units**output_units else: ou = output_units qm = func(x1) if res is None: res = func(x1.magnitude) if ou is not None: res = self.Q_(res, ou) helpers.assert_quantity_almost_equal(qm, res, rtol=rtol, msg=err_msg) for x1 in raise_with: with pytest.raises(DimensionalityError): func(x1)
def test_to_compact(self): r = Q(1000000000, "m") * Q(1, "mm") / Q(1, "s") / Q(1, "ms") compact_r = r.to_compact() expected = Q(1000.0, "kilometer**2 / second**2") helpers.assert_quantity_almost_equal(compact_r, expected) r = (Q(1, "m") * Q(1, "mm") / Q(1, "m") / Q(2, "um") * Q(2, "s")).to_compact() helpers.assert_quantity_almost_equal(r, Q(1000, "s"))
def test_pintarray_creation(self): x = ureg.Quantity([1.0, 2.0, 3.0], "m") ys = [ PintArray.from_1darray_quantity(x), PintArray._from_sequence([item for item in x]), ] for y in ys: helpers.assert_quantity_almost_equal(x, y.quantity)
def test_solve(self): A = self.q b = [[3], [7]] * self.ureg.s x = np.linalg.solve(A, b) helpers.assert_quantity_almost_equal(x, self.Q_([[1], [1]], "s / m")) helpers.assert_quantity_almost_equal(np.dot(A, x), b)
def test_issue_88(): q_m = ureg.Quantity([1, 2], "m") a = PintArray(q_m) helpers.assert_quantity_almost_equal(q_m, a.quantity) q_mm = ureg.Quantity([1000, 2000], "mm") b = PintArray(q_mm, "m") helpers.assert_quantity_almost_equal(q_m, b.quantity)
def test_addition_with_scalar(self): a = np.array([0, 1, 2]) b = 10.0 * self.ureg("gram/kilogram") helpers.assert_quantity_almost_equal( a + b, self.Q_([0.01, 1.01, 2.01], self.ureg.dimensionless) ) helpers.assert_quantity_almost_equal( b + a, self.Q_([0.01, 1.01, 2.01], self.ureg.dimensionless) )
def test_issue45b(self): helpers.assert_quantity_almost_equal( np.sin([np.pi / 2] * ureg.m / ureg.m), np.sin([np.pi / 2] * ureg.dimensionless), ) helpers.assert_quantity_almost_equal( np.sin([np.pi / 2] * ureg.cm / ureg.m), np.sin([np.pi / 2] * ureg.dimensionless * 0.01), )
def test_issue85(self): T = 4.0 * ureg.kelvin m = 1.0 * ureg.amu va = 2.0 * ureg.k * T / m va.to_base_units() boltmk = 1.380649e-23 * ureg.J / ureg.K vb = 2.0 * boltmk * T / m helpers.assert_quantity_almost_equal(va.to_base_units(), vb.to_base_units())
def test_issue93(self): x = 5 * ureg.meter assert isinstance(x.magnitude, int) y = 0.1 * ureg.meter assert isinstance(y.magnitude, float) z = 5 * ureg.meter assert isinstance(z.magnitude, int) z += y assert isinstance(z.magnitude, float) helpers.assert_quantity_almost_equal(x + y, 5.1 * ureg.meter) helpers.assert_quantity_almost_equal(z, 5.1 * ureg.meter)
def test_mix_regular_log_units(self): # Test regular-logarithmic mixed definition, such as dB/km or dB/cm # Multiplications and divisions with a mix of Logarithmic Units and regular Units is normally not possible. # The reason is that dB are considered by pint like offset units. # Multiplications and divisions that involve offset units are badly defined, so pint raises an error with pytest.raises(OffsetUnitCalculusError): (-10.0 * self.ureg.dB) / (1 * self.ureg.cm) # However, if the flag autoconvert_offset_to_baseunit=True is given to UnitRegistry, then pint converts the unit to base. # With this flag on multiplications and divisions are now possible: new_reg = UnitRegistry(autoconvert_offset_to_baseunit=True) helpers.assert_quantity_almost_equal(-10 * new_reg.dB / new_reg.cm, 0.1 / new_reg.cm)
def test_multiplication_with_autoconvert(self, input_tuple, expected): self.ureg.autoconvert_offset_to_baseunit = True qin1, qin2 = input_tuple q1, q2 = self.QP_(*qin1), self.QP_(*qin2) input_tuple = q1, q2 if expected == "error": with pytest.raises(OffsetUnitCalculusError): op.mul(q1, q2) else: expected = self.QP_(*expected) assert op.mul(q1, q2).units == expected.units helpers.assert_quantity_almost_equal(op.mul(q1, q2), expected, atol=0.01)
def test_addition(self, input_tuple, expected): self.ureg.autoconvert_offset_to_baseunit = False qin1, qin2 = input_tuple q1, q2 = self.QP_(*qin1), self.QP_(*qin2) # update input tuple with new values to have correct values on failure input_tuple = q1, q2 if expected == "error": with pytest.raises(OffsetUnitCalculusError): op.add(q1, q2) else: expected = self.QP_(*expected) assert op.add(q1, q2).units == expected.units helpers.assert_quantity_almost_equal(op.add(q1, q2), expected, atol="0.01")
def test_op(a_pint, a_pint_array, b_, coerce=True): try: result_pint = op(a_pint, b_) if coerce: # a PintArray is returned from arithmetics, so need the data c_pint_array = op(a_pint_array, b_).quantity else: # a boolean array is returned from comparatives c_pint_array = op(a_pint_array, b_) helpers.assert_quantity_almost_equal(result_pint, c_pint_array) except Exception as caught_exception: with pytest.raises(type(caught_exception)): op(a_pint_array, b)
def test_log_convert(self): # # 1 dB = 1/10 * bel # helpers.assert_quantity_almost_equal(self.Q_(1.0, "dB").to("dimensionless"), self.Q_(1, "bell") / 10) # # Uncomment Bell unit in default_en.txt # ## Test dB to dB units octave - decade # 1 decade = log2(10) octave helpers.assert_quantity_almost_equal( self.Q_(1.0, "decade"), self.Q_(math.log(10, 2), "octave")) # ## Test dB to dB units dBm - dBu # 0 dBm = 1mW = 1e3 uW = 30 dBu helpers.assert_quantity_almost_equal(self.Q_(0.0, "dBm"), self.Q_(29.999999999999996, "dBu"), atol=1e-7)
def test_multiplication_with_scalar(self, input_tuple, expected): self.ureg.default_as_delta = False in1, in2 = input_tuple if type(in1) is tuple: in1, in2 = self.QP_(*in1), self.NON_INT_TYPE(in2) else: in1, in2 = in1, self.QP_(*in2) input_tuple = in1, in2 # update input_tuple for better tracebacks if expected == "error": with pytest.raises(OffsetUnitCalculusError): op.mul(in1, in2) else: expected = self.QP_(*expected) assert op.mul(in1, in2).units == expected.units helpers.assert_quantity_almost_equal(op.mul(in1, in2), expected, atol="0.01")
def test_division_with_scalar(self, input_tuple, expected): self.ureg.default_as_delta = False in1, in2 = input_tuple if type(in1) is tuple: in1, in2 = self.QP_(*in1), self.NON_INT_TYPE(in2) else: in1, in2 = self.NON_INT_TYPE(in1), self.QP_(*in2) input_tuple = in1, in2 # update input_tuple for better tracebacks expected_copy = expected[:] for i, mode in enumerate([False, True]): self.ureg.autoconvert_offset_to_baseunit = mode if expected_copy[i] == "error": with pytest.raises(OffsetUnitCalculusError): op.truediv(in1, in2) else: expected = self.QP_(*expected_copy[i]) assert op.truediv(in1, in2).units == expected.units helpers.assert_quantity_almost_equal(op.truediv(in1, in2), expected)
def test_to_and_from_offset_units(self, input_tuple, expected): src, dst = input_tuple src, dst = UnitsContainer(src), UnitsContainer(dst) value = 10.0 convert = self.ureg.convert if isinstance(expected, str): with pytest.raises(DimensionalityError): convert(value, src, dst) if src != dst: with pytest.raises(DimensionalityError): convert(value, dst, src) else: helpers.assert_quantity_almost_equal( convert(value, src, dst), expected, atol=0.001 ) if src != dst: helpers.assert_quantity_almost_equal( convert(expected, dst, src), value, atol=0.001 )
def test_issues86b(self): ureg = self.ureg T1 = 200.0 * ureg.degC T2 = T1.to(ureg.kelvin) m = 132.9054519 * ureg.amu v1 = 2 * ureg.k * T1 / m v2 = 2 * ureg.k * T2 / m helpers.assert_quantity_almost_equal(v1, v2) helpers.assert_quantity_almost_equal(v1, v2.to_base_units()) helpers.assert_quantity_almost_equal(v1.to_base_units(), v2) helpers.assert_quantity_almost_equal(v1.to_base_units(), v2.to_base_units())
def test_textile(self): ureg = self.ureg qty_direct = 1.331 * ureg.tex with pytest.raises(DimensionalityError): qty_indirect = qty_direct.to("Nm") with ureg.context("textile"): from pint.util import find_shortest_path qty_indirect = qty_direct.to("Nm") a = qty_direct.to_base_units() b = qty_indirect.to_base_units() da, db = Context.__keytransform__(a.dimensionality, b.dimensionality) p = find_shortest_path(ureg._active_ctx.graph, da, db) assert p msg = "{} <-> {}".format(a, b) helpers.assert_quantity_almost_equal(b, a, rtol=0.01, msg=msg) # Check RKM <-> cN/tex conversion helpers.assert_quantity_almost_equal(1 * ureg.RKM, 0.980665 * ureg.cN / ureg.tex) helpers.assert_quantity_almost_equal((1 / 0.980665) * ureg.RKM, 1 * ureg.cN / ureg.tex) assert (round( abs((1 * ureg.RKM).to(ureg.cN / ureg.tex).m - 0.980665), 7) == 0) assert (round( abs((1 * ureg.cN / ureg.tex).to(ureg.RKM).m - 1 / 0.980665), 7) == 0)
def test_non_multiplicative(subtests): ureg = UnitRegistry(""" kelvin = [temperature] fahrenheit = 5 / 9 * kelvin; offset: 255 bogodegrees = 9 * kelvin @context nonmult_to_nonmult fahrenheit = 7 * kelvin; offset: 123 @end @context nonmult_to_mult fahrenheit = 123 * kelvin @end @context mult_to_nonmult bogodegrees = 5 * kelvin; offset: 123 @end """.splitlines()) k = ureg.Quantity(100, "kelvin") with subtests.test("baseline"): helpers.assert_quantity_almost_equal( k.to("fahrenheit").magnitude, (100 - 255) * 9 / 5) helpers.assert_quantity_almost_equal( k.to("bogodegrees").magnitude, 100 / 9) with subtests.test("nonmult_to_nonmult"): with ureg.context("nonmult_to_nonmult"): helpers.assert_quantity_almost_equal( k.to("fahrenheit").magnitude, (100 - 123) / 7) with subtests.test("nonmult_to_mult"): with ureg.context("nonmult_to_mult"): helpers.assert_quantity_almost_equal( k.to("fahrenheit").magnitude, 100 / 123) with subtests.test("mult_to_nonmult"): with ureg.context("mult_to_nonmult"): helpers.assert_quantity_almost_equal( k.to("bogodegrees").magnitude, (100 - 123) / 5)
def test_issue104(self): x = [ureg("1 meter"), ureg("1 meter"), ureg("1 meter")] y = [ureg("1 meter")] * 3 def summer(values): if not values: return 0 total = values[0] for v in values[1:]: total += v return total helpers.assert_quantity_almost_equal(summer(x), ureg.Quantity(3, "meter")) helpers.assert_quantity_almost_equal(x[0], ureg.Quantity(1, "meter")) helpers.assert_quantity_almost_equal(summer(y), ureg.Quantity(3, "meter")) helpers.assert_quantity_almost_equal(y[0], ureg.Quantity(1, "meter"))
def test_convert(self): helpers.assert_quantity_almost_equal( self.Q_("2 inch").to("meter"), self.Q_( self.NON_INT_TYPE("2") * self.NON_INT_TYPE("0.0254"), "meter"), ) helpers.assert_quantity_almost_equal( self.Q_("2 meter").to("inch"), self.Q_( self.NON_INT_TYPE("2") / self.NON_INT_TYPE("0.0254"), "inch"), ) helpers.assert_quantity_almost_equal( self.Q_("2 sidereal_year").to("second"), self.QP_("63116297.5325", "second")) helpers.assert_quantity_almost_equal( self.Q_("2.54 centimeter/second").to("inch/second"), self.Q_("1 inch/second"), ) assert round(abs(self.Q_("2.54 centimeter").to("inch").magnitude - 1), 7) == 0 assert (round( abs(self.Q_("2 second").to("millisecond").magnitude - 2000), 7) == 0)
def test_to_base_units(self): x = self.Q_("1*inch") helpers.assert_quantity_almost_equal(x.to_base_units(), self.QP_("0.0254", "meter")) x = self.Q_("1*inch*inch") helpers.assert_quantity_almost_equal( x.to_base_units(), self.Q_( self.NON_INT_TYPE("0.0254")**self.NON_INT_TYPE("2.0"), "meter*meter"), ) x = self.Q_("1*inch/minute") helpers.assert_quantity_almost_equal( x.to_base_units(), self.Q_( self.NON_INT_TYPE("0.0254") / self.NON_INT_TYPE("60"), "meter/second"), )