Exemplo n.º 1
0
def test_plus_minus():
    if sys.version_info.major <= 3:
        return
    with Quantity.prefs(
            spacer=None,
            show_label=None,
            label_fmt=None,
            label_fmt_full=None,
            show_desc=False,
            prec=4,
            plus=Quantity.plus_sign,
            minus=Quantity.minus_sign,
            map_sf=Quantity.map_sf_to_sci_notation,
    ):
        qpp = Quantity('+1Ms')
        qpm = Quantity('+1us')
        qmp = Quantity('-1Ms')
        qmm = Quantity('-1us')

        assert '{}'.format(qpp) == '1 Ms'
        assert '{}'.format(qpm) == '1 µs'
        assert '{}'.format(qmp) == '−1 Ms'
        assert '{}'.format(qmm) == '−1 µs'

        assert '{0:e} {0:u}'.format(qpp) == '1e+06 s'
        assert '{0:e} {0:u}'.format(qpm) == '1e−06 s'
        assert '{0:e} {0:u}'.format(qmp) == '−1e+06 s'
        assert '{0:e} {0:u}'.format(qmm) == '−1e−06 s'

        assert '{:.8p}'.format(qpp) == '1000000 s'
        assert '{:.8p}'.format(qpm) == '0.000001 s'
        assert '{:.8p}'.format(qmp) == '−1000000 s'
        assert '{:.8p}'.format(qmm) == '−0.000001 s'
Exemplo n.º 2
0
def test_prefs_defaults():
    Quantity.reset_prefs()
    Quantity.set_prefs(spacer='-', map_sf=dict(k='K'))
    assert Quantity.get_pref('spacer') == '-'
    assert Quantity.get_pref('map_sf') == dict(k='K')

    class Foo(Quantity):
        pass

    assert Foo.get_pref('spacer') == '-'
    assert Foo.get_pref('map_sf') == dict(k='K')
    Foo.set_prefs(spacer='~', map_sf={})
    assert Foo.get_pref('spacer') == '~'
    assert Foo.get_pref('map_sf') == dict()
    assert Quantity.get_pref('spacer') == '-'
    assert Quantity.get_pref('map_sf') == dict(k='K')

    with Quantity.prefs(spacer=None, map_sf=None):
        assert Quantity.get_pref('spacer') == ' '
        assert Quantity.get_pref('map_sf') == {}

    assert Quantity.get_pref('spacer') == '-'
    assert Quantity.get_pref('map_sf') == dict(k='K')

    Quantity.set_prefs(spacer=None, map_sf=None)
Exemplo n.º 3
0
def test_reader():
    with Quantity.prefs(known_units='Zippy'):
        for line in data1.splitlines():
            v, s1, s2, s3, s4, s5 = [
                c.strip() for c in line.strip().split(';')
            ]
            print('Trying: v={v}, s1={s1}, s2={s2}, s3={s3}, s4={s4}, s5={s5}'.
                  format(**locals()))
            q = Quantity(v, binary=True)

            res = str(q)
            exp = '{v}: expected <{s1}>, got <{res}>.'.format(**locals())
            assert s1 == res, exp

            res = q.binary()
            exp = '{v}: expected <{s2}>, got <{res}>.'.format(**locals())
            assert s2 == res, exp

            res = q.binary(prec=4, strip_zeros=False)
            exp = '{v}: expected <{s3}>, got <{res}>.'.format(**locals())
            assert s3 == res, exp

            res = q.binary(strip_zeros=True,
                           strip_radix=False,
                           show_units=False)
            exp = '{v}: expected <{s4}>, got <{res}>.'.format(**locals())
            assert s4 == res, exp

            res = q.binary(prec='full', strip_zeros=False)
            exp = '{v}: expected <{s5}>, got <{res}>.'.format(**locals())
            assert s5 == res, exp
Exemplo n.º 4
0
def test_time():
    Quantity.reset_prefs()
    with Quantity.prefs(
        spacer=None, show_label=None, label_fmt=None, label_fmt_full=None,
        ignore_sf=True
    ):
        q=Quantity('86400 s')
        assert q.render() == '86.4 ks'
        assert q.render(scale='sec') == '86.4 ksec'
        assert q.render(scale='min') == '1.44 kmin'
        assert q.render(scale='hr') == '24 hr'
        assert q.render(scale='hour') == '24 hour'
        assert q.render(scale='day') == '1 day'

        q=Quantity('1 day', scale='s')
        assert q.render() == '86.4 ks'

        q=Quantity('24 hour', scale='s')
        assert q.render() == '86.4 ks'

        q=Quantity('24 hr', scale='s')
        assert q.render() == '86.4 ks'

        q=Quantity('60 min', scale='s')
        assert q.render() == '3.6 ks'

        q=Quantity('60 sec', scale='s')
        assert q.render() == '60 s'
Exemplo n.º 5
0
def test_radix_comma_exception():
    with pytest.raises(ValueError) as exception:
        with Quantity.prefs(radix=',', ):
            Quantity('$1M')
    assert exception.value.args[0] == "comma and radix must differ."

    with pytest.raises(QuantiPhyError) as exception:
        with Quantity.prefs(comma='.', ):
            Quantity('$1M')
    assert exception.value.args[0] == "comma and radix must differ."

    with pytest.raises(IncompatiblePreferences) as exception:
        with Quantity.prefs(
                comma='^',
                radix='^',
        ):
            Quantity('$1M')
    assert exception.value.args[0] == "comma and radix must differ."
Exemplo n.º 6
0
def test_simple_scaling():
    Quantity.reset_prefs()
    with Quantity.prefs(
        spacer=None, show_label=None, label_fmt=None, label_fmt_full=None
    ):
        q=Quantity('1kg', scale=2)
        qs=Quantity('2ms')
        assert q.render() == '2 kg'
        assert qs.render() == '2 ms'
        assert q.render(scale=0.001) == '2 g'
        assert str(q.scale(0.001)) == '2 g'
        assert q.render(scale=qs) == '4 g'
        assert str(q.scale(qs)) == '4 g'
        with pytest.raises(KeyError) as exception:
            q.render(scale='fuzz')
        assert str(exception.value) == "unable to convert between 'fuzz' and 'g'."
        assert isinstance(exception.value, UnknownConversion)
        assert isinstance(exception.value, QuantiPhyError)
        assert isinstance(exception.value, KeyError)
        assert exception.value.args == ('fuzz', 'g')
        with pytest.raises(KeyError) as exception:
            q.scale('fuzz')
        assert str(exception.value) == "unable to convert between 'fuzz' and 'g'."
        assert isinstance(exception.value, UnknownConversion)
        assert isinstance(exception.value, QuantiPhyError)
        assert isinstance(exception.value, KeyError)
        assert exception.value.args == ('fuzz', 'g')

        q=Quantity('1', units='g', scale=1000)
        assert q.render() == '1 kg'
        assert q.render(scale=(0.0022046, 'lbs')) == '2.2046 lbs'
        assert str(q.scale((0.0022046, 'lbs'))) == '2.2046 lbs'

        q=Quantity('1', units='g', scale=qs)
        assert q.render() == '2 mg'

        q=Quantity('1', scale=(1000, 'g'))
        assert q.render() == '1 kg'
        assert q.render(scale=lambda v, u: (0.0022046*v, 'lbs')) == '2.2046 lbs'

        def dB(v, u):
            return 20*math.log(v, 10), 'dB'+u

        def adB(v, u):
            return pow(10, v/20), u[2:] if u.startswith('dB') else u

        q=Quantity('-40 dBV', scale=adB)
        assert q.render() == '10 mV'
        assert q.render(scale=dB) == '-40 dBV'
        assert str(q.scale(dB)) == '-40 dBV'
Exemplo n.º 7
0
def test_number_recognition(name, given, prefs, tests, error):
    with Quantity.prefs(**prefs):
        try:
            defined = with_quantiphy.exec(given)
        except (ValueError, KeyError) as e:
            assert not tests, name
            assert str(e) == error, name
            return

        for id, test in tests.items():
            result = eval(test['evaluate'], {}, defined)
            expected = eval(test['expected'], {}, defined)
            assert result == pytest.approx(expected, abs=0,
                                           nan_ok=True), f'{name} {id}'
Exemplo n.º 8
0
def test_radix_comma_input():
    with Quantity.prefs(
        spacer = None,
        show_label = None,
        label_fmt = None,
        label_fmt_full = None,
        show_desc = False,
        prec = 4,
        radix = ',',
        comma = '.',
    ):
        assert Quantity('299,79 Mm/s').render() == '299,79 Mm/s'
        assert Quantity('299,792458e6 m/s').render() == '299,79 Mm/s'
        assert Quantity('299,792458 Mm/s').render() == '299,79 Mm/s'
        assert Quantity('299.792.458,0000 m/s').render() == '299,79 Mm/s'
        assert Quantity('299792458,0000 m/s').render() == '299,79 Mm/s'
        assert Quantity('1.000.000,00 KiB', binary=True).render() == '1,024 GB'
        assert Quantity('$1.000.000,00').render() == '$1M'
        assert Quantity('$1.000.000,00e3').render() == '$1G'

    with Quantity.prefs(
        spacer = None,
        show_label = None,
        label_fmt = None,
        label_fmt_full = None,
        show_desc = False,
        prec = 4,
        radix = ',',
        comma = '',
    ):
        assert Quantity('299,79 Mm/s').render() == '299,79 Mm/s'
        assert Quantity('299.79 Mm/s').render() == '299,79 Mm/s'
        assert Quantity('$1000000,00').render() == '$1M'
        assert Quantity('$1000000.00').render() == '$1M'
        assert Quantity('$1,00e8').render() == '$100M'
        assert Quantity('$1.00e8').render() == '$100M'
Exemplo n.º 9
0
def test_assign_rec():
    with Quantity.prefs(
            assign_rec=
            r'(?P<name>\w+?)\s*=\s*(?P<val>\w*)(\s+(--)\s*(?P<desc>.*?))?\Z'):
        qs = Quantity.extract(r"""
                -- The Hydrogen Line
                bad = --    Also known as the 21 cm line
                = bad --    The spectral line associated with a spin flip.

                f_hy = 1420MHz -- Hydrogen line frequency
            """)
        f_hy = qs.pop('f_hy')
        assert f_hy.is_close(Quantity(1.42e9, 'Hz'), check_units=True)
        assert f_hy.is_close(1.42e9)
        assert f_hy.units == 'Hz'
        assert f_hy.name == 'f_hy'
        assert f_hy.desc == 'Hydrogen line frequency'
        assert not qs
Exemplo n.º 10
0
def test_mass():
    with Quantity.prefs(
        spacer=None, show_label=None, label_fmt=None, label_fmt_full=None,
        ignore_sf=False
    ):
        q=Quantity('1 g')
        assert q.render() == '1 g'
        assert q.render(scale='oz') == '35.274 moz'
        assert q.render(scale='lb') == '2.2046 mlb'
        assert q.render(scale='lbs') == '2.2046 mlbs'

        q=Quantity('1 oz', scale='g')
        assert q.render() == '28.35 g'

        q=Quantity('1 lb', scale='g')
        assert q.render() == '453.59 g'

        q=Quantity('1 lbs', scale='g')
        assert q.render() == '453.59 g'
