Exemplo n.º 1
0
    def from_lines(cls, lines, to_base_func=None):
        header, lines = lines[0], lines[1:]

        r = _header_re.search(header)
        name = r.groupdict()['name'].strip()
        aliases = r.groupdict()['aliases']
        if aliases:
            aliases = tuple(a.strip() for a in r.groupdict()['aliases'].split('='))
        else:
            aliases = ()
        defaults = r.groupdict()['defaults']

        if defaults:
            def to_num(val):
                val = complex(val)
                if not val.imag:
                    return val.real
                return val
            defaults = dict((str(k), to_num(v))
                            for k, v in _def_re.findall(defaults.strip('()')))
            ctx = cls(name, aliases, defaults)
        else:
            ctx = cls(name, aliases)

        names = set()
        for line in lines:
            line = line.strip()
            if not line or line.startswith('#'):
                continue

            rel, eq = line.split(':')
            names.update(_varname_re.findall(eq))

            func = _expression_to_function(eq)

            if '<->' in rel:
                src, dst = (ParserHelper.from_string(s) for s in rel.split('<->'))
                if to_base_func:
                    src = to_base_func(src)
                    dst = to_base_func(dst)
                ctx.add_transformation(src, dst, func)
                ctx.add_transformation(dst, src, func)
            elif '->' in rel:
                src, dst = (ParserHelper.from_string(s) for s in rel.split('->'))
                if to_base_func:
                    src = to_base_func(src)
                    dst = to_base_func(dst)
                ctx.add_transformation(src, dst, func)
            else:
                raise ValueError('Relationships must be specified with <-> or ->.')

        if defaults:
            missing_pars = set(defaults.keys()).difference(set(names))
            if missing_pars:
                raise ValueError('Context parameters {0} not found in any equation.'.format(missing_pars))

        return ctx
Exemplo n.º 2
0
 def test_issue25(self):
     x = ParserHelper.from_string("10 %")
     self.assertEqual(x, ParserHelper(10, {"%": 1}))
     x = ParserHelper.from_string("10 ‰")
     self.assertEqual(x, ParserHelper(10, {"‰": 1}))
     ureg.define("percent = [fraction]; offset: 0 = %")
     ureg.define("permille = percent / 10 = ‰")
     x = ureg.parse_expression("10 %")
     self.assertEqual(x, ureg.Quantity(10, {"%": 1}))
     y = ureg.parse_expression("10 ‰")
     self.assertEqual(y, ureg.Quantity(10, {"‰": 1}))
     self.assertEqual(x.to("‰"), ureg.Quantity(1, {"‰": 1}))
Exemplo n.º 3
0
 def test_issue25(self):
     x = ParserHelper.from_string("10 %")
     assert x == ParserHelper(10, {"%": 1})
     x = ParserHelper.from_string("10 ‰")
     assert x == ParserHelper(10, {"‰": 1})
     ureg.define("percent = [fraction]; offset: 0 = %")
     ureg.define("permille = percent / 10 = ‰")
     x = ureg.parse_expression("10 %")
     assert x == ureg.Quantity(10, {"%": 1})
     y = ureg.parse_expression("10 ‰")
     assert y == ureg.Quantity(10, {"‰": 1})
     assert x.to("‰") == ureg.Quantity(1, {"‰": 1})
Exemplo n.º 4
0
 def test_issue25(self):
     x = ParserHelper.from_string('10 %')
     self.assertEqual(x, ParserHelper(10, {'%': 1}))
     x = ParserHelper.from_string('10 ‰')
     self.assertEqual(x, ParserHelper(10, {'‰': 1}))
     ureg = UnitRegistry()
     ureg.define('percent = [fraction]; offset: 0 = %')
     ureg.define('permille = percent / 10 = ‰')
     x = ureg.parse_expression('10 %')
     self.assertEqual(x, ureg.Quantity(10, {'%': 1}))
     y = ureg.parse_expression('10 ‰')
     self.assertEqual(y, ureg.Quantity(10, {'‰': 1}))
     self.assertEqual(x.to('‰'), ureg.Quantity(1, {'‰': 1}))
Exemplo n.º 5
0
 def test_issue25(self):
     x = ParserHelper.from_string('10 %')
     self.assertEqual(x, ParserHelper(10, {'%': 1}))
     x = ParserHelper.from_string('10 ‰')
     self.assertEqual(x, ParserHelper(10, {'‰': 1}))
     ureg = UnitRegistry()
     ureg.define('percent = [fraction]; offset: 0 = %')
     ureg.define('permille = percent / 10 = ‰')
     x = ureg.parse_expression('10 %')
     self.assertEqual(x, ureg.Quantity(10, {'%': 1}))
     y = ureg.parse_expression('10 ‰')
     self.assertEqual(y, ureg.Quantity(10, {'‰': 1}))
     self.assertEqual(x.to('‰'), ureg.Quantity(1, {'‰': 1}))
