示例#1
0
 def test_dimension_definition(self):
     x = Definition.from_string('[speed] = [length]/[time]')
     self.assertIsInstance(x, DimensionDefinition)
     self.assertEqual(x.reference,
                      UnitsContainer({
                          '[length]': 1,
                          '[time]': -1
                      }))
示例#2
0
    def test_quantity_creation(self):
        for args in ((4.2, 'meter'), (4.2, UnitsContainer(meter=1)),
                     ('4.2*meter', ), ('4.2/meter**(-1)', ),
                     (self.Q_(4.2, 'meter'), )):
            x = self.Q_(*args)
            self.assertEqual(x.magnitude, 4.2)
            self.assertEqual(x.units, UnitsContainer(meter=1))

        x = self.Q_(4.2, UnitsContainer(length=1))
        y = self.Q_(x)
        self.assertEqual(x.magnitude, y.magnitude)
        self.assertEqual(x.units, y.units)
        self.assertIsNot(x, y)

        x = self.Q_(4.2, None)
        self.assertEqual(x.magnitude, 4.2)
        self.assertEqual(x.units, UnitsContainer())
示例#3
0
    def test_convert(self):

        # Conversions with single units take a different codepath than
        # Conversions with more than one unit.
        src_dst1 = UnitsContainer(meter=1), UnitsContainer(inch=1)
        src_dst2 = UnitsContainer(meter=1,
                                  second=-1), UnitsContainer(inch=1, minute=-1)
        for src, dst in (src_dst1, src_dst2):
            a = np.ones((3, 1))
            ac = np.ones((3, 1))

            q = self.Q_(a, src)
            qac = self.Q_(ac, src).to(dst)
            r = q.to(dst)
            self.assertQuantityAlmostEqual(qac, r)
            self.assertIsNot(r, q)
            self.assertIsNot(r._magnitude, a)
示例#4
0
    def test_issue876(self):
        # Same hash must not imply equality.

        # As an implementation detail of CPython, hash(-1) == hash(-2).
        # This test is useless in potential alternative Python implementations where
        # hash(-1) != hash(-2); one would need to find hash collisions specific for each
        # implementation

        a = UnitsContainer({"[mass]": -1})
        b = UnitsContainer({"[mass]": -2})
        c = UnitsContainer({"[mass]": -3})

        # Guarantee working on alternative Python implementations
        assert (hash(-1) == hash(-2)) == (hash(a) == hash(b))
        assert (hash(-1) == hash(-3)) == (hash(a) == hash(c))
        assert a != b
        assert a != c
示例#5
0
    def test_parse_simple(self):

        a = Context.__keytransform__(UnitsContainer({'[time]': -1}),
                                     UnitsContainer({'[length]': 1}))
        b = Context.__keytransform__(UnitsContainer({'[length]': 1}),
                                     UnitsContainer({'[time]': -1}))

        s = [
            '@context longcontextname', '[length] -> 1 / [time]: c / value',
            '1 / [time] -> [length]: c / value'
        ]

        c = Context.from_lines(s)
        self.assertEqual(c.name, 'longcontextname')
        self.assertEqual(c.aliases, ())
        self.assertEqual(c.defaults, {})
        self.assertEqual(set(c.funcs.keys()), set((a, b)))
        self._test_ctx(c)

        s = [
            '@context longcontextname = lc',
            '[length] <-> 1 / [time]: c / value'
        ]

        c = Context.from_lines(s)
        self.assertEqual(c.name, 'longcontextname')
        self.assertEqual(c.aliases, ('lc', ))
        self.assertEqual(c.defaults, {})
        self.assertEqual(set(c.funcs.keys()), set((a, b)))
        self._test_ctx(c)

        s = [
            '@context longcontextname = lc = lcn',
            '[length] <-> 1 / [time]: c / value'
        ]

        c = Context.from_lines(s)
        self.assertEqual(c.name, 'longcontextname')
        self.assertEqual(c.aliases, (
            'lc',
            'lcn',
        ))
        self.assertEqual(c.defaults, {})
        self.assertEqual(set(c.funcs.keys()), set((a, b)))
        self._test_ctx(c)