Exemplo n.º 11
0
def test_radix_comma_output():
    with Quantity.prefs(
        spacer = None,
        show_label = None,
        label_fmt = None,
        label_fmt_full = None,
        show_desc = False,
        prec = 4,
        radix = ',',
        comma = '.',
    ):
        q=Quantity('c')
        assert '{}'.format(q) == '299,79 Mm/s'
        assert '{:.8}'.format(q) == '299,792458 Mm/s'
        assert '{:.8s}'.format(q) == '299,792458 Mm/s'
        assert '{:.8S}'.format(q) == 'c = 299,792458 Mm/s'
        assert '{:.8q}'.format(q) == '299,792458 Mm/s'
        assert '{:.8Q}'.format(q) == 'c = 299,792458 Mm/s'
        assert '{:r}'.format(q) == '299,79M'
        assert '{:R}'.format(q) == 'c = 299,79M'
        assert '{:u}'.format(q) == 'm/s'
        assert '{:.4f}'.format(q) == '299792458'
        assert '{:.4F}'.format(q) == 'c = 299792458'
        assert '{:e}'.format(q) == '2.9979e+08'
        assert '{:E}'.format(q) == 'c = 2.9979e+08'
        assert '{:g}'.format(q) == '2.9979e+08'
        assert '{:G}'.format(q) == 'c = 2.9979e+08'
        assert '{:n}'.format(q) == 'c'
        assert '{:d}'.format(q) == 'speed of light'
        assert '{:#p}'.format(q) == '299792458,0000 m/s'
        assert '{:#.2p}'.format(q) == '299792458,00 m/s'
        assert '{:#,.2p}'.format(q) == '299.792.458,00 m/s'
        assert '{:#,P}'.format(q) == 'c = 299.792.458,0000 m/s'
        assert '{:#.2P}'.format(q) == 'c = 299792458,00 m/s'
        assert '{:#,.2P}'.format(q) == 'c = 299.792.458,00 m/s'
        assert '{:p}'.format(q) == '299792458 m/s'
        assert '{:.2p}'.format(q) == '299792458 m/s'
        assert '{:,.2p}'.format(q) == '299.792.458 m/s'
        assert '{:,P}'.format(q) == 'c = 299.792.458 m/s'
        assert '{:.2P}'.format(q) == 'c = 299792458 m/s'
        assert '{:,.2P}'.format(q) == 'c = 299.792.458 m/s'
Exemplo n.º 12
0
def test_plus_minus():
    with Quantity.prefs(
        spacer = None,
        show_label = None,
        label_fmt = None,
        label_fmt_full = None,
        show_desc = False,
        prec = 4,
        plus = Quantity.plus_sign,
        minus = Quantity.minus_sign,
        map_sf = Quantity.map_sf_to_sci_notation,
    ):
        qpp=Quantity('+1Ms')
        qpm=Quantity('+1us')
        qmp=Quantity('-1Ms')
        qmm=Quantity('-1us')

        assert '{}'.format(qpp) == '1 Ms'
        assert '{}'.format(qpm) == '1 µs'
        assert '{}'.format(qmp) == '−1 Ms'
        assert '{}'.format(qmm) == '−1 µs'

        assert '{0:e} {0:u}'.format(qpp) == '1e+06 s'
        assert '{0:e} {0:u}'.format(qpm) == '1e−06 s'
        assert '{0:e} {0:u}'.format(qmp) == '−1e+06 s'
        assert '{0:e} {0:u}'.format(qmm) == '−1e−06 s'

        assert '{:.8p}'.format(qpp) == '1000000 s'
        assert '{:.8p}'.format(qpm) == '0.000001 s'
        assert '{:.8p}'.format(qmp) == '−1000000 s'
        assert '{:.8p}'.format(qmm) == '−0.000001 s'

        assert qpp.render(form='sia') == '1 Ms'
        assert qpm.render(form='sia') == '1 us'
        assert qmp.render(form='sia') == '−1 Ms'
        assert qmm.render(form='sia') == '−1 us'
Exemplo n.º 13
0
 def ident(self):
     with Quantity.prefs(spacer=''):
         return ''.join(cull([self.tokens.name(), self.date])).lower()
Exemplo n.º 14
0
def to_rkm(q, prec=None, show_units=None, strip_zeros=None, strip_code=None):
    '''To RKM

    Convert a quantiphy.Quantity to an RKM string.

    Args:
        q (quantiphy.Quantity, str, or float):
            The value to be converted to an RKM code.
        prec (int):
            The precision. The number of digits is the precision + 1.
        show_units (bool):
            Whether and where the units should be included in the RKM code
            (default is False).
        strip_zeros (bool):
            Whether excess zeros should be removed (default is True).
        strip_code (bool):
            Whether the base code should be removed from the end of the RKM code
            (eg: 470 → 470 if true and 470r otherwise).
    Returns:
        A quantiphy.Quantity if a valid RKM code was found, otherwise *None* is
        returned.
    '''
    if show_units is None:
        show_units = _show_units
    if strip_zeros is None:
        strip_zeros = _strip_zeros
    if strip_code is None:
        strip_code = _strip_code
    if prec is None:
        prec = _prec
    try:
        units = q.units
    except AttributeError:
        q = Quantity(q)
        units = q.units
    rkm_base_code = _units_to_rkm_base_code.get(units, units)
    if not rkm_base_code:
        rkm_base_code = 'd'
    if not show_units:
        units = ''

    with q.prefs(
        map_sf={},
        show_units=False,
        strip_zeros=False,
        strip_radix=False,
        prec=prec
    ):
        value = q.render(form='si')
        if 'e-' in value:
            value = q.render(form='fixed')
    is_negative = value.startswith('-')
    if is_negative:
        value = value[1:]

    sf = value[-1]
    if sf and sf in q.output_sf:
        value = value[:-1]
    elif units:
        sf = ''
    else:
        sf = rkm_base_code
    if '.' not in value:
        value += '.'
    if strip_zeros:
        value = value.rstrip('0')
    if value.startswith('0.') and value[-1] != '.':
        value = value[1:]
    if not sf:
        if units:
            sf = units
            units = ''
        else:
            sf = rkm_base_code
    if strip_code and sf == rkm_base_code:
        value = value.rstrip('.')
    if is_negative:
        value = '-' + value
    value = value.replace('-', _minus_sign)
    return value.replace('.', _map_sf.get(sf, sf)+units)
Exemplo n.º 15
0
def test_sign():
    Quantity.set_prefs(spacer=None, show_label=None, label_fmt=None, label_fmt_full=None, show_desc=False)

    # Positive numbers
    q=Quantity('f = 1420.405751786 MHz -- frequency of hydrogen line')
    assert '{}'.format(q) == '1.4204 GHz'
    assert '{:q}'.format(q) == '1.4204 GHz'
    assert '{:r}'.format(q) == '1.4204G'
    assert '{:f}'.format(q) == '1420405751.786'
    assert '{:e}'.format(q) == '1.4204e+09'
    assert '{:g}'.format(q) == '1.4204e+09'
    assert '{:p}'.format(q) == '1420405751.786 Hz'
    assert '{:,p}'.format(q) == '1,420,405,751.786 Hz'
    assert '{:#.3q}'.format(q) == '1.420 GHz'
    assert '{:#p}'.format(q) == '1420405751.7860 Hz'

    q=Quantity('Total = $1000k -- a large amount of money')
    assert '{}'.format(q) == '$1M'
    assert '{:q}'.format(q) == '$1M'
    assert '{:r}'.format(q) == '1M'
    assert '{:f}'.format(q) == '1000000'
    assert '{:e}'.format(q) == '1e+06'
    assert '{:g}'.format(q) == '1e+06'
    assert '{:p}'.format(q) == '$1000000'
    assert '{:#p}'.format(q) == '$1000000.0000'

    q=Quantity('f = 1e100 atoms')
    assert '{}'.format(q) == '10e99 atoms'
    assert '{:q}'.format(q) == '10e99 atoms'
    assert '{:r}'.format(q) == '10e99'
    assert '{:e}'.format(q) == '1e+100'
    assert '{:g}'.format(q) == '1e+100'

    q=Quantity('light = inf Hz -- a high frequency')
    assert '{}'.format(q) == 'inf Hz'
    assert '{:q}'.format(q) == 'inf Hz'
    assert '{:r}'.format(q) == 'inf'
    assert '{:f}'.format(q) == 'inf'
    assert '{:e}'.format(q) == 'inf'
    assert '{:g}'.format(q) == 'inf'
    assert '{:p}'.format(q) == 'inf Hz'

    q=Quantity('f = -1420.405751786 MHz -- frequency of hydrogen line')
    assert '{}'.format(q) == '-1.4204 GHz'
    assert '{:f}'.format(q) == '-1420405751.786'
    assert '{:e}'.format(q) == '-1.4204e+09'
    assert '{:g}'.format(q) == '-1.4204e+09'
    assert '{:p}'.format(q) == '-1420405751.786 Hz'
    assert '{:,p}'.format(q) == '-1,420,405,751.786 Hz'
    assert '{:#.3q}'.format(q) == '-1.420 GHz'
    assert '{:#p}'.format(q) == '-1420405751.7860 Hz'

    # Negative numbers
    q=Quantity('f = -1420.405751786 MHz -- frequency of hydrogen line')
    assert '{}'.format(q) == '-1.4204 GHz'
    assert '{:q}'.format(q) == '-1.4204 GHz'
    assert '{:r}'.format(q) == '-1.4204G'
    assert '{:f}'.format(q) == '-1420405751.786'
    assert '{:e}'.format(q) == '-1.4204e+09'
    assert '{:g}'.format(q) == '-1.4204e+09'
    assert '{:p}'.format(q) == '-1420405751.786 Hz'
    assert '{:,p}'.format(q) == '-1,420,405,751.786 Hz'
    assert '{:#.3q}'.format(q) == '-1.420 GHz'
    assert '{:#p}'.format(q) == '-1420405751.7860 Hz'

    q=Quantity('Total = -$1000k -- a large amount of money')
    assert '{}'.format(q) == '-$1M'
    assert '{:q}'.format(q) == '-$1M'
    assert '{:r}'.format(q) == '-1M'
    assert '{:f}'.format(q) == '-1000000'
    assert '{:e}'.format(q) == '-1e+06'
    assert '{:g}'.format(q) == '-1e+06'
    assert '{:p}'.format(q) == '-$1000000'
    assert '{:#p}'.format(q) == '-$1000000.0000'

    q=Quantity('f = -1e-100 atoms')
    assert '{}'.format(q) == '-100e-102 atoms'
    assert '{:q}'.format(q) == '-100e-102 atoms'
    assert '{:r}'.format(q) == '-100e-102'
    assert '{:e}'.format(q) == '-1e-100'
    assert '{:g}'.format(q) == '-1e-100'

    q=Quantity('light = -inf Hz -- a high frequency')
    assert '{}'.format(q) == '-inf Hz'
    assert '{:q}'.format(q) == '-inf Hz'
    assert '{:r}'.format(q) == '-inf'
    assert '{:f}'.format(q) == '-inf'
    assert '{:e}'.format(q) == '-inf'
    assert '{:g}'.format(q) == '-inf'
    assert '{:p}'.format(q) == '-inf Hz'

    with Quantity.prefs(plus=Quantity.plus_sign, minus=Quantity.minus_sign):

        # Positive numbers
        q=Quantity('f = 1420.405751786 MHz -- frequency of hydrogen line')
        assert '{}'.format(q) == '1.4204 GHz'
        assert '{:q}'.format(q) == '1.4204 GHz'
        assert '{:r}'.format(q) == '1.4204G'
        assert '{:f}'.format(q) == '1420405751.786'
        assert '{:e}'.format(q) == '1.4204e+09'
        assert '{:g}'.format(q) == '1.4204e+09'
        assert '{:p}'.format(q) == '1420405751.786 Hz'
        assert '{:,p}'.format(q) == '1,420,405,751.786 Hz'
        assert '{:#.3q}'.format(q) == '1.420 GHz'
        assert '{:#p}'.format(q) == '1420405751.7860 Hz'

        q=Quantity('Total = $1000k -- a large amount of money')
        assert '{}'.format(q) == '$1M'
        assert '{:q}'.format(q) == '$1M'
        assert '{:r}'.format(q) == '1M'
        assert '{:f}'.format(q) == '1000000'
        assert '{:e}'.format(q) == '1e+06'
        assert '{:g}'.format(q) == '1e+06'
        assert '{:p}'.format(q) == '$1000000'
        assert '{:#p}'.format(q) == '$1000000.0000'

        q=Quantity('f = 1e100 atoms')
        assert '{}'.format(q) == '10e99 atoms'
        assert '{:q}'.format(q) == '10e99 atoms'
        assert '{:r}'.format(q) == '10e99'
        assert '{:e}'.format(q) == '1e+100'
        assert '{:g}'.format(q) == '1e+100'

        q=Quantity('light = inf Hz -- a high frequency')
        assert '{}'.format(q) == 'inf Hz'
        assert '{:q}'.format(q) == 'inf Hz'
        assert '{:r}'.format(q) == 'inf'
        assert '{:f}'.format(q) == 'inf'
        assert '{:e}'.format(q) == 'inf'
        assert '{:g}'.format(q) == 'inf'
        assert '{:p}'.format(q) == 'inf Hz'

        # Negative numbers
        q=Quantity('f = -1420.405751786 MHz -- frequency of hydrogen line')
        assert '{}'.format(q) == '−1.4204 GHz'
        assert '{:q}'.format(q) == '−1.4204 GHz'
        assert '{:r}'.format(q) == '−1.4204G'
        assert '{:f}'.format(q) == '−1420405751.786'
        assert '{:e}'.format(q) == '−1.4204e+09'
        assert '{:g}'.format(q) == '−1.4204e+09'
        assert '{:p}'.format(q) == '−1420405751.786 Hz'
        assert '{:,p}'.format(q) == '−1,420,405,751.786 Hz'
        assert '{:#.3q}'.format(q) == '−1.420 GHz'
        assert '{:#p}'.format(q) == '−1420405751.7860 Hz'

        q=Quantity('Total = -$1000k -- a large amount of money')
        assert '{}'.format(q) == '−$1M'
        assert '{:q}'.format(q) == '−$1M'
        assert '{:r}'.format(q) == '−1M'
        assert '{:f}'.format(q) == '−1000000'
        assert '{:e}'.format(q) == '−1e+06'
        assert '{:g}'.format(q) == '−1e+06'
        assert '{:p}'.format(q) == '−$1000000'
        assert '{:#p}'.format(q) == '−$1000000.0000'

        q=Quantity('f = -1e-100 atoms')
        assert '{}'.format(q) == '−100e−102 atoms'
        assert '{:q}'.format(q) == '−100e−102 atoms'
        assert '{:r}'.format(q) == '−100e−102'
        assert '{:e}'.format(q) == '−1e−100'
        assert '{:g}'.format(q) == '−1e−100'

        q=Quantity('light = -inf Hz -- a high frequency')
        assert '{}'.format(q) == '−inf Hz'
        assert '{:q}'.format(q) == '−inf Hz'
        assert '{:r}'.format(q) == '−inf'
        assert '{:f}'.format(q) == '−inf'
        assert '{:e}'.format(q) == '−inf'
        assert '{:g}'.format(q) == '−inf'
        assert '{:p}'.format(q) == '−inf Hz'

    with Quantity.prefs(plus='', minus=Quantity.minus_sign):

        # Positive numbers
        q=Quantity('f = 1420.405751786 MHz -- frequency of hydrogen line')
        assert '{}'.format(q) == '1.4204 GHz'
        assert '{:q}'.format(q) == '1.4204 GHz'
        assert '{:r}'.format(q) == '1.4204G'
        assert '{:f}'.format(q) == '1420405751.786'
        assert '{:e}'.format(q) == '1.4204e09'
        assert '{:g}'.format(q) == '1.4204e09'
        assert '{:p}'.format(q) == '1420405751.786 Hz'
        assert '{:,p}'.format(q) == '1,420,405,751.786 Hz'
        assert '{:#.3q}'.format(q) == '1.420 GHz'
        assert '{:#p}'.format(q) == '1420405751.7860 Hz'

        q=Quantity('Total = $1000k -- a large amount of money')
        assert '{}'.format(q) == '$1M'
        assert '{:q}'.format(q) == '$1M'
        assert '{:r}'.format(q) == '1M'
        assert '{:f}'.format(q) == '1000000'
        assert '{:e}'.format(q) == '1e06'
        assert '{:g}'.format(q) == '1e06'
        assert '{:p}'.format(q) == '$1000000'
        assert '{:#p}'.format(q) == '$1000000.0000'

        q=Quantity('f = 1e100 atoms')
        assert '{}'.format(q) == '10e99 atoms'
        assert '{:q}'.format(q) == '10e99 atoms'
        assert '{:r}'.format(q) == '10e99'
        assert '{:e}'.format(q) == '1e100'
        assert '{:g}'.format(q) == '1e100'

        q=Quantity('light = inf Hz -- a high frequency')
        assert '{}'.format(q) == 'inf Hz'
        assert '{:q}'.format(q) == 'inf Hz'
        assert '{:r}'.format(q) == 'inf'
        assert '{:f}'.format(q) == 'inf'
        assert '{:e}'.format(q) == 'inf'
        assert '{:g}'.format(q) == 'inf'
        assert '{:p}'.format(q) == 'inf Hz'

        # Negative numbers
        q=Quantity('f = -1420.405751786 MHz -- frequency of hydrogen line')
        assert '{}'.format(q) == '−1.4204 GHz'
        assert '{:q}'.format(q) == '−1.4204 GHz'
        assert '{:r}'.format(q) == '−1.4204G'
        assert '{:f}'.format(q) == '−1420405751.786'
        assert '{:e}'.format(q) == '−1.4204e09'
        assert '{:g}'.format(q) == '−1.4204e09'
        assert '{:p}'.format(q) == '−1420405751.786 Hz'
        assert '{:,p}'.format(q) == '−1,420,405,751.786 Hz'
        assert '{:#.3q}'.format(q) == '−1.420 GHz'
        assert '{:#p}'.format(q) == '−1420405751.7860 Hz'

        q=Quantity('Total = -$1000k -- a large amount of money')
        assert '{}'.format(q) == '−$1M'
        assert '{:q}'.format(q) == '−$1M'
        assert '{:r}'.format(q) == '−1M'
        assert '{:f}'.format(q) == '−1000000'
        assert '{:e}'.format(q) == '−1e06'
        assert '{:g}'.format(q) == '−1e06'
        assert '{:p}'.format(q) == '−$1000000'
        assert '{:#p}'.format(q) == '−$1000000.0000'

        q=Quantity('f = -1e-100 atoms')
        assert '{}'.format(q) == '−100e−102 atoms'
        assert '{:q}'.format(q) == '−100e−102 atoms'
        assert '{:r}'.format(q) == '−100e−102'
        assert '{:e}'.format(q) == '−1e−100'
        assert '{:g}'.format(q) == '−1e−100'

        q=Quantity('light = -inf Hz -- a high frequency')
        assert '{}'.format(q) == '−inf Hz'
        assert '{:q}'.format(q) == '−inf Hz'
        assert '{:r}'.format(q) == '−inf'
        assert '{:f}'.format(q) == '−inf'
        assert '{:e}'.format(q) == '−inf'
        assert '{:g}'.format(q) == '−inf'
        assert '{:p}'.format(q) == '−inf Hz'