Exemplo n.º 6
0
 def test_issue25(self):
     x = ParserHelper.from_string("10 %")
     self.assertEqual(x, ParserHelper(10, {"%": 1}))
     x = ParserHelper.from_string("10 ‰")
     self.assertEqual(x, ParserHelper(10, {"‰": 1}))
     ureg = UnitRegistry()
     ureg.define("percent = [fraction]; offset: 0 = %")
     ureg.define("permille = percent / 10 = ‰")
     x = ureg.parse_expression("10 %")
     self.assertEqual(x, ureg.Quantity(10, {"%": 1}))
     y = ureg.parse_expression("10 ‰")
     self.assertEqual(y, ureg.Quantity(10, {"‰": 1}))
     self.assertEqual(x.to("‰"), ureg.Quantity(1, {"‰": 1}))
Exemplo n.º 7
0
 def test_get_compatible_units(self):
     ureg = UnitRegistry()
     self.assertEqual(ureg.get_compatible_units(""), frozenset())
     self.assertEqual(
         ureg.get_compatible_units("meter"),
         ureg.get_compatible_units(ParserHelper(meter=1)),
     )
Exemplo n.º 8
0
 def test_get_base_units(self):
     ureg = UnitRegistry()
     assert ureg.get_base_units("") == (1, ureg.Unit(""))
     assert ureg.get_base_units("pi") == (math.pi, ureg.Unit(""))
     assert ureg.get_base_units("ln10") == (math.log(10), ureg.Unit(""))
     assert ureg.get_base_units("meter") == ureg.get_base_units(
         ParserHelper(meter=1))
Exemplo n.º 9
0
def _freeze(d):
    """Return a hashable view of dict.
    """
    if isinstance(d, string_types):
        d = ParserHelper.from_string(d)
    if isinstance(d, frozenset):
        return d
    return frozenset(d.items())
Exemplo n.º 10
0
def _freeze(d):
    """Return a hashable view of dict.
    """
    if isinstance(d, string_types):
        d = ParserHelper.from_string(d)
    if isinstance(d, frozenset):
        return d
    return frozenset(d.items())
Exemplo n.º 11
0
 def test_get_base_units(self):
     ureg = UnitRegistry()
     self.assertEqual(ureg.get_base_units(""), (1, ureg.Unit("")))
     self.assertEqual(ureg.get_base_units("pi"), (math.pi, ureg.Unit("")))
     self.assertEqual(ureg.get_base_units("ln10"),
                      (math.log(10), ureg.Unit("")))
     self.assertEqual(ureg.get_base_units("meter"),
                      ureg.get_base_units(ParserHelper(meter=1)))
Exemplo n.º 12
0
		def __init__(self, name, symbol, aliases, ):
			self.reference = reference
			self.is_base = is_base
			if isinstance(converter, string_types):
				converter = ParserHelper.from_string(converter)
				self.reference = UnitsContainer(converter)
				converter = ScaleConverter(converter.scale)
			super(UnitDefinition, self).__init__(name, symbol, aliases, converter)
Exemplo n.º 13
0
 def test_get_base_units(self):
     ureg = UnitRegistry()
     self.assertEqual(ureg.get_base_units(''), (1, ureg.Unit('')))
     self.assertEqual(ureg.get_base_units('pi'), (math.pi, ureg.Unit('')))
     self.assertEqual(ureg.get_base_units('ln10'),
                      (math.log(10), ureg.Unit('')))
     self.assertEqual(ureg.get_base_units('meter'),
                      ureg.get_base_units(ParserHelper(meter=1)))
Exemplo n.º 14
0
    def test_issue856(self):
        ph1 = ParserHelper(scale=123)
        ph2 = copy.deepcopy(ph1)
        assert ph2.scale == ph1.scale

        ureg1 = UnitRegistry()
        ureg2 = copy.deepcopy(ureg1)
        # Very basic functionality test
        assert ureg2("1 t").to("kg").magnitude == 1000
Exemplo n.º 15
0
    def test_basic(self):
        # Parse Helper ar mutables, so we build one everytime
        x = lambda: ParserHelper(1, meter=2)
        xp = lambda: ParserHelper(1, meter=2)
        y = lambda: ParserHelper(2, meter=2)

        self.assertEqual(x(), xp())
        self.assertNotEqual(x(), y())
        self.assertEqual(ParserHelper.from_string(''), ParserHelper())
        self.assertEqual(repr(x()), "<ParserHelper(1, {'meter': 2})>")

        self.assertEqual(ParserHelper(2), 2)

        self.assertEqual(x(), dict(meter=2))
        self.assertEqual(x(), 'meter ** 2')
        self.assertNotEqual(y(), dict(meter=2))
        self.assertNotEqual(y(), 'meter ** 2')

        self.assertNotEqual(xp(), object())