示例#6
0
    def test_dimensionless_units(self):
        self.assertAlmostEqual(self.Q_(360, 'degree').to('radian').magnitude, 2 * math.pi)
        self.assertAlmostEqual(self.Q_(2 * math.pi, 'radian'), self.Q_(360, 'degree'))
        self.assertEqual(self.Q_(1, 'radian').dimensionality, UnitsContainer())
        self.assertTrue(self.Q_(1, 'radian').dimensionless)
        self.assertFalse(self.Q_(1, 'radian').unitless)

        self.assertEqual(self.Q_(1, 'meter')/self.Q_(1, 'meter'), 1)
        self.assertEqual((self.Q_(1, 'meter')/self.Q_(1, 'mm')).to(''), 1000)
示例#7
0
文件: test_unit.py 项目: schryer/pint
 def test_to_and_from_offset_units(self, input_tuple, expected):
     src, dst = input_tuple
     src, dst = UnitsContainer(src), UnitsContainer(dst)
     value = 10.
     convert = self.ureg.convert
     if isinstance(expected, string_types):
         self.assertRaises(DimensionalityError, convert, value, src, dst)
         if src != dst:
             self.assertRaises(DimensionalityError, convert, value, dst,
                               src)
     else:
         self.assertQuantityAlmostEqual(convert(value, src, dst),
                                        expected,
                                        atol=0.001)
         if src != dst:
             self.assertQuantityAlmostEqual(convert(expected, dst, src),
                                            value,
                                            atol=0.001)
示例#8
0
def add_sharedargdef_ctxs(ureg):
    a, b = UnitsContainer({'[length]': 1}), UnitsContainer({'[time]': -1})
    d = Context('lc', defaults=dict(n=1))
    assert d.defaults == dict(n=1)

    d.add_transformation(a, b, lambda ureg, x, n: ureg.speed_of_light / x / n)
    d.add_transformation(b, a, lambda ureg, x, n: ureg.speed_of_light / x / n)

    ureg.add_context(d)

    a, b = UnitsContainer({'[length]': 1}), UnitsContainer({'[current]': 1})
    d = Context('ab', defaults=dict(n=0))
    d.add_transformation(a, b,
                         lambda ureg, x, n: ureg.ampere * ureg.meter * n / x)
    d.add_transformation(b, a,
                         lambda ureg, x, n: ureg.ampere * ureg.meter * n / x)

    ureg.add_context(d)
示例#9
0
文件: test_unit.py 项目: schryer/pint
    def test_convert_inplace(self):
        ureg = self.ureg

        # Conversions with single units take a different codepath than
        # Conversions with more than one unit.
        src_dst1 = UnitsContainer(meter=1), UnitsContainer(inch=1)
        src_dst2 = UnitsContainer(meter=1,
                                  second=-1), UnitsContainer(inch=1, minute=-1)
        for src, dst in (src_dst1, src_dst2):
            v = ureg.convert(1, src, dst),

            a = np.ones((3, 1))
            ac = np.ones((3, 1))

            r1 = ureg.convert(a, src, dst)
            np.testing.assert_allclose(r1, v * ac)
            self.assertIsNot(r1, a)

            r2 = ureg.convert(a, src, dst, inplace=True)
            np.testing.assert_allclose(r2, v * ac)
            self.assertIs(r2, a)
示例#10
0
文件: test_unit.py 项目: schryer/pint
    def test_dimension_definition(self):
        x = DimensionDefinition('[time]', '', (), converter='')
        self.assertTrue(x.is_base)
        self.assertEqual(x.name, '[time]')

        x = Definition.from_string('[speed] = [length]/[time]')
        self.assertIsInstance(x, DimensionDefinition)
        self.assertEqual(x.reference,
                         UnitsContainer({
                             '[length]': 1,
                             '[time]': -1
                         }))