Exemplo n.º 16
0
def test_number_fmt():
    Quantity.set_prefs(spacer=None, show_label=None, label_fmt=None, label_fmt_full=None, show_desc=False)
    Quantity.set_prefs(prec=None)
    with Quantity.prefs(number_fmt='{whole:>3s}{frac:<4s} {units:<2s}'):
        assert '<{:s}>'.format(Quantity('1 mm')) ==     '<  1     mm>'
        assert '<{:s}>'.format(Quantity('10 mm')) ==    '< 10     mm>'
        assert '<{:s}>'.format(Quantity('100 mm')) ==   '<100     mm>'
        assert '<{:s}>'.format(Quantity('1.234 mm')) == '<  1.234 mm>'
        assert '<{:s}>'.format(Quantity('12.34 mm')) == '< 12.34  mm>'
        assert '<{:s}>'.format(Quantity('123.4 mm')) == '<123.4   mm>'

    with Quantity.prefs(number_fmt='{whole:>5s}{frac:<7s} {units:<6s}'):
        assert '<{:s}>'.format(Quantity('1 mm')) ==           '<    1        mm    >'
        assert '<{:s}>'.format(Quantity('10 mm')) ==          '<   10        mm    >'
        assert '<{:s}>'.format(Quantity('100 mm')) ==         '<  100        mm    >'
        assert '<{:s}>'.format(Quantity('1.234 mm')) ==       '<    1.234    mm    >'
        assert '<{:s}>'.format(Quantity('12.34 mm')) ==       '<   12.34     mm    >'
        assert '<{:s}>'.format(Quantity('123.4 mm')) ==       '<  123.4      mm    >'
        assert '<{:s}>'.format(Quantity('123.4 mmeter')) ==   '<  123.4      mmeter>'
        assert '<{:s}>'.format(Quantity('1e36 m')) ==         '<    1e36     m     >'
        assert '<{:s}>'.format(Quantity('10e36 m')) ==        '<   10e36     m     >'
        assert '<{:s}>'.format(Quantity('100e36 m')) ==       '<  100e36     m     >'
        assert '<{:s}>'.format(Quantity('1.234e36 m')) ==     '<    1.234e36 m     >'
        assert '<{:s}>'.format(Quantity('12.34e36 m')) ==     '<   12.34e36  m     >'
        assert '<{:s}>'.format(Quantity('123.4e36 m')) ==     '<  123.4e36   m     >'
        assert '<{:s}>'.format(Quantity('123.4e36 meter')) == '<  123.4e36   meter >'
        assert '<{:s}>'.format(Quantity('$1k')) ==            '<   $1        k     >'
        assert '<{:s}>'.format(Quantity('$10k')) ==           '<  $10        k     >'
        assert '<{:s}>'.format(Quantity('$100k')) ==          '< $100        k     >'
        assert '<{:s}>'.format(Quantity('$1.234k')) ==        '<   $1.234    k     >'
        assert '<{:s}>'.format(Quantity('$12.34k')) ==        '<  $12.34     k     >'
        assert '<{:s}>'.format(Quantity('$123.4k')) ==        '< $123.4      k     >'
        assert '<{:s}>'.format(Quantity('-$1k')) ==           '<  -$1        k     >'
        assert '<{:s}>'.format(Quantity('-$10k')) ==          '< -$10        k     >'
        assert '<{:s}>'.format(Quantity('-$100k')) ==         '<-$100        k     >'
        assert '<{:s}>'.format(Quantity('-$1.234k')) ==       '<  -$1.234    k     >'
        assert '<{:s}>'.format(Quantity('-$12.34k')) ==       '< -$12.34     k     >'
        assert '<{:s}>'.format(Quantity('-$123.4k')) ==       '<-$123.4      k     >'
        assert '<{:s}>'.format(Quantity('nan Hz')) ==         '<  NaN        Hz    >'
        assert '<{:s}>'.format(Quantity('inf Hz')) ==         '<  inf        Hz    >'

    with Quantity.prefs(number_fmt='{whole:>3s}{frac} {units}'):
        assert '<{:s}>'.format(Quantity('1 mm')) ==     '<  1 mm>'
        assert '<{:s}>'.format(Quantity('10 mm')) ==    '< 10 mm>'
        assert '<{:s}>'.format(Quantity('100 mm')) ==   '<100 mm>'
        assert '<{:s}>'.format(Quantity('1.234 mm')) == '<  1.234 mm>'
        assert '<{:s}>'.format(Quantity('12.34 mm')) == '< 12.34 mm>'
        assert '<{:s}>'.format(Quantity('123.4 mm')) == '<123.4 mm>'

    def fmt_num(whole, frac, units):
        return '{mantissa:>5s} {units}'.format(mantissa=whole+frac, units=units)

    with Quantity.prefs(number_fmt=fmt_num):
        assert '<{:s}>'.format(Quantity('1 mm')) ==     '<    1 mm>'
        assert '<{:s}>'.format(Quantity('10 mm')) ==    '<   10 mm>'
        assert '<{:s}>'.format(Quantity('100 mm')) ==   '<  100 mm>'
        assert '<{:s}>'.format(Quantity('1.234 mm')) == '<1.234 mm>'
        assert '<{:s}>'.format(Quantity('12.34 mm')) == '<12.34 mm>'
        assert '<{:s}>'.format(Quantity('123.4 mm')) == '<123.4 mm>'

    with Quantity.prefs(number_fmt='{whole:>3s}{frac:<4s} {units:<2s}', radix=',', comma='.'):
        assert '<{:s}>'.format(Quantity('1 mm')) ==     '<  1     mm>'
        assert '<{:s}>'.format(Quantity('10 mm')) ==    '< 10     mm>'
        assert '<{:s}>'.format(Quantity('100 mm')) ==   '<100     mm>'
        assert '<{:s}>'.format(Quantity('1,234 mm')) == '<  1,234 mm>'
        assert '<{:s}>'.format(Quantity('12,34 mm')) == '< 12,34  mm>'
        assert '<{:s}>'.format(Quantity('123,4 mm')) == '<123,4   mm>'