Exemplo n.º 16
0
    def test_basic(self):
        # Parse Helper ar mutables, so we build one everytime
        x = lambda: ParserHelper(1, meter=2)
        xp = lambda: ParserHelper(1, meter=2)
        y = lambda: ParserHelper(2, meter=2)

        assert x() == xp()
        assert x() != y()
        assert ParserHelper.from_string("") == ParserHelper()
        assert repr(x()) == "<ParserHelper(1, {'meter': 2})>"

        assert ParserHelper(2) == 2

        assert x() == dict(meter=2)
        assert x() == "meter ** 2"
        assert y() != dict(meter=2)
        assert y() != "meter ** 2"

        assert xp() != object()
Exemplo n.º 17
0
    def test_basic(self):
        # Parse Helper ar mutables, so we build one everytime
        x = lambda: ParserHelper(1, meter=2)
        xp = lambda: ParserHelper(1, meter=2)
        y = lambda: ParserHelper(2, meter=2)

        self.assertEqual(x(), xp())
        self.assertNotEqual(x(), y())
        self.assertEqual(ParserHelper.from_string(""), ParserHelper())
        self.assertEqual(repr(x()), "<ParserHelper(1, {'meter': 2.0})>")

        self.assertEqual(ParserHelper(2), 2)

        self.assertEqual(x(), dict(meter=2))
        self.assertEqual(x(), "meter ** 2")
        self.assertNotEqual(y(), dict(meter=2))
        self.assertNotEqual(y(), "meter ** 2")

        self.assertNotEqual(xp(), object())
Exemplo n.º 18
0
 def test_get_compatible_units(self):
     ureg = UnitRegistry()
     assert ureg.get_compatible_units("") == frozenset()
     assert ureg.get_compatible_units("meter") == ureg.get_compatible_units(
         ParserHelper(meter=1)
     )
Exemplo n.º 19
0
 def _test_eval_token(self, expected, expression, use_decimal=False):
     token = next(tokenizer(expression))
     actual = ParserHelper.eval_token(token, use_decimal=use_decimal)
     self.assertEqual(expected, actual)
     self.assertEqual(type(expected), type(actual))
Exemplo n.º 20
0
    def test_calculate(self):
        # Parse Helper ar mutables, so we build one everytime
        x = lambda: ParserHelper(1.0, meter=2)
        y = lambda: ParserHelper(2.0, meter=-2)
        z = lambda: ParserHelper(2.0, meter=2)

        self.assertEqual(x() * 4.0, ParserHelper(4.0, meter=2))
        self.assertEqual(x() * y(), ParserHelper(2.0))
        self.assertEqual(x() * "second", ParserHelper(1.0, meter=2, second=1))

        self.assertEqual(x() / 4.0, ParserHelper(0.25, meter=2))
        self.assertEqual(x() / "second", ParserHelper(1.0, meter=2, second=-1))
        self.assertEqual(x() / z(), ParserHelper(0.5))

        self.assertEqual(4.0 / z(), ParserHelper(2.0, meter=-2))
        self.assertEqual("seconds" / z(), ParserHelper(0.5,
                                                       seconds=1,
                                                       meter=-2))
        self.assertEqual(
            dict(seconds=1) / z(), ParserHelper(0.5, seconds=1, meter=-2))
Exemplo n.º 21
0
 def _test_eval_token(self, expected, expression, use_decimal=False):
     token = next(tokenizer(expression))
     actual = ParserHelper.eval_token(token, use_decimal=use_decimal)
     assert expected == actual
     assert type(expected) == type(actual)
Exemplo n.º 22
0
    def test_calculate(self):
        # Parse Helper ar mutables, so we build one everytime
        x = lambda: ParserHelper(1., meter=2)
        y = lambda: ParserHelper(2., meter=-2)
        z = lambda: ParserHelper(2., meter=2)

        self.assertEqual(x() * 4., ParserHelper(4., meter=2))
        self.assertEqual(x() * y(), ParserHelper(2.))
        self.assertEqual(x() * 'second', ParserHelper(1., meter=2, second=1))

        self.assertEqual(x() / 4., ParserHelper(0.25, meter=2))
        self.assertEqual(x() / 'second', ParserHelper(1., meter=2, second=-1))
        self.assertEqual(x() / z(), ParserHelper(0.5))

        self.assertEqual(4. / z(), ParserHelper(2., meter=-2))
        self.assertEqual('seconds' / z(),
                         ParserHelper(0.5, seconds=1, meter=-2))
        self.assertEqual(dict(seconds=1) / z(),
                         ParserHelper(0.5, seconds=1, meter=-2))