示例#11
0
    def test_parse_parameterized(self):
        a = Context.__keytransform__(UnitsContainer({'[time]': -1.}),
                                     UnitsContainer({'[length]': 1.}))
        b = Context.__keytransform__(UnitsContainer({'[length]': 1.}),
                                     UnitsContainer({'[time]': -1.}))

        s = [
            '@context(n=1) longcontextname',
            '[length] <-> 1 / [time]: n * c / value'
        ]

        c = Context.from_lines(s)
        self.assertEqual(c.defaults, {'n': 1})
        self.assertEqual(set(c.funcs.keys()), set((a, b)))
        self._test_ctx(c)

        # If the variable is not present in the definition, then raise an error
        s = [
            '@context(n=1) longcontextname',
            '[length] <-> 1 / [time]: c / value'
        ]
        self.assertRaises(ValueError, Context.from_lines, s)
示例#12
0
    def test_quantity_creation(self):
        for args in ((4.2, 'meter'), (4.2, UnitsContainer(meter=1)),
                     (4.2, self.ureg.meter), ('4.2*meter', ),
                     ('4.2/meter**(-1)', ), (self.Q_(4.2, 'meter'), )):
            x = self.Q_(*args)
            self.assertEqual(x.magnitude, 4.2)
            self.assertEqual(x.units, UnitsContainer(meter=1))

        x = self.Q_(4.2, UnitsContainer(length=1))
        y = self.Q_(x)
        self.assertEqual(x.magnitude, y.magnitude)
        self.assertEqual(x.units, y.units)
        self.assertIsNot(x, y)

        x = self.Q_(4.2, None)
        self.assertEqual(x.magnitude, 4.2)
        self.assertEqual(x.units, UnitsContainer())

        with self.capture_log() as buffer:
            self.assertEqual(4.2 * self.ureg.meter,
                             self.Q_(4.2, 2 * self.ureg.meter))
            self.assertEqual(len(buffer), 1)
示例#13
0
文件: test_unit.py 项目: schryer/pint
    def test_unit_definition(self):
        x = Definition.from_string('coulomb = ampere * second')
        self.assertIsInstance(x, UnitDefinition)
        self.assertFalse(x.is_base)
        self.assertIsInstance(x.converter, ScaleConverter)
        self.assertEqual(x.converter.scale, 1)
        self.assertEqual(x.reference, UnitsContainer(ampere=1, second=1))

        x = Definition.from_string('faraday =  96485.3399 * coulomb')
        self.assertIsInstance(x, UnitDefinition)
        self.assertFalse(x.is_base)
        self.assertIsInstance(x.converter, ScaleConverter)
        self.assertEqual(x.converter.scale, 96485.3399)
        self.assertEqual(x.reference, UnitsContainer(coulomb=1))

        x = Definition.from_string('degF = 9 / 5 * kelvin; offset: 255.372222')
        self.assertIsInstance(x, UnitDefinition)
        self.assertFalse(x.is_base)
        self.assertIsInstance(x.converter, OffsetConverter)
        self.assertEqual(x.converter.scale, 9 / 5)
        self.assertEqual(x.converter.offset, 255.372222)
        self.assertEqual(x.reference, UnitsContainer(kelvin=1))
示例#14
0
文件: test_unit.py 项目: schryer/pint
 def test_invalid(self):
     self.assertRaises(TypeError, UnitsContainer, {1: 2})
     self.assertRaises(TypeError, UnitsContainer, {'1': '2'})
     d = UnitsContainer()
     self.assertRaises(TypeError, d.__setitem__, 1, 2)
     self.assertRaises(TypeError, d.__setitem__, '1', '2')
     self.assertRaises(TypeError, d.__mul__, list())
     self.assertRaises(TypeError, d.__imul__, list())
     self.assertRaises(TypeError, d.__pow__, list())
     self.assertRaises(TypeError, d.__ipow__, list())
     self.assertRaises(TypeError, d.__truediv__, list())
     self.assertRaises(TypeError, d.__itruediv__, list())
     self.assertRaises(TypeError, d.__rtruediv__, list())