Exemplo n.º 17
0
def test_negligible():
    Quantity.set_prefs(spacer=None,
                       show_label=None,
                       label_fmt=None,
                       label_fmt_full=None)
    pn = Quantity('1nV')
    nn = Quantity('-1nV')
    pf = Quantity('1fV')
    nf = Quantity('-1fV')
    assert pn.render() == '1 nV'
    assert nn.render() == '-1 nV'
    assert pf.render() == '1 fV'
    assert nf.render() == '-1 fV'
    assert pn.render(negligible=1e-12) == '1 nV'
    assert nn.render(negligible=1e-12) == '-1 nV'
    assert pf.render(negligible=1e-12) == '0 V'
    assert nf.render(negligible=1e-12) == '0 V'
    with Quantity.prefs(negligible=1e-12):
        assert pn.render() == '1 nV'
        assert nn.render() == '-1 nV'
        assert pf.render() == '0 V'
        assert nf.render() == '0 V'
        assert repr(pn) == "Quantity('1 nV')"
        assert repr(nn) == "Quantity('-1 nV')"
        assert repr(pf) == "Quantity('1 fV')"
        assert repr(nf) == "Quantity('-1 fV')"
        assert pn.render(negligible=1e-6) == '0 V'
        assert nn.render(negligible=1e-6) == '0 V'
        assert pf.render(negligible=1e-6) == '0 V'
        assert nf.render(negligible=1e-6) == '0 V'

    q = Quantity('-0')
    assert q.render() == '-0'
    assert q.render(negligible=0) == '0'

    v = Quantity('1nV')
    c = Quantity('1fA')
    f = Quantity('1mHz')
    k = Quantity('k')
    u = Quantity(1e-9)
    with Quantity.prefs():
        assert v.render() == '1 nV'
        assert c.render() == '1 fA'
        assert f.render() == '1 mHz'
        assert u.render() == '1n'
        assert k.render() == '13.806e-24 J/K'
    with Quantity.prefs(negligible=1e-6):
        assert v.render() == '0 V'
        assert c.render() == '0 A'
        assert f.render() == '1 mHz'
        assert u.render() == '0'
        assert k.render() == '0 J/K'
    with Quantity.prefs(negligible=dict(V=1e-6, A=1e-12, Hz=1)):
        assert v.render() == '0 V'
        assert c.render() == '0 A'
        assert f.render() == '0 Hz'
        assert u.render() == '1n'
        assert k.render() == '13.806e-24 J/K'
    with Quantity.prefs(negligible={
            'V': 1e-6,
            'A': 1e-12,
            'Hz': 1,
            None: 1e-12
    }):
        assert v.render() == '0 V'
        assert c.render() == '0 A'
        assert f.render() == '0 Hz'
        assert u.render() == '1n'
        assert k.render() == '0 J/K'
    with Quantity.prefs(negligible={
            'V': 1e-6,
            'A': 1e-12,
            'Hz': 1,
            None: 1e-6
    }):
        assert v.render() == '0 V'
        assert c.render() == '0 A'
        assert f.render() == '0 Hz'
        assert u.render() == '0'
        assert k.render() == '0 J/K'
    with Quantity.prefs(negligible={
            'V': 1e-6,
            'A': 1e-12,
            'Hz': 1,
            '': 1e-10,
            None: 1e-12
    }):
        assert v.render() == '0 V'
        assert c.render() == '0 A'
        assert f.render() == '0 Hz'
        assert u.render() == '1n'
        assert k.render() == '0 J/K'
    with Quantity.prefs(negligible={
            'V': 1e-6,
            'A': 1e-12,
            'Hz': 1,
            '': 1e-6,
            None: 1e-12
    }):
        assert v.render() == '0 V'
        assert c.render() == '0 A'
        assert f.render() == '0 Hz'
        assert u.render() == '0'
        assert k.render() == '0 J/K'

    given = 'Pass @ 3.40000006e-03s: V(atb) voltage: expected=0.00000000e+00V, measured=-8.60793065e-76V, diff=8.60793065e-76V.'
    expected = 'Pass @ 3.4 ms: V(atb) voltage: expected=0 V, measured=-860.79e-78 V, diff=860.79e-78 V.'
    got = Quantity.all_from_conv_fmt(given)
    assert got == expected

    expected = 'Pass @ 3.4 ms: V(atb) voltage: expected=0 V, measured=0 V, diff=0 V.'
    got = Quantity.all_from_conv_fmt(given, negligible=1e-12)
    assert got == expected