Exemplo n.º 23
0
	def constructCurrencyDefinition(rate):
		parserHelper=ParserHelper.from_word(baseCurrencyISOCode) * rate.rate
		unit=UnitDefinition(rate.iso, symbol=None, aliases=[rate.name.replace(" ", "_")], reference=UnitsContainer(parserHelper), is_base=False, converter=ScaleConverter(parserHelper))
		
		#return unit
		return rate.iso+" = "+str(rate.rate)+" "+baseCurrencyISOCode
Exemplo n.º 24
0
    def test_calculate(self):
        # Parse Helper ar mutables, so we build one everytime
        x = lambda: ParserHelper(1.0, meter=2)
        y = lambda: ParserHelper(2.0, meter=-2)
        z = lambda: ParserHelper(2.0, meter=2)

        assert x() * 4.0 == ParserHelper(4.0, meter=2)
        assert x() * y() == ParserHelper(2.0)
        assert x() * "second" == ParserHelper(1.0, meter=2, second=1)

        assert x() / 4.0 == ParserHelper(0.25, meter=2)
        assert x() / "second" == ParserHelper(1.0, meter=2, second=-1)
        assert x() / z() == ParserHelper(0.5)

        assert 4.0 / z() == ParserHelper(2.0, meter=-2)
        assert "seconds" / z() == ParserHelper(0.5, seconds=1, meter=-2)
        assert dict(seconds=1) / z() == ParserHelper(0.5, seconds=1, meter=-2)
Exemplo n.º 25
0
    def from_lines(cls, lines, to_base_func=None):
        header, lines = lines[0], lines[1:]

        r = _header_re.search(header)
        name = r.groupdict()['name'].strip()
        aliases = r.groupdict()['aliases']
        if aliases:
            aliases = tuple(a.strip()
                            for a in r.groupdict()['aliases'].split('='))
        else:
            aliases = ()
        defaults = r.groupdict()['defaults']

        if defaults:

            def to_num(val):
                val = complex(val)
                if not val.imag:
                    return val.real
                return val

            defaults = dict((str(k), to_num(v))
                            for k, v in _def_re.findall(defaults.strip('()')))
            ctx = cls(name, aliases, defaults)
        else:
            ctx = cls(name, aliases)

        names = set()
        for line in lines:
            line = line.strip()
            if not line or line.startswith('#'):
                continue

            rel, eq = line.split(':')
            names.update(_varname_re.findall(eq))

            func = _expression_to_function(eq)

            if '<->' in rel:
                src, dst = (ParserHelper.from_string(s)
                            for s in rel.split('<->'))
                if to_base_func:
                    src = to_base_func(src)
                    dst = to_base_func(dst)
                ctx.add_transformation(src, dst, func)
                ctx.add_transformation(dst, src, func)
            elif '->' in rel:
                src, dst = (ParserHelper.from_string(s)
                            for s in rel.split('->'))
                if to_base_func:
                    src = to_base_func(src)
                    dst = to_base_func(dst)
                ctx.add_transformation(src, dst, func)
            else:
                raise ValueError(
                    'Relationships must be specified with <-> or ->.')

        if defaults:
            missing_pars = set(defaults.keys()).difference(set(names))
            if missing_pars:
                raise ValueError(
                    'Context parameters {0} not found in any equation.'.format(
                        missing_pars))

        return ctx
Exemplo n.º 26
0
 def test_nan(self):
     for s in ("nan", "NAN", "NaN", "123 NaN nan NAN 456"):
         with self.subTest(s):
             p = ParserHelper.from_string(s + " kg")
             assert math.isnan(p.scale)
             self.assertEqual(dict(p), {"kg": 1})
Exemplo n.º 27
0
 def _test_eval_token(self, expected, expression, use_decimal=False):
     token = next(tokenizer(expression))
     actual = ParserHelper.eval_token(token, use_decimal=use_decimal)
     self.assertEqual(expected, actual)
     self.assertEqual(type(expected), type(actual))
Exemplo n.º 28
0
 def test_get_base_units(self):
     ureg = UnitRegistry()
     self.assertEqual(ureg.get_base_units(''), (1, ureg.Unit('')))
     self.assertEqual(ureg.get_base_units('meter'),
                      ureg.get_base_units(ParserHelper(meter=1)))
Exemplo n.º 29
0
 def test_nan(self, subtests):
     for s in ("nan", "NAN", "NaN", "123 NaN nan NAN 456"):
         with subtests.test(s):
             p = ParserHelper.from_string(s + " kg")
             assert math.isnan(p.scale)
             assert dict(p) == {"kg": 1}