示例#15
0
 def test_to_delta(self):
     parse = self.ureg.parse_units
     self.assertEqual(parse('degK', to_delta=True), UnitsContainer(degK=1))
     self.assertEqual(parse('degK', to_delta=False), UnitsContainer(degK=1))
     self.assertEqual(parse('degK**(-1)', to_delta=True),
                      UnitsContainer(degK=-1))
     self.assertEqual(parse('degK**(-1)', to_delta=False),
                      UnitsContainer(degK=-1))
     self.assertEqual(parse('degK**2', to_delta=True),
                      UnitsContainer(delta_degK=2))
     self.assertEqual(parse('degK**2', to_delta=False),
                      UnitsContainer(degK=2))
     self.assertEqual(parse('degK*meter', to_delta=True),
                      UnitsContainer(delta_degK=1, meter=1))
     self.assertEqual(parse('degK*meter', to_delta=False),
                      UnitsContainer(degK=1, meter=1))
示例#16
0
 def test_default_formatting(self):
     ureg = UnitRegistry()
     x = ureg.Quantity(4.12345678, UnitsContainer(meter=2, kilogram=1, second=-1))
     for spec, result in (('L', r'4.12345678 \frac{kilogram \cdot meter^{2}}{second}'),
                          ('P', '4.12345678 kilogram·meter²/second'),
                          ('H', '4.12345678 kilogram meter<sup>2</sup>/second'),
                          ('C', '4.12345678 kilogram*meter**2/second'),
                          ('~', '4.12345678 kg * m ** 2 / s'),
                          ('L~', r'4.12345678 \frac{kg \cdot m^{2}}{s}'),
                          ('P~', '4.12345678 kg·m²/s'),
                          ('H~', '4.12345678 kg m<sup>2</sup>/s'),
                          ('C~', '4.12345678 kg*m**2/s'),
                          ):
         ureg.default_format = spec
         self.assertEqual('{0}'.format(x), result)