Exemplo n.º 18
0
def test_misc2():
    class Foo(Quantity):
        pass

    Foo.set_prefs(assign_rec=r'(?P<name>\w+)\s*=\s*(?P<val>.*)')
    q = Foo('seven = 7')
    assert q.name == 'seven'
    assert str(q) == '7'
    with pytest.raises(ValueError) as exception:
        q = Foo('%')
    assert str(exception.value) == '%: not a valid number.'
    assert isinstance(exception.value, InvalidNumber)
    assert isinstance(exception.value, QuantiPhyError)
    assert isinstance(exception.value, ValueError)
    assert exception.value.args == ('%', )
    assert exception.value.render(
        template='bad number given ({!r})') == "bad number given ('%')"
    assert exception.value.render(
        template='bad number given') == "%: bad number given"
    # the following is not kosher, but it should work
    exception.value._template = 'bad number ({!r})'
    assert str(exception.value) == "bad number ('%')"
    assert repr(exception.value) == "InvalidNumber('%')"
    with pytest.raises(ValueError):
        exception.value.render(template=['{} {}', '{} {} {}'])
    with pytest.raises(ValueError):
        exception.value.render(template=['{a} {b}', '{a} {b} {c}'])

    with pytest.raises(KeyError) as exception:
        Foo.set_prefs(assign_rec=r'(\w+)\s*=\s*(.*)')  # no named groups
        Foo('seven = 7')
    assert str(exception.value) == "recognizer does not contain 'val' key."
    assert isinstance(exception.value, InvalidRecognizer)
    assert isinstance(exception.value, QuantiPhyError)
    assert isinstance(exception.value, KeyError)
    assert exception.value.args == ()

    assert Foo.get_pref('prec') == 4
    assert Foo.get_pref('full_prec') == 12
    with Foo.prefs(prec=5, full_prec=13):
        assert Foo.get_pref('prec') == 5
        assert Foo.get_pref('full_prec') == 13
        with Foo.prefs(prec=6, full_prec=14):
            assert Foo.get_pref('prec') == 6
            assert Foo.get_pref('full_prec') == 14
        assert Foo.get_pref('prec') == 5
        assert Foo.get_pref('full_prec') == 13
    assert Foo.get_pref('prec') == 4
    assert Foo.get_pref('full_prec') == 12

    q = Quantity('1.8_V')
    assert q.render(prec='full') == '1.8 V'

    with pytest.raises(ValueError) as exception:
        q = Quantity('x*y = z')
    assert str(exception.value) == 'z: not a valid number.'
    assert isinstance(exception.value, InvalidNumber)
    assert isinstance(exception.value, QuantiPhyError)
    assert isinstance(exception.value, ValueError)
    assert exception.value.args == ('z', )

    # this used to be an ValueError because 'x*y' is not an identifier
    vals = Quantity.extract('x*y = 1 m/s')
    assert str(vals['x*y']) == '1 m/s'

    # this used to be an ValueError because 'in' is a python keyword
    vals = Quantity.extract('in = 1mA')
    assert str(vals['in']) == '1 mA'

    with pytest.raises(ValueError) as exception:
        Quantity('x\ny = z')
    assert str(exception.value) == 'z: not a valid number.'
    assert isinstance(exception.value, InvalidNumber)
    assert isinstance(exception.value, QuantiPhyError)
    assert isinstance(exception.value, ValueError)
    assert exception.value.args == ('z', )

    Quantity.set_prefs(label_fmt='{x}')
    with pytest.raises(KeyError) as exception:
        '{:S}'.format(Quantity('f = 1kHz'))
    assert str(exception.value) == 'x: unknown format key.'
    assert isinstance(exception.value, UnknownFormatKey)
    assert isinstance(exception.value, QuantiPhyError)
    assert isinstance(exception.value, KeyError)
    assert exception.value.args == ('x', )

    Quantity.set_prefs(label_fmt_full='{n} = {v}  # {d}',
                       label_fmt='{n} = {v}',
                       show_desc=True)
    q1 = Quantity('10ns', name='trise')
    q2 = Quantity('10ns', name='trise', desc='rise time')
    assert '{:G}'.format(q1) == 'trise = 1e-08'
    assert '{:G}'.format(q2) == 'trise = 1e-08  # rise time'

    q3 = Quantity('10cm', name='foo')
    q4 = Quantity('10%', name='bar', desc='buzz')
    assert '{:G}'.format(q3) == 'foo = 0.1'
    assert '{:G}'.format(q4) == 'bar = 10  # buzz'
    assert '{:S}'.format(q4) == 'bar = 10%  # buzz'

    class Derived(Quantity):
        pass

    Derived.set_prefs(prec=8)
    mu = Derived('mu0')
    assert mu.render() == '1.25663706 uH/m'
    Derived.set_prefs(prec=None)
    assert mu.render() == '1.2566 uH/m'

    q = Quantity('Tclk = 10ns -- clock period')
    assert q.render(show_label=True) == 'Tclk = 10 ns  # clock period'

    q = Quantity('Tclk = 10ns')
    assert q.render(show_label=True) == 'Tclk = 10 ns'
    assert q.is_close(1e-8) is True
    assert q.is_close(1.001e-8) is False

    add_constant(
        Quantity('F_hy = 1420405751.786 Hz -- frequency of hydrogen line'))
    h_line = Quantity('F_hy')
    assert h_line.render(
        show_label=True) == 'F_hy = 1.4204 GHz  # frequency of hydrogen line'

    h_line2 = Quantity(h_line, h_line)
    assert h_line2.render(
        show_label=True) == 'F_hy = 1.4204 GHz  # frequency of hydrogen line'

    h_line3 = Quantity(1 * h_line, h_line)
    assert h_line3.render(show_label=True) == '1.4204 GHz'

    h_line4 = Quantity(1420405751.786, 'F_hy Hz frequency of hydrogen line')
    assert h_line4.render(
        show_label=True) == 'F_hy = 1.4204 GHz  # frequency of hydrogen line'

    size = Quantity('100k', 'B')
    assert size.render() == '100 kB'

    f1 = Quantity('1GHz')
    f2 = Quantity('1GOhms')
    assert f1.is_close(f1) is True
    assert f1.is_close(f2) is False
    assert f1.is_close(f1 + 1) is True
    assert f1.is_close(f1 + 1e6) is False

    p = Quantity('3_1_4_1.592_65_36mRads')
    assert p.render() == '3.1416 Rads'

    Quantity.set_prefs(known_units='au pc')
    d1 = Quantity('1 au')
    d2 = Quantity('1000 pc')
    assert d1.render(form='eng') == '1 au'
    assert d2.render() == '1 kpc'

    p = Quantity.get_pref(name='known_units')
    assert ' '.join(p) == 'au pc'

    if sys.version_info.major == 3:

        class Foo(Quantity):
            pass

        t = Foo('1us')

        assert Foo.get_pref('map_sf') == {}
        assert Quantity.get_pref('map_sf') == {}

        Foo.set_prefs(map_sf=Foo.map_sf_to_greek)
        assert t.render() == '1 µs'
        assert Foo.get_pref('map_sf') == Foo.map_sf_to_greek
        assert Quantity.get_pref('map_sf') == {}

        Foo.set_prefs(map_sf=Quantity.map_sf_to_sci_notation)
        assert t.render(form='eng') == '1×10⁻⁶ s'
        assert t.render(form='si') == '1 µs'
        assert Foo.get_pref('map_sf') == Foo.map_sf_to_sci_notation
        assert Quantity.get_pref('map_sf') == {}

    Quantity.set_prefs(label_fmt_full='{V:<18}  # {d}',
                       label_fmt='{n} = {v}',
                       show_desc=True)
    T = Quantity('T = 300K -- ambient temperature', ignore_sf=True)
    k = Quantity('k')
    q = Quantity('q')
    Vt = Quantity(k * T / q, 'Vt V thermal voltage')
    result = '{:S}\n{:S}\n{:S}\n{:S}'.format(T, k, q, Vt)
    expected = dedent("""
        T = 300 K           # ambient temperature
        k = 13.806e-24 J/K  # Boltzmann's constant
        q = 160.22e-21 C    # elementary charge
        Vt = 25.852 mV      # thermal voltage
    """).strip()
    assert result == expected

    result = '{:Q}\n{:R}\n{:E}\n{:G}'.format(T, k, q, Vt)
    expected = dedent("""
        T = 300 K           # ambient temperature
        k = 13.806e-24      # Boltzmann's constant
        q = 1.6022e-19      # elementary charge
        Vt = 0.025852       # thermal voltage
    """).strip()
    assert result == expected

    Quantity.set_prefs(label_fmt_full='{V:<18}  # {d}',
                       label_fmt='{n}: {v}',
                       show_desc=True)
    result = '{:S}\n{:S}\n{:S}\n{:S}'.format(T, k, q, Vt)
    expected = dedent("""
        T: 300 K            # ambient temperature
        k: 13.806e-24 J/K   # Boltzmann's constant
        q: 160.22e-21 C     # elementary charge
        Vt: 25.852 mV       # thermal voltage
    """).strip()
    assert result == expected

    processed = Quantity.all_from_conv_fmt('1420405751.786Hz', form='si')
    assert processed == '1.4204 GHz'
    processed = Quantity.all_from_conv_fmt('1.420405751786e9Hz', form='si')
    assert processed == '1.4204 GHz'
    processed = Quantity.all_from_si_fmt('1420.405751786MHz', form='eng')
    assert processed == '1.4204e9 Hz'
    processed = Quantity.all_from_si_fmt('1420405751.786_Hz', form='eng')
    assert processed == '1.4204e9 Hz'

    if sys.version_info.major == 3:
        # spacer is non-breaking space
        processed = Quantity.all_from_conv_fmt('1420405751.786 Hz', form='si')
        assert processed == '1.4204 GHz'

        q = Quantity('3.45e6 m·s⁻²')
        assert q.render() == '3.45 Mm·s⁻²'
        q = Quantity('accel = 3.45e6 m·s⁻² -- acceleration')
        assert q.render() == '3.45 Mm·s⁻²'

    processed = Quantity.all_from_si_fmt('0s', form='si')
    assert processed == '0 s'

    # test input_sf
    Quantity.set_prefs(input_sf='GMk', unity_sf='_', spacer='')
    assert Quantity('10m').render(form='eng') == '10_m'
    Quantity.set_prefs(input_sf=None, unity_sf='_')
    assert Quantity('10m').render(form='eng') == '10e-3'
    with pytest.raises(ValueError) as exception:
        Quantity.set_prefs(input_sf='GMkwq', unity_sf='_', spacer='')
    assert str(exception.value) == 'q, w: unknown scale factors.'
    assert isinstance(exception.value, UnknownScaleFactor)
    assert isinstance(exception.value, QuantiPhyError)
    assert isinstance(exception.value, ValueError)
    assert exception.value.args == ('q', 'w')
    assert repr(exception.value) == "UnknownScaleFactor('q', 'w')"
    exception.value.render('{}, {}: unknown') == 'q, w: unknown'

    Quantity.set_prefs(input_sf=None, unity_sf=None, spacer=None)
    assert Quantity('10m').render(form='eng') == '10e-3'

    Quantity.input_sf = 'GMkwq'
    with pytest.raises(ValueError) as exception:
        Quantity('10m')
    assert str(exception.value) == 'q, w: unknown scale factors.'
    assert isinstance(exception.value, UnknownScaleFactor)
    assert isinstance(exception.value, QuantiPhyError)
    assert isinstance(exception.value, ValueError)
    assert exception.value.args == ('q', 'w')
    assert repr(exception.value) == "UnknownScaleFactor('q', 'w')"
    exception.value.render('{}, {}: unknown') == 'q, w: unknown'

    del Quantity.input_sf

    # test map_sf
    if sys.version_info.major == 3:
        Quantity.set_prefs(map_sf=Quantity.map_sf_to_greek)
        assert Quantity('10e-6 m').render() == '10 µm'
        Quantity.set_prefs(map_sf=Quantity.map_sf_to_sci_notation)
        assert Quantity('10e-6 m').render() == '10 µm'
        assert Quantity('10e-6 m').render(form='eng') == '10×10⁻⁶ m'
        Quantity.set_prefs(map_sf=None)
    sf_map = {
        'u': ' PPM',
        'n': ' PPB',
        'p': ' PPT',
        'f': ' PPQ',
    }
    with Quantity.prefs(map_sf=sf_map):
        assert Quantity('10e-6').render() == '10 PPM'
        assert Quantity('1e-7').render() == '100 PPB'
        assert Quantity('1e-12').render() == '1 PPT'
        assert Quantity('1e-13').render() == '100 PPQ'

    # test set_prefs error handling
    with pytest.raises(KeyError) as exception:
        Quantity.set_prefs(fuzz=True)
    assert exception.value.args[0] == 'fuzz'
    with pytest.raises(KeyError) as exception:
        fuzz = Quantity.get_pref('fuzz')
    assert str(exception.value) == 'fuzz: unknown preference.'
    assert isinstance(exception.value, UnknownPreference)
    assert isinstance(exception.value, QuantiPhyError)
    assert isinstance(exception.value, KeyError)
    assert exception.value.args == ('fuzz', )

    c = Quantity('c')
    Quantity.set_prefs(label_fmt=None, label_fmt_full=None)
    Quantity.set_prefs(show_label=False, show_desc=False)
    assert str(c) == '299.79 Mm/s'
    assert '{:s}'.format(c) == '299.79 Mm/s'
    assert '{:S}'.format(c) == 'c = 299.79 Mm/s'
    assert c.render() == '299.79 Mm/s'
    assert c.render(show_label=False) == '299.79 Mm/s'
    assert c.render(show_label=True) == 'c = 299.79 Mm/s'
    assert c.render(show_label='f') == 'c = 299.79 Mm/s -- speed of light'
    assert c.render(show_label='a') == 'c = 299.79 Mm/s'
    Quantity.set_prefs(show_label=True)
    assert str(c) == 'c = 299.79 Mm/s'
    assert '{:s}'.format(c) == '299.79 Mm/s'
    assert '{:S}'.format(c) == 'c = 299.79 Mm/s'
    assert c.render() == 'c = 299.79 Mm/s'
    assert c.render(show_label=False) == '299.79 Mm/s'
    assert c.render(show_label=True) == 'c = 299.79 Mm/s'
    assert c.render(show_label='f') == 'c = 299.79 Mm/s -- speed of light'
    assert c.render(show_label='a') == 'c = 299.79 Mm/s'
    Quantity.set_prefs(show_label='f')
    assert str(c) == 'c = 299.79 Mm/s -- speed of light'
    assert '{:s}'.format(c) == '299.79 Mm/s'
    assert '{:S}'.format(c) == 'c = 299.79 Mm/s -- speed of light'
    assert c.render() == 'c = 299.79 Mm/s -- speed of light'
    assert c.render(show_label=False) == '299.79 Mm/s'
    assert c.render(show_label=True) == 'c = 299.79 Mm/s -- speed of light'
    assert c.render(show_label='f') == 'c = 299.79 Mm/s -- speed of light'
    assert c.render(show_label='a') == 'c = 299.79 Mm/s'

    Quantity.set_prefs(label_fmt='{n}: {v}', label_fmt_full='{n}: {v} -- {d}')
    Quantity.set_prefs(show_label=False, show_desc=False)
    assert str(c) == '299.79 Mm/s'
    assert '{:s}'.format(c) == '299.79 Mm/s'
    assert '{:S}'.format(c) == 'c: 299.79 Mm/s'
    assert c.render() == '299.79 Mm/s'
    assert c.render(show_label=False) == '299.79 Mm/s'
    assert c.render(show_label=True) == 'c: 299.79 Mm/s'
    assert c.render(show_label='f') == 'c: 299.79 Mm/s -- speed of light'
    assert c.render(show_label='a') == 'c: 299.79 Mm/s'
    Quantity.set_prefs(show_label=True)
    assert str(c) == 'c: 299.79 Mm/s'
    assert '{:s}'.format(c) == '299.79 Mm/s'
    assert '{:S}'.format(c) == 'c: 299.79 Mm/s'
    assert c.render() == 'c: 299.79 Mm/s'
    assert c.render(show_label=False) == '299.79 Mm/s'
    assert c.render(show_label=True) == 'c: 299.79 Mm/s'
    assert c.render(show_label='f') == 'c: 299.79 Mm/s -- speed of light'
    assert c.render(show_label='a') == 'c: 299.79 Mm/s'
    Quantity.set_prefs(show_label='f')
    assert str(c) == 'c: 299.79 Mm/s -- speed of light'
    assert '{:s}'.format(c) == '299.79 Mm/s'
    assert '{:S}'.format(c) == 'c: 299.79 Mm/s -- speed of light'
    assert c.render() == 'c: 299.79 Mm/s -- speed of light'
    assert c.render(show_label=False) == '299.79 Mm/s'
    assert c.render(show_label=True) == 'c: 299.79 Mm/s -- speed of light'
    assert c.render(show_label='f') == 'c: 299.79 Mm/s -- speed of light'
    assert c.render(show_label='a') == 'c: 299.79 Mm/s'

    Quantity.set_prefs(label_fmt='{n}: {v}', label_fmt_full='{V} // {d}')
    Quantity.set_prefs(show_label=False, show_desc=True)
    assert str(c) == '299.79 Mm/s'
    assert '{:s}'.format(c) == '299.79 Mm/s'
    assert '{:S}'.format(c) == 'c: 299.79 Mm/s // speed of light'
    assert c.render() == '299.79 Mm/s'
    assert c.render(show_label=False) == '299.79 Mm/s'
    assert c.render(show_label=True) == 'c: 299.79 Mm/s // speed of light'
    assert c.render(show_label='f') == 'c: 299.79 Mm/s // speed of light'
    assert c.render(show_label='a') == 'c: 299.79 Mm/s'
    Quantity.set_prefs(show_label=True)
    assert str(c) == 'c: 299.79 Mm/s // speed of light'
    assert '{:s}'.format(c) == '299.79 Mm/s'
    assert '{:S}'.format(c) == 'c: 299.79 Mm/s // speed of light'
    assert c.render() == 'c: 299.79 Mm/s // speed of light'
    assert c.render(show_label=False) == '299.79 Mm/s'
    assert c.render(show_label=True) == 'c: 299.79 Mm/s // speed of light'
    assert c.render(show_label='f') == 'c: 299.79 Mm/s // speed of light'
    assert c.render(show_label='a') == 'c: 299.79 Mm/s'
    Quantity.set_prefs(show_label='f')
    assert str(c) == 'c: 299.79 Mm/s // speed of light'
    assert '{:s}'.format(c) == '299.79 Mm/s'
    assert '{:S}'.format(c) == 'c: 299.79 Mm/s // speed of light'
    assert c.render() == 'c: 299.79 Mm/s // speed of light'
    assert c.render(show_label=False) == '299.79 Mm/s'
    assert c.render(show_label=True) == 'c: 299.79 Mm/s // speed of light'
    assert c.render(show_label='f') == 'c: 299.79 Mm/s // speed of light'
    assert c.render(show_label='a') == 'c: 299.79 Mm/s'
Exemplo n.º 19
0
def test_misc():
    Quantity.set_prefs(spacer=None,
                       show_label=None,
                       label_fmt=None,
                       label_fmt_full=None)
    q = Quantity(1420405751.786, 'Hz')
    assert q.render(show_si=False, show_units=False) == '1.4204e9'

    t = Quantity('1420405751.786 Hz').as_tuple()
    assert t == (1420405751.786, 'Hz')

    t = Quantity('1420405751.786 Hz').render(show_si=True,
                                             show_units=True,
                                             prec='full')
    assert t == '1.420405751786 GHz'

    s = Quantity('1420405751.786 Hz').render(show_si=False,
                                             show_units=True,
                                             prec='full')
    assert s == '1.420405751786e9 Hz'

    f = float(Quantity('1420405751.786 Hz'))
    assert f == 1420405751.786

    t = Quantity('1420405751.786 Hz').render(show_si=True, show_units=False)
    assert t == '1.4204G'

    s = Quantity('1420405751.786 Hz').render(show_si=False, show_units=False)
    assert s == '1.4204e9'

    s = Quantity(1420405751.786, 'Hz').render(show_si=False,
                                              show_units=False,
                                              prec='full')
    assert s == '1.420405751786e9'

    f = Quantity('14204.05751786MHz').render(show_si=True,
                                             show_units=False,
                                             prec='full')
    assert f == '14.20405751786G'

    q = Quantity('1420405751.786 Hz', units='HZ').render()
    assert q == '1.4204 GHZ'

    q = Quantity('1420405751.786 Hz')
    assert q.is_nan() == False

    q = Quantity('1420405751.786 Hz')
    assert q.is_infinite() == False

    q = Quantity('NaN Hz')
    assert q.is_nan() == True

    q = Quantity('NaN Hz')
    assert q.is_infinite() == False

    q = Quantity('inf Hz')
    assert q.is_nan() == False

    q = Quantity('inf Hz')
    assert q.is_infinite() == True

    # check the various formats for assignment recognition
    q = Quantity('f_hy = 1420405751.786 Hz -- frequency of hydrogen line')
    assert q.render(
        show_label='f') == 'f_hy = 1.4204 GHz -- frequency of hydrogen line'
    assert q.name == 'f_hy'
    assert q.desc == 'frequency of hydrogen line'

    q = Quantity('f_hy: 1420405751.786 Hz # frequency of hydrogen line')
    assert q.render(
        show_label='f') == 'f_hy = 1.4204 GHz -- frequency of hydrogen line'
    assert q.name == 'f_hy'
    assert q.desc == 'frequency of hydrogen line'

    q = Quantity('f_hy = 1420405751.786 Hz // frequency of hydrogen line')
    assert q.render(
        show_label='f') == 'f_hy = 1.4204 GHz -- frequency of hydrogen line'
    assert q.name == 'f_hy'
    assert q.desc == 'frequency of hydrogen line'

    q = Quantity('f_hy = 1420405751.786 Hz')
    assert q.render(show_label='f') == 'f_hy = 1.4204 GHz'
    assert q.name == 'f_hy'
    assert q.desc == ''

    q = Quantity('1420405751.786 Hz // frequency of hydrogen line')
    assert q.render(show_label='f') == '1.4204 GHz'
    assert q.name == ''
    assert q.desc == 'frequency of hydrogen line'

    q = Quantity('1420405751.786 Hz')
    assert q.render(show_label='f') == '1.4204 GHz'
    assert q.name == ''
    assert q.desc == ''

    class Foo(Quantity):
        pass

    Foo.set_prefs(assign_rec=r'(?P<name>\w+)\s*=\s*(?P<val>.*)')
    q = Foo('seven = 7')
    assert q.name == 'seven'
    assert str(q) == '7'
    with pytest.raises(ValueError):
        q = Foo('%')
    with pytest.raises(KeyError):
        Foo.set_prefs(assign_rec=r'(\w+)\s*=\s*(.*)')  # no named groups
        Foo('seven = 7')

    assert Foo.get_pref('prec') == 4
    assert Foo.get_pref('full_prec') == 12
    with Foo.prefs(prec=5, full_prec=13):
        assert Foo.get_pref('prec') == 5
        assert Foo.get_pref('full_prec') == 13
        with Foo.prefs(prec=6, full_prec=14):
            assert Foo.get_pref('prec') == 6
            assert Foo.get_pref('full_prec') == 14
        assert Foo.get_pref('prec') == 5
        assert Foo.get_pref('full_prec') == 13
    assert Foo.get_pref('prec') == 4
    assert Foo.get_pref('full_prec') == 12

    q = Quantity('1.8_V')
    assert q.render(prec='full') == '1.8 V'

    with pytest.raises(ValueError):
        q = Quantity('x*y = z')

    with pytest.raises(ValueError):
        Quantity.extract('1ns')

    # this used to be an ValueError because 'x*y' is not an identifier
    vals = Quantity.extract('x*y = 1 m/s')
    assert str(vals['x*y']) == '1 m/s'

    # this used to be an ValueError because 'in' is a python keyword
    vals = Quantity.extract('in = 1mA')
    assert str(vals['in']) == '1 mA'

    with pytest.raises(ValueError):
        Quantity('x\ny = z')

    Quantity.set_prefs(label_fmt='{x}')
    with pytest.raises(KeyError):
        '{:S}'.format(Quantity('f = 1kHz'))

    Quantity.set_prefs(label_fmt_full='{n} = {v}  # {d}',
                       label_fmt='{n} = {v}',
                       show_desc=True)
    q1 = Quantity('10ns', name='trise')
    q2 = Quantity('10ns', name='trise', desc='rise time')
    assert '{:G}'.format(q1) == 'trise = 1e-08'
    assert '{:G}'.format(q2) == 'trise = 1e-08  # rise time'

    q3 = Quantity('10cm', name='foo')
    q4 = Quantity('10%', name='bar', desc='buzz')
    assert '{:G}'.format(q3) == 'foo = 0.1'
    assert '{:G}'.format(q4) == 'bar = 10  # buzz'
    assert '{:S}'.format(q4) == 'bar = 10 %  # buzz'

    class Derived(Quantity):
        pass

    Derived.set_prefs(prec=8)
    mu = Derived('mu0')
    assert mu.render() == '1.25663706 uH/m'
    Derived.set_prefs(prec=None)
    assert mu.render() == '1.2566 uH/m'

    q = Quantity('Tclk = 10ns -- clock period')
    assert q.render(show_label=True) == 'Tclk = 10 ns  # clock period'

    q = Quantity('Tclk = 10ns')
    assert q.render(show_label=True) == 'Tclk = 10 ns'
    assert q.is_close(1e-8) is True
    assert q.is_close(1.001e-8) is False

    add_constant(
        Quantity('F_hy = 1420405751.786 Hz -- frequency of hydrogen line'))
    h_line = Quantity('F_hy')
    assert h_line.render(
        show_label=True) == 'F_hy = 1.4204 GHz  # frequency of hydrogen line'

    h_line2 = Quantity(h_line, h_line)
    assert h_line2.render(
        show_label=True) == 'F_hy = 1.4204 GHz  # frequency of hydrogen line'

    h_line3 = Quantity(1 * h_line, h_line)
    assert h_line3.render(show_label=True) == '1.4204 GHz'

    h_line4 = Quantity(1420405751.786, 'F_hy Hz frequency of hydrogen line')
    assert h_line4.render(
        show_label=True) == 'F_hy = 1.4204 GHz  # frequency of hydrogen line'

    size = Quantity('100k', 'B')
    assert size.render() == '100 kB'

    f1 = Quantity('1GHz')
    f2 = Quantity('1GOhms')
    assert f1.is_close(f1) == True
    assert f1.is_close(f2) == False
    assert f1.is_close(f1 + 1) == True
    assert f1.is_close(f1 + 1e6) == False

    p = Quantity('3_1_4_1.592_65_36mRads')
    assert p.render() == '3.1416 Rads'

    Quantity.set_prefs(known_units='au pc')
    d1 = Quantity('1 au')
    d2 = Quantity('1000 pc')
    assert d1.render(show_si=False) == '1 au'
    assert d2.render() == '1 kpc'

    p = Quantity.get_pref(name='known_units')
    assert ' '.join(p) == 'au pc'

    if sys.version_info.major == 3:

        class Foo(Quantity):
            pass

        t = Foo('1us')

        assert Foo.get_pref('map_sf') == {}
        assert Quantity.get_pref('map_sf') == {}

        Foo.set_prefs(map_sf=Foo.map_sf_to_greek)
        assert t.render() == '1 μs'
        assert Foo.get_pref('map_sf') == Foo.map_sf_to_greek
        assert Quantity.get_pref('map_sf') == {}

        Foo.set_prefs(map_sf=Quantity.map_sf_to_sci_notation)
        assert t.render(show_si=False) == '1×10⁻⁶ s'
        assert Foo.get_pref('map_sf') == Foo.map_sf_to_sci_notation
        assert Quantity.get_pref('map_sf') == {}

    Quantity.set_prefs(label_fmt_full='{V:<18}  # {d}',
                       label_fmt='{n} = {v}',
                       show_desc=True)
    T = Quantity('T = 300K -- ambient temperature', ignore_sf=True)
    k = Quantity('k')
    q = Quantity('q')
    Vt = Quantity(k * T / q, 'Vt V thermal voltage')
    result = '{:S}\n{:S}\n{:S}\n{:S}'.format(T, k, q, Vt)
    expected = dedent("""
        T = 300 K           # ambient temperature
        k = 13.806e-24 J/K  # Boltzmann's constant
        q = 160.22e-21 C    # elementary charge
        Vt = 25.852 mV      # thermal voltage
    """).strip()
    assert result == expected

    result = '{:Q}\n{:R}\n{:E}\n{:G}'.format(T, k, q, Vt)
    expected = dedent("""
        T = 300 K           # ambient temperature
        k = 13.806e-24      # Boltzmann's constant
        q = 1.6022e-19      # elementary charge
        Vt = 0.025852       # thermal voltage
    """).strip()
    assert result == expected

    Quantity.set_prefs(label_fmt_full='{V:<18}  # {d}',
                       label_fmt='{n}: {v}',
                       show_desc=True)
    result = '{:S}\n{:S}\n{:S}\n{:S}'.format(T, k, q, Vt)
    expected = dedent("""
        T: 300 K            # ambient temperature
        k: 13.806e-24 J/K   # Boltzmann's constant
        q: 160.22e-21 C     # elementary charge
        Vt: 25.852 mV       # thermal voltage
    """).strip()
    assert result == expected

    processed = Quantity.all_from_conv_fmt('1420405751.786Hz', show_si=True)
    assert processed == '1.4204 GHz'
    processed = Quantity.all_from_conv_fmt('1.420405751786e9Hz', show_si=True)
    assert processed == '1.4204 GHz'
    processed = Quantity.all_from_si_fmt('1420.405751786MHz', show_si=False)
    assert processed == '1.4204e9 Hz'
    processed = Quantity.all_from_si_fmt('1420405751.786_Hz', show_si=False)
    assert processed == '1.4204e9 Hz'

    if sys.version_info.major == 3:
        # spacer is non-breaking space
        processed = Quantity.all_from_conv_fmt('1420405751.786 Hz',
                                               show_si=True)
        assert processed == '1.4204 GHz'

        q = Quantity('3.45e6 m·s⁻²')
        assert q.render() == '3.45 Mm·s⁻²'
        q = Quantity('accel = 3.45e6 m·s⁻² -- acceleration')
        assert q.render() == '3.45 Mm·s⁻²'

    processed = Quantity.all_from_si_fmt('0s', show_si=True)
    assert processed == '0 s'

    # test input_sf
    Quantity.set_prefs(input_sf='GMk', unity_sf='_', spacer='')
    assert Quantity('10m').render(show_si=False) == '10_m'
    Quantity.set_prefs(input_sf=None, unity_sf='_')
    assert Quantity('10m').render(show_si=False) == '10e-3'
    with pytest.raises(ValueError):
        Quantity.set_prefs(input_sf='GMkwq', unity_sf='_', spacer='')
    Quantity.set_prefs(input_sf=None, unity_sf=None, spacer=None)

    # test map_sf
    if sys.version_info.major == 3:
        Quantity.set_prefs(map_sf=Quantity.map_sf_to_greek)
        assert Quantity('10e-6 m').render() == '10 μm'
        Quantity.set_prefs(map_sf=Quantity.map_sf_to_sci_notation)
        assert Quantity('10e-6 m').render() == '10 μm'
        assert Quantity('10e-6 m').render(show_si=False) == '10×10⁻⁶ m'
        Quantity.set_prefs(map_sf=None)
    sf_map = {
        'u': ' PPM',
        'n': ' PPB',
        'p': ' PPT',
        'f': ' PPQ',
    }
    with Quantity.prefs(map_sf=sf_map):
        assert Quantity('10e-6').render() == '10 PPM'
        assert Quantity('1e-7').render() == '100 PPB'
        assert Quantity('1e-12').render() == '1 PPT'
        assert Quantity('1e-13').render() == '100 PPQ'

    # test set_prefs error handling
    with pytest.raises(KeyError):
        Quantity.set_prefs(fuzz=True)
    with pytest.raises(KeyError):
        fuzz = Quantity.get_pref('fuzz')

    c = Quantity('c')
    Quantity.set_prefs(label_fmt=None, label_fmt_full=None)
    Quantity.set_prefs(show_label=False, show_desc=False)
    assert str(c) == '299.79 Mm/s'
    assert '{:s}'.format(c) == '299.79 Mm/s'
    assert '{:S}'.format(c) == 'c = 299.79 Mm/s'
    assert c.render() == '299.79 Mm/s'
    assert c.render(show_label=False) == '299.79 Mm/s'
    assert c.render(show_label=True) == 'c = 299.79 Mm/s'
    assert c.render(show_label='f') == 'c = 299.79 Mm/s -- speed of light'
    assert c.render(show_label='a') == 'c = 299.79 Mm/s'
    Quantity.set_prefs(show_label=True)
    assert str(c) == 'c = 299.79 Mm/s'
    assert '{:s}'.format(c) == '299.79 Mm/s'
    assert '{:S}'.format(c) == 'c = 299.79 Mm/s'
    assert c.render() == 'c = 299.79 Mm/s'
    assert c.render(show_label=False) == '299.79 Mm/s'
    assert c.render(show_label=True) == 'c = 299.79 Mm/s'
    assert c.render(show_label='f') == 'c = 299.79 Mm/s -- speed of light'
    assert c.render(show_label='a') == 'c = 299.79 Mm/s'
    Quantity.set_prefs(show_label='f')
    assert str(c) == 'c = 299.79 Mm/s -- speed of light'
    assert '{:s}'.format(c) == '299.79 Mm/s'
    assert '{:S}'.format(c) == 'c = 299.79 Mm/s'
    assert c.render() == 'c = 299.79 Mm/s -- speed of light'
    assert c.render(show_label=False) == '299.79 Mm/s'
    assert c.render(show_label=True) == 'c = 299.79 Mm/s'
    assert c.render(show_label='f') == 'c = 299.79 Mm/s -- speed of light'
    assert c.render(show_label='a') == 'c = 299.79 Mm/s'

    Quantity.set_prefs(label_fmt='{n}: {v}', label_fmt_full='{n}: {v} -- {d}')
    Quantity.set_prefs(show_label=False, show_desc=False)
    assert str(c) == '299.79 Mm/s'
    assert '{:s}'.format(c) == '299.79 Mm/s'
    assert '{:S}'.format(c) == 'c: 299.79 Mm/s'
    assert c.render() == '299.79 Mm/s'
    assert c.render(show_label=False) == '299.79 Mm/s'
    assert c.render(show_label=True) == 'c: 299.79 Mm/s'
    assert c.render(show_label='f') == 'c: 299.79 Mm/s -- speed of light'
    assert c.render(show_label='a') == 'c: 299.79 Mm/s'
    Quantity.set_prefs(show_label=True)
    assert str(c) == 'c: 299.79 Mm/s'
    assert '{:s}'.format(c) == '299.79 Mm/s'
    assert '{:S}'.format(c) == 'c: 299.79 Mm/s'
    assert c.render() == 'c: 299.79 Mm/s'
    assert c.render(show_label=False) == '299.79 Mm/s'
    assert c.render(show_label=True) == 'c: 299.79 Mm/s'
    assert c.render(show_label='f') == 'c: 299.79 Mm/s -- speed of light'
    assert c.render(show_label='a') == 'c: 299.79 Mm/s'
    Quantity.set_prefs(show_label='f')
    assert str(c) == 'c: 299.79 Mm/s -- speed of light'
    assert '{:s}'.format(c) == '299.79 Mm/s'
    assert '{:S}'.format(c) == 'c: 299.79 Mm/s'
    assert c.render() == 'c: 299.79 Mm/s -- speed of light'
    assert c.render(show_label=False) == '299.79 Mm/s'
    assert c.render(show_label=True) == 'c: 299.79 Mm/s'
    assert c.render(show_label='f') == 'c: 299.79 Mm/s -- speed of light'
    assert c.render(show_label='a') == 'c: 299.79 Mm/s'

    Quantity.set_prefs(label_fmt='{n}: {v}', label_fmt_full='{V} // {d}')
    Quantity.set_prefs(show_label=False, show_desc=True)
    assert str(c) == '299.79 Mm/s'
    assert '{:s}'.format(c) == '299.79 Mm/s'
    assert '{:S}'.format(c) == 'c: 299.79 Mm/s // speed of light'
    assert c.render() == '299.79 Mm/s'
    assert c.render(show_label=False) == '299.79 Mm/s'
    assert c.render(show_label=True) == 'c: 299.79 Mm/s // speed of light'
    assert c.render(show_label='f') == 'c: 299.79 Mm/s // speed of light'
    assert c.render(show_label='a') == 'c: 299.79 Mm/s'
    Quantity.set_prefs(show_label=True)
    assert str(c) == 'c: 299.79 Mm/s // speed of light'
    assert '{:s}'.format(c) == '299.79 Mm/s'
    assert '{:S}'.format(c) == 'c: 299.79 Mm/s // speed of light'
    assert c.render() == 'c: 299.79 Mm/s // speed of light'
    assert c.render(show_label=False) == '299.79 Mm/s'
    assert c.render(show_label=True) == 'c: 299.79 Mm/s // speed of light'
    assert c.render(show_label='f') == 'c: 299.79 Mm/s // speed of light'
    assert c.render(show_label='a') == 'c: 299.79 Mm/s'
    Quantity.set_prefs(show_label='f')
    assert str(c) == 'c: 299.79 Mm/s // speed of light'
    assert '{:s}'.format(c) == '299.79 Mm/s'
    assert '{:S}'.format(c) == 'c: 299.79 Mm/s // speed of light'
    assert c.render() == 'c: 299.79 Mm/s // speed of light'
    assert c.render(show_label=False) == '299.79 Mm/s'
    assert c.render(show_label=True) == 'c: 299.79 Mm/s // speed of light'
    assert c.render(show_label='f') == 'c: 299.79 Mm/s // speed of light'
    assert c.render(show_label='a') == 'c: 299.79 Mm/s'

    mvi_raw_conv = '''
Status @ 0.00000000e+00s: Tests started for mylib.sh:MiM.
    Assertion successfully detects expected fault @ 1.00013334e-04s in sh_tb.REF (sh): 'V(cm)' out of range.
    Assertion successfully detects expected fault @ 1.00123334e-04s in sh_tb.REF (sh): 'V(cm)' out of range.
Status @ 2.00500000e-04s: in_val = 5.000000e-01.
    Pass @ 3.00500000e-04s: V(out) voltage: expected=2.00000000e+00V, measured=1.99999965e+00V, diff=3.46117130e-07V.
Status @ 3.00500000e-04s: in_val = 7.500000e-01.
    Pass @ 4.00500000e-04s: V(out) voltage: expected=1.75000000e+00V, measured=1.74999966e+00V, diff=3.41027651e-07V.
Status @ 4.00500000e-04s: in_val = 1.000000e+00.
    Pass @ 5.00500000e-04s: V(out) voltage: expected=1.50000000e+00V, measured=1.49999944e+00V, diff=5.55270307e-07V.
Status @ 5.00500000e-04s: in_val = 1.250000e+00.
    Pass @ 6.00500000e-04s: V(out) voltage: expected=1.25000000e+00V, measured=1.25000000e+00V, diff=1.26565425e-14V.
Status @ 6.00500000e-04s: in_val = 1.500000e+00.
    Pass @ 7.00500000e-04s: V(out) voltage: expected=1.00000000e+00V, measured=9.99999924e-01V, diff=7.59200380e-08V.
Status @ 7.00500000e-04s: in_val = 1.750000e+00.
    Pass @ 8.00500000e-04s: V(out) voltage: expected=7.50000000e-01V, measured=7.50017054e-01V, diff=1.70539238e-05V.
Status @ 8.00500000e-04s: in_val = 2.000000e+00.
    FAIL @ 9.00500000e-04s: V(out) voltage: expected=5.00000000e-01V, measured=5.48562457e-01V, diff=4.85624570e-02V.
Summary @ 9.00510000e-04s: 7 tests run, 1 failures detected, 0 faults detected, 0 test sequences skipped.
    '''

    mvi_raw_si = '''
Status @ 0s: Tests started for mylib.sh:MiM.
    Assertion successfully detects expected fault @ 100.013334us in sh_tb.REF (sh): 'V(cm)' out of range.
    Assertion successfully detects expected fault @ 100.123334us in sh_tb.REF (sh): 'V(cm)' out of range.
Status @ 200.5us: in_val = 500m.
    Pass @ 300.5us: V(out) voltage: expected=2V, measured=1.99999965V, diff=346.11713nV.
Status @ 300.5us: in_val = 750m.
    Pass @ 400.5us: V(out) voltage: expected=1.75V, measured=1.74999966V, diff=341.027651nV.
Status @ 400.5us: in_val = 1.
    Pass @ 500.5us: V(out) voltage: expected=1.5V, measured=1.49999944V, diff=555.270307nV.
Status @ 500.5us: in_val = 1.25.
    Pass @ 600.5us: V(out) voltage: expected=1.25V, measured=1.25V, diff=12.6565425fV.
Status @ 600.5us: in_val = 1.5.
    Pass @ 700.5us: V(out) voltage: expected=1V, measured=999.999924mV, diff=75.920038nV.
Status @ 700.5us: in_val = 1.75.
    Pass @ 800.5us: V(out) voltage: expected=750mV, measured=750.017054mV, diff=17.0539238uV.
Status @ 800.5us: in_val = 2.
    FAIL @ 900.5us: V(out) voltage: expected=500mV, measured=548.562457mV, diff=48.562457mV.
Summary @ 900.51us: 7 tests run, 1 failures detected, 0 faults detected, 0 test sequences skipped.
    '''

    mvi_conv = '''
Status @ 0 s: Tests started for mylib.sh:MiM.
    Assertion successfully detects expected fault @ 100.01e-6 s in sh_tb.REF (sh): 'V(cm)' out of range.
    Assertion successfully detects expected fault @ 100.12e-6 s in sh_tb.REF (sh): 'V(cm)' out of range.
Status @ 200.5e-6 s: in_val = 500e-3.
    Pass @ 300.5e-6 s: V(out) voltage: expected=2 V, measured=2 V, diff=346.12e-9 V.
Status @ 300.5e-6 s: in_val = 750e-3.
    Pass @ 400.5e-6 s: V(out) voltage: expected=1.75 V, measured=1.75 V, diff=341.03e-9 V.
Status @ 400.5e-6 s: in_val = 1.
    Pass @ 500.5e-6 s: V(out) voltage: expected=1.5 V, measured=1.5 V, diff=555.27e-9 V.
Status @ 500.5e-6 s: in_val = 1.25.
    Pass @ 600.5e-6 s: V(out) voltage: expected=1.25 V, measured=1.25 V, diff=12.657e-15 V.
Status @ 600.5e-6 s: in_val = 1.5.
    Pass @ 700.5e-6 s: V(out) voltage: expected=1 V, measured=1 V, diff=75.92e-9 V.
Status @ 700.5e-6 s: in_val = 1.75.
    Pass @ 800.5e-6 s: V(out) voltage: expected=750e-3 V, measured=750.02e-3 V, diff=17.054e-6 V.
Status @ 800.5e-6 s: in_val = 2.
    FAIL @ 900.5e-6 s: V(out) voltage: expected=500e-3 V, measured=548.56e-3 V, diff=48.562e-3 V.
Summary @ 900.51e-6 s: 7 tests run, 1 failures detected, 0 faults detected, 0 test sequences skipped.
    '''

    mvi_conv_full = '''
Status @ 0 s: Tests started for mylib.sh:MiM.
    Assertion successfully detects expected fault @ 100.013334e-6 s in sh_tb.REF (sh): 'V(cm)' out of range.
    Assertion successfully detects expected fault @ 100.123334e-6 s in sh_tb.REF (sh): 'V(cm)' out of range.
Status @ 200.5e-6 s: in_val = 500e-3.
    Pass @ 300.5e-6 s: V(out) voltage: expected=2 V, measured=1.99999965 V, diff=346.11713e-9 V.
Status @ 300.5e-6 s: in_val = 750e-3.
    Pass @ 400.5e-6 s: V(out) voltage: expected=1.75 V, measured=1.74999966 V, diff=341.027651e-9 V.
Status @ 400.5e-6 s: in_val = 1.
    Pass @ 500.5e-6 s: V(out) voltage: expected=1.5 V, measured=1.49999944 V, diff=555.270307e-9 V.
Status @ 500.5e-6 s: in_val = 1.25.
    Pass @ 600.5e-6 s: V(out) voltage: expected=1.25 V, measured=1.25 V, diff=12.6565425e-15 V.
Status @ 600.5e-6 s: in_val = 1.5.
    Pass @ 700.5e-6 s: V(out) voltage: expected=1 V, measured=999.999924e-3 V, diff=75.920038e-9 V.
Status @ 700.5e-6 s: in_val = 1.75.
    Pass @ 800.5e-6 s: V(out) voltage: expected=750e-3 V, measured=750.017054e-3 V, diff=17.0539238e-6 V.
Status @ 800.5e-6 s: in_val = 2.
    FAIL @ 900.5e-6 s: V(out) voltage: expected=500e-3 V, measured=548.562457e-3 V, diff=48.562457e-3 V.
Summary @ 900.51e-6 s: 7 tests run, 1 failures detected, 0 faults detected, 0 test sequences skipped.
    '''

    mvi_si = '''
Status @ 0 s: Tests started for mylib.sh:MiM.
    Assertion successfully detects expected fault @ 100.01 us in sh_tb.REF (sh): 'V(cm)' out of range.
    Assertion successfully detects expected fault @ 100.12 us in sh_tb.REF (sh): 'V(cm)' out of range.
Status @ 200.5 us: in_val = 500m.
    Pass @ 300.5 us: V(out) voltage: expected=2 V, measured=2 V, diff=346.12 nV.
Status @ 300.5 us: in_val = 750m.
    Pass @ 400.5 us: V(out) voltage: expected=1.75 V, measured=1.75 V, diff=341.03 nV.
Status @ 400.5 us: in_val = 1.
    Pass @ 500.5 us: V(out) voltage: expected=1.5 V, measured=1.5 V, diff=555.27 nV.
Status @ 500.5 us: in_val = 1.25.
    Pass @ 600.5 us: V(out) voltage: expected=1.25 V, measured=1.25 V, diff=12.657 fV.
Status @ 600.5 us: in_val = 1.5.
    Pass @ 700.5 us: V(out) voltage: expected=1 V, measured=1 V, diff=75.92 nV.
Status @ 700.5 us: in_val = 1.75.
    Pass @ 800.5 us: V(out) voltage: expected=750 mV, measured=750.02 mV, diff=17.054 uV.
Status @ 800.5 us: in_val = 2.
    FAIL @ 900.5 us: V(out) voltage: expected=500 mV, measured=548.56 mV, diff=48.562 mV.
Summary @ 900.51 us: 7 tests run, 1 failures detected, 0 faults detected, 0 test sequences skipped.
    '''

    mvi_si_full = '''
Status @ 0 s: Tests started for mylib.sh:MiM.
    Assertion successfully detects expected fault @ 100.013334 us in sh_tb.REF (sh): 'V(cm)' out of range.
    Assertion successfully detects expected fault @ 100.123334 us in sh_tb.REF (sh): 'V(cm)' out of range.
Status @ 200.5 us: in_val = 500m.
    Pass @ 300.5 us: V(out) voltage: expected=2 V, measured=1.99999965 V, diff=346.11713 nV.
Status @ 300.5 us: in_val = 750m.
    Pass @ 400.5 us: V(out) voltage: expected=1.75 V, measured=1.74999966 V, diff=341.027651 nV.
Status @ 400.5 us: in_val = 1.
    Pass @ 500.5 us: V(out) voltage: expected=1.5 V, measured=1.49999944 V, diff=555.270307 nV.
Status @ 500.5 us: in_val = 1.25.
    Pass @ 600.5 us: V(out) voltage: expected=1.25 V, measured=1.25 V, diff=12.6565425 fV.
Status @ 600.5 us: in_val = 1.5.
    Pass @ 700.5 us: V(out) voltage: expected=1 V, measured=999.999924 mV, diff=75.920038 nV.
Status @ 700.5 us: in_val = 1.75.
    Pass @ 800.5 us: V(out) voltage: expected=750 mV, measured=750.017054 mV, diff=17.0539238 uV.
Status @ 800.5 us: in_val = 2.
    FAIL @ 900.5 us: V(out) voltage: expected=500 mV, measured=548.562457 mV, diff=48.562457 mV.
Summary @ 900.51 us: 7 tests run, 1 failures detected, 0 faults detected, 0 test sequences skipped.
    '''

    processed = Quantity.all_from_conv_fmt(mvi_raw_conv, show_si=True)
    assert processed == mvi_si
    processed = Quantity.all_from_conv_fmt(mvi_raw_conv, show_si=False)
    assert processed == mvi_conv
    processed = Quantity.all_from_conv_fmt(mvi_raw_conv,
                                           show_si=True,
                                           prec='full')
    assert processed == mvi_si_full
    processed = Quantity.all_from_conv_fmt(mvi_raw_conv,
                                           show_si=False,
                                           prec='full')
    assert processed == mvi_conv_full

    processed = Quantity.all_from_si_fmt(mvi_raw_si, show_si=True)
    assert processed == mvi_si
    processed = Quantity.all_from_si_fmt(mvi_raw_si, show_si=False)
    assert processed == mvi_conv
    processed = Quantity.all_from_si_fmt(mvi_raw_si, show_si=True, prec='full')
    assert processed == mvi_si_full
    processed = Quantity.all_from_si_fmt(mvi_raw_si,
                                         show_si=False,
                                         prec='full')
    assert processed == mvi_conv_full

    processed = Quantity.all_from_si_fmt(
        '1420.40575MHz+1420.40575MHz+1420.40575MHz', show_si=True)
    assert processed == '1.4204 GHz+1.4204 GHz+1.4204 GHz'

    processed = Quantity.all_from_si_fmt(
        '1420.40575MHz+abc+1420.40575MHz+abc+1420.40575MHz', show_si=True)
    assert processed == '1.4204 GHz+abc+1.4204 GHz+abc+1.4204 GHz'

    processed = Quantity.all_from_si_fmt('1420.40575e+6+1420.40575e+6',
                                         show_si=True)
    assert processed == '1420.40575e+6+1420.40575e+6'