示例#17
0
    def test_dimensionless_units(self):
        twopi = self.NON_INT_TYPE("2") * self.ureg.pi
        self.assertAlmostEqual(self.QP_("360", "degree").to("radian").magnitude, twopi)
        self.assertAlmostEqual(self.Q_(twopi, "radian"), self.QP_("360", "degree"))
        self.assertEqual(self.QP_("1", "radian").dimensionality, UnitsContainer())
        self.assertTrue(self.QP_("1", "radian").dimensionless)
        self.assertFalse(self.QP_("1", "radian").unitless)

        self.assertEqual(self.QP_("1", "meter") / self.QP_("1", "meter"), 1)
        self.assertEqual((self.QP_("1", "meter") / self.QP_("1", "mm")).to(""), 1000)

        self.assertEqual(self.Q_(10) // self.QP_("360", "degree"), 1)
        self.assertEqual(self.QP_("400", "degree") // self.Q_(twopi), 1)
        self.assertEqual(self.QP_("400", "degree") // twopi, 1)
        self.assertEqual(7 // self.QP_("360", "degree"), 1)
示例#18
0
 def test_quantity_format(self):
     x = self.Q_(4.12345678, UnitsContainer(meter=2, kilogram=1, second=-1))
     for spec, result in (('{}', str(x)), ('{!s}', str(x)), ('{!r}', repr(x)),
                          ('{0.magnitude}',  str(x.magnitude)), ('{0.units}',  str(x.units)),
                          ('{0.magnitude!s}',  str(x.magnitude)), ('{0.units!s}',  str(x.units)),
                          ('{0.magnitude!r}',  repr(x.magnitude)), ('{0.units!r}',  repr(x.units)),
                          ('{:.4f}', '{:.4f} {!s}'.format(x.magnitude, x.units)),
                          ('{:L}', r'4.12345678 \frac{kilogram \cdot meter^{2}}{second}'),
                          ('{:P}', '4.12345678 kilogram·meter²/second'),
                          ('{:H}', '4.12345678 kilogram meter<sup>2</sup>/second'),
                          ('{:~}', '4.12345678 kg * m ** 2 / s'),
                          ('{:L~}', r'4.12345678 \frac{kg \cdot m^{2}}{s}'),
                          ('{:P~}', '4.12345678 kg·m²/s'),
                          ('{:H~}', '4.12345678 kg m<sup>2</sup>/s'),
                          ):
         self.assertEqual(spec.format(x), result)
示例#19
0
 def test_get_dimensionality(self):
     get = self.ureg.get_dimensionality
     self.assertEqual(get('[time]'), UnitsContainer({'[time]': 1}))
     self.assertEqual(get(UnitsContainer({'[time]': 1})),
                      UnitsContainer({'[time]': 1}))
     self.assertEqual(get('seconds'), UnitsContainer({'[time]': 1}))
     self.assertEqual(get(UnitsContainer({'seconds': 1})),
                      UnitsContainer({'[time]': 1}))
     self.assertEqual(get('[speed]'),
                      UnitsContainer({
                          '[length]': 1,
                          '[time]': -1
                      }))
     self.assertEqual(get('[acceleration]'),
                      UnitsContainer({
                          '[length]': 1,
                          '[time]': -2
                      }))
示例#20
0
文件: test_unit.py 项目: schryer/pint
 def test_as_delta(self):
     parse = self.ureg.parse_units
     self.assertEqual(parse('kelvin', as_delta=True),
                      UnitsContainer(kelvin=1))
     self.assertEqual(parse('kelvin', as_delta=False),
                      UnitsContainer(kelvin=1))
     self.assertEqual(parse('kelvin**(-1)', as_delta=True),
                      UnitsContainer(kelvin=-1))
     self.assertEqual(parse('kelvin**(-1)', as_delta=False),
                      UnitsContainer(kelvin=-1))
     self.assertEqual(parse('kelvin**2', as_delta=True),
                      UnitsContainer(kelvin=2))
     self.assertEqual(parse('kelvin**2', as_delta=False),
                      UnitsContainer(kelvin=2))
     self.assertEqual(parse('kelvin*meter', as_delta=True),
                      UnitsContainer(kelvin=1, meter=1))
     self.assertEqual(parse('kelvin*meter', as_delta=False),
                      UnitsContainer(kelvin=1, meter=1))
示例#21
0
    def test_dimensionless_units(self):
        twopi = self.NON_INT_TYPE("2") * self.ureg.pi
        assert (round(
            abs(self.QP_("360", "degree").to("radian").magnitude - twopi),
            7) == 0)
        assert round(abs(self.Q_(twopi, "radian") - self.QP_("360", "degree")),
                     7) == 0
        assert self.QP_("1", "radian").dimensionality == UnitsContainer()
        assert self.QP_("1", "radian").dimensionless
        assert not self.QP_("1", "radian").unitless

        assert self.QP_("1", "meter") / self.QP_("1", "meter") == 1
        assert (self.QP_("1", "meter") / self.QP_("1", "mm")).to("") == 1000

        assert self.Q_(10) // self.QP_("360", "degree") == 1
        assert self.QP_("400", "degree") // self.Q_(twopi) == 1
        assert self.QP_("400", "degree") // twopi == 1
        assert 7 // self.QP_("360", "degree") == 1
示例#22
0
def __format__(self, spec):
    # modify Pint unit __format__

    spec = spec or self.default_format

    # special cases
    if "Lx" in spec:  # the LaTeX siunitx code
        return r"\si[]{%s}" % siunitx_format_unit(self)

    if '~' in spec or 'K' in spec or 'T' in spec or 'L' in spec:  # spectrochempy modified
        if self.dimensionless and 'absorbance' not in self._units:
            if self._units == 'ppm':
                units = UnitsContainer({'ppm': 1})
            elif self._units in ['percent', 'transmittance']:
                units = UnitsContainer({'%': 1})
            elif self._units == 'weight_percent':
                units = UnitsContainer({'wt.%': 1})
            elif self._units == 'radian':
                units = UnitsContainer({'rad': 1})
            elif self._units == 'degree':
                units = UnitsContainer({'deg': 1})
            # elif self._units == 'absorbance':
            #    units = UnitsContainer({'a.u.': 1})
            elif abs(self.scaling - 1.) < 1.e-10:
                units = UnitsContainer({'': 1})
            else:
                units = UnitsContainer({'scaled-dimensionless (%.2g)' % self.scaling: 1})
        else:
            units = UnitsContainer(
                dict((self._REGISTRY._get_symbol(key), value) for key, value in list(self._units.items())))
        spec = spec.replace('~', '')
    else:
        units = self._units

    if "H" in spec:
        # HTML / Jupyter Notebook (
        return r"\[" + format(units, spec).replace(" ", r"\ ") + r"\]"

    return '%s' % (format(units, spec))
示例#23
0
def __format__(self, spec):
    # modify Pint unit __format__

    spec = formatting.extract_custom_flags(spec or self.default_format)
    if "~" in spec:
        if not self._units:
            return ""

        # Spectrochempy
        if self.dimensionless and "absorbance" not in self._units:
            if self._units == "ppm":
                units = UnitsContainer({"ppm": 1})
            elif self._units in ["percent", "transmittance"]:
                units = UnitsContainer({"%": 1})
            elif self._units == "weight_percent":
                units = UnitsContainer({"wt.%": 1})
            elif self._units == "radian":
                units = UnitsContainer({"rad": 1})
            elif self._units == "degree":
                units = UnitsContainer({"deg": 1})
            # elif self._units == 'absorbance':
            #    units = UnitsContainer({'a.u.': 1})
            elif abs(self.scaling - 1.0) < 1.0e-10:
                units = UnitsContainer({"": 1})
            else:
                units = UnitsContainer(
                    {"scaled-dimensionless (%.2g)" % self.scaling: 1})
        else:
            units = UnitsContainer(
                dict((self._REGISTRY._get_symbol(key), value)
                     for key, value in self._units.items()))
        spec = spec.replace("~", "")
    else:
        units = self._units

    return formatting.format_unit(units, spec, registry=self._REGISTRY)
示例#24
0
 def test_issue66b(self):
     ureg = UnitRegistry()
     self.assertEqual(ureg.get_base_units(ureg.degK.units),
                      (1., UnitsContainer({'degK': 1})))
     self.assertEqual(ureg.get_base_units(ureg.degC.units),
                      (1., UnitsContainer({'degC': 1})))
示例#25
0
 def test_issue66b(self):
     ureg = UnitRegistry()
     self.assertEqual(ureg.get_base_units(ureg.kelvin.units),
                      (None, UnitsContainer({'kelvin': 1})))
     self.assertEqual(ureg.get_base_units(ureg.degC.units),
                      (None, UnitsContainer({'kelvin': 1})))
示例#26
0
 def test_issue523(self):
     src, dst = UnitsContainer({"meter": 1}), UnitsContainer({"degF": 1})
     value = 10.0
     convert = self.ureg.convert
     self.assertRaises(DimensionalityError, convert, value, src, dst)
     self.assertRaises(DimensionalityError, convert, value, dst, src)
示例#27
0
 def test_issue29(self):
     t = 4 * ureg("mW")
     self.assertEqual(t.magnitude, 4)
     self.assertEqual(t._units, UnitsContainer(milliwatt=1))
     self.assertEqual(t.to("joule / second"), 4e-3 * ureg("W"))
示例#28
0
 def test_issue66b(self):
     ureg = UnitRegistry()
     self.assertEqual(ureg.get_base_units(ureg.kelvin),
                      (1.0, ureg.Unit(UnitsContainer({'kelvin': 1}))))
     self.assertEqual(ureg.get_base_units(ureg.degC),
                      (1.0, ureg.Unit(UnitsContainer({'kelvin': 1}))))
示例#29
0
 def test_quantity_repr(self):
     x = self.Q_(4.2, UnitsContainer(meter=1))
     self.assertEqual(str(x), '4.2 meter')
     self.assertEqual(repr(x), "<Quantity(4.2, 'meter')>")
示例#30
0
 def test_issue29(self):
     ureg = UnitRegistry()
     t = 4 * ureg('mM')
     self.assertEqual(t.magnitude, 4)
     self.assertEqual(t._units, UnitsContainer(millimolar=1))
     self.assertEqual(t.to('mole / liter'), 4e-3 * ureg('M'))