Exemplo n.º 20
0
def test_temperature():
    Quantity.reset_prefs()
    with Quantity.prefs(
        spacer=None, show_label=None, label_fmt=None, label_fmt_full=None,
        ignore_sf=True
    ):
        q=Quantity('100 °C')
        assert q.render() == '100 °C'
        assert q.render(scale='C') == '100 C'
        assert q.render(scale='°C') == '100 °C'
        assert q.render(scale='K') == '373.15 K'
        assert q.render(scale='°F') == '212 °F'
        assert q.render(scale='F') == '212 F'
        assert q.render(scale='°R') == '671.67 °R'
        assert q.render(scale='R') == '671.67 R'

        q=Quantity('100 C')
        assert q.render() == '100 C'
        assert q.render(scale='C') == '100 C'
        assert q.render(scale='K') == '373.15 K'
        assert q.render(scale='F') == '212 F'
        assert q.render(scale='R') == '671.67 R'
        assert q.render(scale='°C') == '100 °C'
        assert q.render(scale='°F') == '212 °F'
        assert q.render(scale='°R') == '671.67 °R'

        q=Quantity('373.15 K')
        assert q.render() == '373.15 K'
        assert q.render(scale='C') == '100 C'
        assert q.render(scale='K') == '373.15 K'
        assert q.render(scale='F') == '212 F'
        assert q.render(scale='R') == '671.67 R'
        assert q.render(scale='°C') == '100 °C'
        assert q.render(scale='°F') == '212 °F'
        assert q.render(scale='°R') == '671.67 °R'

        q=Quantity('212 °F')
        assert q.render() == '212 °F'
        assert q.render(scale='°C') == '100 °C'
        assert q.render(scale='C') == '100 C'
        assert q.render(scale='K') == '373.15 K'
        assert q.render(scale='°F') == '212 °F'
        assert q.render(scale='F') == '212 F'
        #assert q.render(scale='°R') == '671.67 °R'
        #assert q.render(scale='R') == '671.67 R'

        q=Quantity('212 F')
        assert q.render() == '212 F'
        assert q.render(scale='C') == '100 C'
        assert q.render(scale='K') == '373.15 K'
        assert q.render(scale='°C') == '100 °C'
        assert q.render(scale='°F') == '212 °F'
        assert q.render(scale='F') == '212 F'
        #assert q.render(scale='°R') == '671.67 °R'
        #assert q.render(scale='R') == '671.67 R'

        q=Quantity('100 °C', scale='K')
        assert q.render() == '373.15 K'

        q=Quantity('212 °F', scale='K')
        assert q.render() == '373.15 K'

        q=Quantity('212 °F', scale='C')
        assert q.render() == '100 C'

        q=Quantity('212 F', scale='°C')
        assert q.render() == '100 °C'

        q=Quantity('491.67 R', scale='°C')
        assert q.is_close(Quantity('0 °C'))

        q=Quantity('491.67 R', scale='K')
        assert q.render() == '273.15 K'
Exemplo n.º 21
0
def test_distance():
    Quantity.reset_prefs()
    with Quantity.prefs(
        spacer=None, show_label=None, label_fmt=None, label_fmt_full=None,
        ignore_sf=False
    ):
        q=Quantity('1_m')
        assert q.render() == '1 m'
        assert q.render(scale='cm', form='eng') == '100 cm'
        assert q.render(scale='mm', form='eng') == '1e3 mm'
        assert q.render(scale='um', form='eng') == '1e6 um'
        assert q.render(scale='μm', form='eng') == '1e6 μm'
        assert q.render(scale='nm', form='eng') == '1e9 nm'
        assert q.render(scale='Å', form='eng') == '10e9 Å'
        assert q.render(scale='angstrom', form='eng') == '10e9 angstrom'
        assert q.render(scale='mi') == '621.37 umi'
        assert q.render(scale='mile') == '621.37 umile'
        assert q.render(scale='miles') == '621.37 umiles'
        assert q.render(scale='in') == '39.37 in'
        assert q.render(scale='inch') == '39.37 inch'
        assert q.render(scale='inches') == '39.37 inches'

        q=Quantity('1_m')
        assert q.render() == '1 m'

        q=Quantity('100cm', scale='m')
        assert q.render() == '1 m'

        q=Quantity('1cm', scale='m')
        assert q.render() == '10 mm'

        q=Quantity('1000mm', scale='m')
        assert q.render() == '1 m'

        q=Quantity('1mm', scale='m')
        assert q.render() == '1 mm'

        q=Quantity('1000000um', scale='m')
        assert q.render() == '1 m'

        q=Quantity('1um', scale='m')
        assert q.render() == '1 um'

        q=Quantity('1000000μm', scale='m')
        assert q.render() == '1 m'

        q=Quantity('1μm', scale='m')
        assert q.render() == '1 um'

        q=Quantity('1000000000nm', scale='m')
        assert q.render() == '1 m'

        q=Quantity('1nm', scale='m')
        assert q.render() == '1 nm'

        q=Quantity('10000000000Å', scale='m')
        assert q.render() == '1 m'

        q=Quantity('1Å', scale='m')
        assert q.render() == '100 pm'

        q=Quantity('1_mi', scale='m')
        assert q.render() == '1.6093 km'

        q=Quantity('1_mile', scale='m')
        assert q.render() == '1.6093 km'

        q=Quantity('1_miles', scale='m')
        assert q.render() == '1.6093 km'

        q=Quantity('d = 93 Mmiles  -- average distance from Sun to Earth', scale='m')
        assert q.render() == '149.67 Gm'