コード例 #1
0
ファイル: test_format.py プロジェクト: KenKundert/quantiphy
def test_scaled_format():
    Quantity.set_prefs(spacer=None, show_label=None, label_fmt=None, label_fmt_full=None, show_desc=False)
    Quantity.set_prefs(prec=None)
    q=Quantity('Tboil = 100 °C -- boiling point of water')
    assert '{}'.format(q) == '100 °C'
    assert '{:.8}'.format(q) == '100 °C'
    assert '{:.8s°F}'.format(q) == '212 °F'
    assert '{:.8S°F}'.format(q) == 'Tboil = 212 °F'
    assert '{:.8q°F}'.format(q) == '212 °F'
    assert '{:.8Q°F}'.format(q) == 'Tboil = 212 °F'
    assert '{:r°F}'.format(q) == '212'
    assert '{:R°F}'.format(q) == 'Tboil = 212'
    assert '{:u°F}'.format(q) == '°F'
    assert '{:f°F}'.format(q) == '212'
    assert '{:F°F}'.format(q) == 'Tboil = 212'
    assert '{:e°F}'.format(q) == '2.12e+02'
    assert '{:E°F}'.format(q) == 'Tboil = 2.12e+02'
    assert '{:g°F}'.format(q) == '212'
    assert '{:G°F}'.format(q) == 'Tboil = 212'
    assert '{:n°F}'.format(q) == 'Tboil'
    assert '{:d°F}'.format(q) == 'boiling point of water'
    assert '{!r}'.format(q) == "Quantity('100 °C')"
    assert '{:.8s°C}'.format(q) == '100 °C'
    assert '{:p°F}'.format(q) == '212 °F'
    assert '{:,.2p°F}'.format(q) == '212 °F'
    assert '{:P°F}'.format(q) == 'Tboil = 212 °F'
    assert '{:,.2P°F}'.format(q) == 'Tboil = 212 °F'
    assert '{:#p°F}'.format(q) == '212.0000 °F'
    assert '{:#,.2p°F}'.format(q) == '212.00 °F'
    assert '{:#P°F}'.format(q) == 'Tboil = 212.0000 °F'
    assert '{:#,.2P°F}'.format(q) == 'Tboil = 212.00 °F'
コード例 #2
0
ファイル: test_misc.py プロジェクト: KenKundert/quantiphy
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)
コード例 #3
0
def test_format():
    Quantity.set_prefs(spacer=None,
                       show_label=None,
                       label_fmt=None,
                       label_fmt_full=None,
                       show_desc=False)
    q = Quantity('f = 1420.405751786 MHz -- frequency of hydrogen line')
    assert '{}'.format(q) == '1.4204 GHz'
    assert '{:.8}'.format(q) == '1.42040575 GHz'
    assert '{:.8s}'.format(q) == '1.42040575 GHz'
    assert '{:.8S}'.format(q) == 'f = 1.42040575 GHz'
    assert '{:.8q}'.format(q) == '1.42040575 GHz'
    assert '{:.8Q}'.format(q) == 'f = 1.42040575 GHz'
    assert '{:r}'.format(q) == '1.4204G'
    assert '{:R}'.format(q) == 'f = 1.4204G'
    assert '{:u}'.format(q) == 'Hz'
    assert '{:f}'.format(q) == '1420405751.7860'
    assert '{:F}'.format(q) == 'f = 1420405751.7860'
    assert '{:e}'.format(q) == '1.4204e+09'
    assert '{:E}'.format(q) == 'f = 1.4204e+09'
    assert '{:g}'.format(q) == '1.4204e+09'
    assert '{:G}'.format(q) == 'f = 1.4204e+09'
    assert '{:n}'.format(q) == 'f'
    assert '{:d}'.format(q) == 'frequency of hydrogen line'
    assert '{:X}'.format(q) == '1.4204 GHz'

    q = Quantity('2ns')
    assert float(q) == 2e-9
コード例 #4
0
def test_scaled_format():
    Quantity.set_prefs(spacer=None,
                       show_label=None,
                       label_fmt=None,
                       label_fmt_full=None,
                       show_desc=False)
    Quantity.set_prefs(prec=None)
    if sys.version_info.major == 3:
        q = Quantity('Tboil = 100 °C -- boiling point of water')
        assert '{}'.format(q) == '100 °C'
        assert '{:.8}'.format(q) == '100 °C'
        assert '{:.8s°F}'.format(q) == '212 °F'
        assert '{:.8S°F}'.format(q) == 'Tboil = 212 °F'
        assert '{:.8q°F}'.format(q) == '212 °F'
        assert '{:.8Q°F}'.format(q) == 'Tboil = 212 °F'
        assert '{:r°F}'.format(q) == '212'
        assert '{:R°F}'.format(q) == 'Tboil = 212'
        assert '{:u°F}'.format(q) == '°F'
        assert '{:f°F}'.format(q) == '212.0000'
        assert '{:F°F}'.format(q) == 'Tboil = 212.0000'
        assert '{:e°F}'.format(q) == '2.1200e+02'
        assert '{:E°F}'.format(q) == 'Tboil = 2.1200e+02'
        assert '{:g°F}'.format(q) == '212'
        assert '{:G°F}'.format(q) == 'Tboil = 212'
        assert '{:n°F}'.format(q) == 'Tboil'
        assert '{:d°F}'.format(q) == 'boiling point of water'
        assert '{:X°F}'.format(q) == '100 °C'
        assert '{!r}'.format(q) == "Quantity('100 °C')"
        assert '{:.8s°C}'.format(q) == '100 °C'
コード例 #5
0
def test_simple_scaling():
    Quantity.set_prefs(spacer=None,
                       show_label=None,
                       label_fmt=None,
                       label_fmt_full=None)
    q = Quantity('1kg')
    assert q.render() == '1 kg'
    assert q.render(scale=0.001, show_units=False) == '1'
    with pytest.raises(KeyError,
                       message="Unable to convert between 'fuzz' and 'g'."):
        q.render(scale='fuzz')

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

    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'
コード例 #6
0
ファイル: test_format.py プロジェクト: KenKundert/quantiphy
def test_width():
    Quantity.set_prefs(spacer=None, show_label=None, label_fmt=None, label_fmt_full=None, show_desc=False)
    Quantity.set_prefs(prec='full')
    q=Quantity('f = 1420.405751786 MHz -- frequency of hydrogen line')
    assert '{:25}'.format(q) == '       1.420405751786 GHz'
    assert '{:>25.8}'.format(q) == '           1.42040575 GHz'
    assert '{:25.8s}'.format(q) == '           1.42040575 GHz'
    assert '{:<25.8s}'.format(q) == '1.42040575 GHz           '
    assert '{:^25.8S}'.format(q) == '   f = 1.42040575 GHz    '
    assert '{:25.8q}'.format(q) == '           1.42040575 GHz'
    assert '{:>25.8Q}'.format(q) == '       f = 1.42040575 GHz'
    assert '{:<25r}'.format(q) == '1.420405751786G          '
    assert '{:^25R}'.format(q) == '   f = 1.420405751786G   '
    assert '{:25u}'.format(q) == 'Hz                       '
    assert '{:>25.4f}'.format(q) == '           1420405751.786'
    assert '{:<25.4F}'.format(q) == 'f = 1420405751.786       '
    assert '{:^25e}'.format(q) == '   1.420405751786e+09    '
    assert '{:25E}'.format(q) == '   f = 1.420405751786e+09'
    assert '{:>25g}'.format(q) == '           1420405751.786'
    assert '{:<25G}'.format(q) == 'f = 1420405751.786       '
    assert '{:^25n}'.format(q) == '            f            '
    assert '{:30d}'.format(q) == 'frequency of hydrogen line    '
    assert '{:>25.2p}'.format(q) == '         1420405751.79 Hz'
    assert '{:<25,.2p}'.format(q) == '1,420,405,751.79 Hz      '
    assert '{:^25.2P}'.format(q) == '  f = 1420405751.79 Hz   '
    assert '{:25,.2P}'.format(q) == '  f = 1,420,405,751.79 Hz'
    assert '{:#25.3q}'.format(q) == '                1.420 GHz'
    assert '{:#25.6p}'.format(q) == '     1420405751.786000 Hz'
    assert '{:25.0q}'.format(q) == '                    1 GHz'
    assert '{:25.0p}'.format(q) == '            1420405752 Hz'
    assert '{:#25.0q}'.format(q) == '                    1 GHz'
    assert '{:#25.0p}'.format(q) == '           1420405752. Hz'
コード例 #7
0
def test_time():
    Quantity.set_prefs(spacer=None,
                       show_label=None,
                       label_fmt=None,
                       label_fmt_full=None)
    Quantity.set_prefs(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'
コード例 #8
0
ファイル: test_format.py プロジェクト: KenKundert/quantiphy
def test_exceptional():
    Quantity.set_prefs(spacer=None, show_label=None, label_fmt=None, label_fmt_full=None, show_desc=False)
    Quantity.set_prefs(prec='full')
    q=Quantity('light = inf Hz -- a high frequency')
    assert '{}'.format(q) == 'inf Hz'
    assert '{:.8}'.format(q) == 'inf Hz'
    assert '{:.8s}'.format(q) == 'inf Hz'
    assert '{:.8S}'.format(q) == 'light = inf Hz'
    assert '{:.8q}'.format(q) == 'inf Hz'
    assert '{:.8Q}'.format(q) == 'light = inf Hz'
    assert '{:r}'.format(q) == 'inf'
    assert '{:R}'.format(q) == 'light = inf'
    assert '{:u}'.format(q) == 'Hz'
    assert '{:.4f}'.format(q) == 'inf'
    assert '{:.4F}'.format(q) == 'light = inf'
    assert '{:e}'.format(q) == 'inf'
    assert '{:E}'.format(q) == 'light = inf'
    assert '{:g}'.format(q) == 'inf'
    assert '{:G}'.format(q) == 'light = inf'
    assert '{:n}'.format(q) == 'light'
    assert '{:d}'.format(q) == 'a high frequency'
    assert '{:.2p}'.format(q) == 'inf Hz'
    assert '{:,.2p}'.format(q) == 'inf Hz'
    assert '{:.2P}'.format(q) == 'light = inf Hz'
    assert '{:,.2P}'.format(q) == 'light = inf Hz'
コード例 #9
0
ファイル: test_format.py プロジェクト: KenKundert/quantiphy
def test_render():
    Quantity.set_prefs(
        spacer = None,
        show_label = None,
        label_fmt = None,
        label_fmt_full = None,
        show_desc = False,
        prec = 4,
        strip_zeros = True,
    )
    q=Quantity('f = 1420.405751786 MHz -- frequency of hydrogen line')
    assert q.render() == '1.4204 GHz'
    assert q.render(prec=8) == '1.42040575 GHz'
    assert q.render(prec=8, show_label=True) == 'f = 1.42040575 GHz'
    assert q.render(show_units=False) == '1.4204G'
    assert q.render(show_units=False, show_label=True) == 'f = 1.4204G'
    assert q.render(form='eng') == '1.4204e9 Hz'
    assert q.render(form='eng', show_label=True) == 'f = 1.4204e9 Hz'
    assert q.render(prec=15, strip_zeros=False) == '1.420405751786000 GHz'
    assert q.render(prec=15, strip_zeros=True) == '1.420405751786 GHz'
    assert q.units == 'Hz'
    assert q.name == 'f'
    assert q.desc == 'frequency of hydrogen line'
    assert q.fixed() == '1420405751.786 Hz'
    assert q.fixed(show_commas=True) == '1,420,405,751.786 Hz'
    assert q.fixed(show_units=False) == '1420405751.786'
    assert q.fixed(strip_zeros=True) == '1420405751.786 Hz'
    assert q.fixed(strip_zeros=False) == '1420405751.7860 Hz'
    assert q.fixed(show_label=True) == 'f = 1420405751.786 Hz'
    assert q.fixed(show_label=True, show_commas=True) == 'f = 1,420,405,751.786 Hz'
    assert q.render(form='fixed') == '1420405751.786 Hz'

    q=Quantity('$1M')
    assert q.render(strip_zeros=True) == '$1M'
    assert q.render(strip_zeros=False) == '$1.0000M'
    assert q.render(strip_zeros=True, strip_radix=False) == '$1M'
    assert q.render(prec='full') == '$1M'
    assert q.fixed(strip_zeros=True) == '$1000000'
    assert q.fixed(strip_zeros=False) == '$1000000.0000'
    assert q.fixed(strip_zeros=True, strip_radix=False) == '$1000000.'
    assert q.fixed(prec='full') == '$1000000'
    assert q.fixed(prec='full', strip_zeros=False) == '$1000000.000000000000'
    assert q.render(form='fixed') == '$1000000'

    q=Quantity('$100')
    assert q.fixed(prec=0, strip_zeros=False, strip_radix=False) == '$100.'
    assert q.fixed(prec=0, strip_zeros=True, strip_radix=False) == '$100.'
    assert q.fixed(prec=0, strip_zeros=False, strip_radix=True) == '$100'
    assert q.fixed(prec=0, strip_zeros=True, strip_radix=True) == '$100'
    assert q.fixed(prec=2, strip_zeros=False, strip_radix=False) == '$100.00'
    assert q.fixed(prec=2, strip_zeros=True, strip_radix=False) == '$100.'
    assert q.fixed(prec=2, strip_zeros=False, strip_radix=True) == '$100.00'
    assert q.fixed(prec=2, strip_zeros=True, strip_radix=True) == '$100'
コード例 #10
0
ファイル: test_misc.py プロジェクト: KenKundert/quantiphy
def test_scale():
    Quantity.reset_prefs()
    Quantity.set_prefs(spacer=None,
                       show_label=None,
                       label_fmt=None,
                       label_fmt_full=None)
    q1 = Quantity('3ns')
    q2 = Quantity('2')
    v2 = 2
    assert str(q1.scale(q2)) == '6 ns'
    assert repr(q1.scale(q2)) == "Quantity('6 ns')"
    assert str(q1.scale(v2)) == '6 ns'
    assert repr(q1.scale(v2)) == "Quantity('6 ns')"

    q1.name = 'period'
    q3 = q1.scale(q2).name == 'period'
    q1.desc = 'duration of one cycle'
    assert q1.scale(q2).name == 'period'
    assert q1.scale(q2).desc == 'duration of one cycle'

    class Dollars(Quantity):
        units = '$'
        prec = 2
        form = 'fixed'
        show_commas = True
        minus = Quantity.minus_sign
        strip_zeros = False

    class Cents(Dollars):
        units = '¢'
        prec = 0

    print(UnitConversion(Dollars, Cents, 0.01))

    total = Dollars(1)
    assert str(total) == '$1.00'
    total = total.scale(1000000)
    assert str(total) == '$1,000,000.00'

    class WholeDollars(Dollars):
        prec = 0

    total = WholeDollars(20)
    assert str(total) == '$20'
    total = total.scale(1000000)
    assert str(total) == '$20,000,000'
    total = total.scale(5, Dollars)
    assert str(total) == '$100,000,000.00'

    total = total.scale(Cents)
    assert str(total) == '10,000,000,000 ¢'
    assert type(total) == Cents
コード例 #11
0
def test_full_format():
    Quantity.set_prefs(spacer=None,
                       show_label=None,
                       label_fmt=None,
                       label_fmt_full=None,
                       show_desc=False)
    Quantity.set_prefs(prec='full')
    q = Quantity('f = 1420.405751786 MHz -- frequency of hydrogen line')
    assert '{}'.format(q) == '1.420405751786 GHz'
    assert '{:.8}'.format(q) == '1.42040575 GHz'
    assert '{:.8s}'.format(q) == '1.42040575 GHz'
    assert '{:.8S}'.format(q) == 'f = 1.42040575 GHz'
    assert '{:.8q}'.format(q) == '1.42040575 GHz'
    assert '{:.8Q}'.format(q) == 'f = 1.42040575 GHz'
    assert '{:r}'.format(q) == '1.420405751786G'
    assert '{:R}'.format(q) == 'f = 1.420405751786G'
    assert '{:u}'.format(q) == 'Hz'
    assert '{:.4f}'.format(q) == '1420405751.786'
    assert '{:.4F}'.format(q) == 'f = 1420405751.786'
    assert '{:e}'.format(q) == '1.420405751786e+09'
    assert '{:E}'.format(q) == 'f = 1.420405751786e+09'
    assert '{:g}'.format(q) == '1420405751.786'
    assert '{:G}'.format(q) == 'f = 1420405751.786'
    assert '{:n}'.format(q) == 'f'
    assert '{:d}'.format(q) == 'frequency of hydrogen line'
    assert '{:.2p}'.format(q) == '1420405751.79 Hz'
    assert '{:,.2p}'.format(q) == '1,420,405,751.79 Hz'
    assert '{:.2P}'.format(q) == 'f = 1420405751.79 Hz'
    assert '{:,.2P}'.format(q) == 'f = 1,420,405,751.79 Hz'
    assert '{:#.3q}'.format(q) == '1.420 GHz'
    assert '{:#.6p}'.format(q) == '1420405751.786000 Hz'
    assert '{:.0q}'.format(q) == '1 GHz'
    assert '{:.0p}'.format(q) == '1420405752 Hz'
    assert '{:#.0q}'.format(q) == '1 GHz'
    assert '{:#.0p}'.format(q) == '1420405752. Hz'
    values = '''
        1.000000 +1.000000 -1.000000
        $1.000000 +$1.000000 -$1.000000
        1.000000_V +1.000000_V -1.000000_V
        1.234567 +1.234567 -1.234567
        $1.234567 +$1.234567 -$1.234567
        1.234567_V +1.234567_V -1.234567_V
    '''
    for given in values.split():
        expected = given.lstrip('+').replace('_', ' ')
        q = Quantity(given)
        assert q.render(form='si', prec='full', strip_zeros=False) == expected

    q = Quantity('2ns')
    assert float(q) == 2e-9
コード例 #12
0
def test_format():
    Quantity.set_prefs(spacer=None,
                       show_label=None,
                       label_fmt=None,
                       label_fmt_full=None,
                       show_desc=False)
    q = Quantity('f = 1420.405751786 MHz -- frequency of hydrogen line')
    assert '{}'.format(q) == '1.4204 GHz'
    assert '{:.8}'.format(q) == '1.42040575 GHz'
    assert '{:.8s}'.format(q) == '1.42040575 GHz'
    assert '{:.8S}'.format(q) == 'f = 1.42040575 GHz'
    assert '{:.8q}'.format(q) == '1.42040575 GHz'
    assert '{:.8Q}'.format(q) == 'f = 1.42040575 GHz'
    assert '{:r}'.format(q) == '1.4204G'
    assert '{:R}'.format(q) == 'f = 1.4204G'
    assert '{:u}'.format(q) == 'Hz'
    assert '{:f}'.format(q) == '1420405751.786'
    assert '{:F}'.format(q) == 'f = 1420405751.786'
    assert '{:e}'.format(q) == '1.4204e+09'
    assert '{:E}'.format(q) == 'f = 1.4204e+09'
    assert '{:g}'.format(q) == '1.4204e+09'
    assert '{:G}'.format(q) == 'f = 1.4204e+09'
    assert '{:n}'.format(q) == 'f'
    assert '{:d}'.format(q) == 'frequency of hydrogen line'
    assert '{:p}'.format(q) == '1420405751.786 Hz'
    assert '{:,p}'.format(q) == '1,420,405,751.786 Hz'
    assert '{:P}'.format(q) == 'f = 1420405751.786 Hz'
    assert '{:,P}'.format(q) == 'f = 1,420,405,751.786 Hz'
    assert '{:#.3q}'.format(q) == '1.420 GHz'
    assert '{:#p}'.format(q) == '1420405751.7860 Hz'
    assert '{:.0q}'.format(q) == '1 GHz'
    assert '{:.0p}'.format(q) == '1420405752 Hz'
    assert '{:#.0q}'.format(q) == '1 GHz'
    assert '{:#.0p}'.format(q) == '1420405752. Hz'

    q = Quantity('2ns')
    assert float(q) == 2e-9

    with pytest.raises(ValueError) as exception:
        q = Quantity('1ns')
        '{:z}'.format(q)
    assert exception.value.args[
        0] == "Unknown format code 'z' for object of type 'float'"
コード例 #13
0
ファイル: test_format.py プロジェクト: KenKundert/quantiphy
def test_currency():
    Quantity.set_prefs(
        spacer = None,
        show_label = None,
        label_fmt = None,
        label_fmt_full = None,
        show_desc = False,
        prec = 4,
    )
    q=Quantity('Total = $1000k -- a large amount of money')
    assert '{}'.format(q) == '$1M'
    assert '{:.8}'.format(q) == '$1M'
    assert '{:.8s}'.format(q) == '$1M'
    assert '{:.8S}'.format(q) == 'Total = $1M'
    assert '{:.8q}'.format(q) == '$1M'
    assert '{:.8Q}'.format(q) == 'Total = $1M'
    assert '{:r}'.format(q) == '1M'
    assert '{:R}'.format(q) == 'Total = 1M'
    assert '{:u}'.format(q) == '$'
    assert '{:.4f}'.format(q) == '1000000'
    assert '{:.4F}'.format(q) == 'Total = 1000000'
    assert '{:e}'.format(q) == '1e+06'
    assert '{:E}'.format(q) == 'Total = 1e+06'
    assert '{:g}'.format(q) == '1e+06'
    assert '{:G}'.format(q) == 'Total = 1e+06'
    assert '{:n}'.format(q) == 'Total'
    assert '{:d}'.format(q) == 'a large amount of money'
    assert '{:#p}'.format(q) == '$1000000.0000'
    assert '{:#.2p}'.format(q) == '$1000000.00'
    assert '{:#,.2p}'.format(q) == '$1,000,000.00'
    assert '{:#,P}'.format(q) == 'Total = $1,000,000.0000'
    assert '{:#.2P}'.format(q) == 'Total = $1000000.00'
    assert '{:#,.2P}'.format(q) == 'Total = $1,000,000.00'
    assert '{:p}'.format(q) == '$1000000'
    assert '{:.2p}'.format(q) == '$1000000'
    assert '{:,.2p}'.format(q) == '$1,000,000'
    assert '{:,P}'.format(q) == 'Total = $1,000,000'
    assert '{:.2P}'.format(q) == 'Total = $1000000'
    assert '{:,.2P}'.format(q) == 'Total = $1,000,000'

    q=Quantity('2ns')
    assert float(q) == 2e-9
コード例 #14
0
def test_mass():
    Quantity.set_prefs(spacer=None,
                       show_label=None,
                       label_fmt=None,
                       label_fmt_full=None)
    Quantity.set_prefs(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'
コード例 #15
0
ファイル: test_format.py プロジェクト: KenKundert/quantiphy
def test_format_method():
    Quantity.set_prefs(
        spacer = None,
        show_label = None,
        label_fmt = None,
        label_fmt_full = None,
        show_desc = False,
        prec = 4,
        strip_zeros = True,
    )
    q=Quantity('f = 1420.405751786 MHz -- frequency of hydrogen line')
    assert q.format() == '1.4204 GHz'
    assert q.format('') == '1.4204 GHz'
    assert q.format('.8') == '1.42040575 GHz'
    assert q.format('.8s') == '1.42040575 GHz'
    assert q.format('.8S') == 'f = 1.42040575 GHz'
    assert q.format('.8q') == '1.42040575 GHz'
    assert q.format('.8Q') == 'f = 1.42040575 GHz'
    assert q.format('r') == '1.4204G'
    assert q.format('R') == 'f = 1.4204G'
    assert q.format('u') == 'Hz'
    assert q.format('f') == '1420405751.786'
    assert q.format('F') == 'f = 1420405751.786'
    assert q.format('e') == '1.4204e+09'
    assert q.format('E') == 'f = 1.4204e+09'
    assert q.format('g') == '1.4204e+09'
    assert q.format('G') == 'f = 1.4204e+09'
    assert q.format('n') == 'f'
    assert q.format('d') == 'frequency of hydrogen line'
    assert q.format('p') == '1420405751.786 Hz'
    assert q.format(',p') == '1,420,405,751.786 Hz'
    assert q.format('P') == 'f = 1420405751.786 Hz'
    assert q.format(',P') == 'f = 1,420,405,751.786 Hz'
    assert q.format('#p') == '1420405751.7860 Hz'
    assert q.format('#,p') == '1,420,405,751.7860 Hz'
    assert q.format('#P') == 'f = 1420405751.7860 Hz'
    assert q.format('#,P') == 'f = 1,420,405,751.7860 Hz'
コード例 #16
0
ファイル: test_quantity.py プロジェクト: Djailla/quantiphy
def test_number_recognition():
    Quantity.set_prefs(spacer=None,
                       show_label=None,
                       label_fmt=None,
                       label_fmt_full=None)
    for case in test_cases:
        if not case:
            continue
        assert case.name not in names, '%s: duplicate test name' % case.name
        names.add(case.name)

        Quantity.set_prefs(prec=None,
                           full_prec=None,
                           spacer='',
                           unity_sf=None,
                           output_sf=None,
                           ignore_sf=None,
                           label_fmt=None,
                           assign_rec=None,
                           show_units=True,
                           strip_radix=True,
                           strip_zeros=True)
        try:
            if case.prefs:
                Quantity.set_prefs(**case.prefs)
            q = Quantity(case.text)
            assert ((q.render(form='eng', show_units=False),
                     q.units) == case.raw), case.name
            assert (str(q) == case.formatted), case.name
            # assure that the output value can be read as an input
            Quantity(str(q))
        except AssertionError:
            raise
        except (ValueError, KeyError):
            assert None is case.raw, case.name
        except Exception:
            print('%s: unexpected exception occurred.' % case.name)
            raise
    Quantity.set_prefs(prec=None,
                       full_prec=None,
                       spacer=None,
                       unity_sf=None,
                       output_sf=None,
                       ignore_sf=None,
                       label_fmt=None,
                       assign_rec=None)
コード例 #17
0
def test_distance():
    Quantity.set_prefs(spacer=None,
                       show_label=None,
                       label_fmt=None,
                       label_fmt_full=None)
    Quantity.set_prefs(ignore_sf=False)
    q = Quantity('1_m')
    assert q.render() == '1 m'
    assert q.render(scale='cm', show_si=False) == '100 cm'
    assert q.render(scale='mm', show_si=False) == '1e3 mm'
    assert q.render(scale='um', show_si=False) == '1e6 um'
    assert q.render(scale='μm', show_si=False) == '1e6 μm'
    assert q.render(scale='nm', show_si=False) == '1e9 nm'
    if sys.version_info.major == 3:
        assert q.render(scale='Å', show_si=False) == '10e9 Å'
    assert q.render(scale='angstrom', show_si=False) == '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'

    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'

    if sys.version_info.major == 3:
        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'

    if sys.version_info.major == 3:
        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'
コード例 #18
0
def test_constants():
    Quantity.set_prefs(spacer=None, show_label=None, label_fmt=None, label_fmt_full=None)
    Quantity.set_prefs(show_desc=True)
    assert '{:.12q}'.format(Quantity('h')) == '662.607004e-36 J-s'
    assert '{:.12q}'.format(Quantity('hbar')) == '105.45718e-36 J-s'
    assert '{:.12q}'.format(Quantity('ħ')) == '105.45718e-36 J-s'
    assert '{:.12q}'.format(Quantity('k')) == '13.8064852e-24 J/K'
    assert '{:.12q}'.format(Quantity('q')) == '160.21766208e-21 C'
    assert '{:.12q}'.format(Quantity('c')) == '299.792458 Mm/s'
    assert '{:.12q}'.format(Quantity('0C')) == '273.15 K'
    assert '{:.12q}'.format(Quantity('eps0')) == '8.854187817 pF/m'
    assert '{:.12q}'.format(Quantity('mu0')) == '1.256637061436 uH/m'
    assert '{:.12q}'.format(Quantity('Z0')) == '376.730313461 Ohms'

    assert str(Quantity('h')) == '662.61e-36 J-s'
    assert str(Quantity('hbar')) == '105.46e-36 J-s'
    assert str(Quantity('ħ')) == '105.46e-36 J-s'
    assert str(Quantity('k')) == '13.806e-24 J/K'
    assert str(Quantity('q')) == '160.22e-21 C'
    assert str(Quantity('c')) == '299.79 Mm/s'
    assert str(Quantity('0C')) == '273.15 K'
    assert str(Quantity('eps0')) == '8.8542 pF/m'
    assert str(Quantity('mu0')) == '1.2566 uH/m'
    assert str(Quantity('Z0')) == '376.73 Ohms'

    assert '{:S}'.format(Quantity('h')) == "h = 662.61e-36 J-s -- Plank's constant"
    assert '{:S}'.format(Quantity('hbar')) == "ħ = 105.46e-36 J-s -- reduced Plank's constant"
    assert '{:S}'.format(Quantity('ħ')) == "ħ = 105.46e-36 J-s -- reduced Plank's constant"
    assert '{:S}'.format(Quantity('k')) == "k = 13.806e-24 J/K -- Boltzmann's constant"
    assert '{:S}'.format(Quantity('q')) == 'q = 160.22e-21 C -- elementary charge'
    assert '{:S}'.format(Quantity('c')) == 'c = 299.79 Mm/s -- speed of light'
    assert '{:S}'.format(Quantity('0C')) == '0°C = 273.15 K -- zero degrees Celsius in Kelvin'
    assert '{:S}'.format(Quantity('eps0')) == 'ε₀ = 8.8542 pF/m -- permittivity of free space'
    assert '{:S}'.format(Quantity('mu0')) == 'μ₀ = 1.2566 uH/m -- permeability of free space'
    assert '{:S}'.format(Quantity('Z0')) == 'Z₀ = 376.73 Ohms -- characteristic impedance of free space'

    set_unit_system('cgs')
    assert '{:.12q}'.format(Quantity('h')) == '6.62607004e-27 erg-s'
    assert '{:.12q}'.format(Quantity('hbar')) == '1.0545718e-27 erg-s'
    assert '{:.12q}'.format(Quantity('ħ')) == '1.0545718e-27 erg-s'
    assert '{:.12q}'.format(Quantity('k')) == '138.064852 aerg/K'
    assert '{:.12q}'.format(Quantity('q')) == '480.320425 pFr'
    assert '{:.12q}'.format(Quantity('c')) == '299.792458 Mm/s'
    assert '{:.12q}'.format(Quantity('0C')) == '273.15 K'

    assert str(Quantity('h')) == '6.6261e-27 erg-s'
    assert str(Quantity('hbar')) == '1.0546e-27 erg-s'
    assert str(Quantity('ħ')) == '1.0546e-27 erg-s'
    assert str(Quantity('k')) == '138.06 aerg/K'
    assert str(Quantity('q')) == '480.32 pFr'
    assert str(Quantity('c')) == '299.79 Mm/s'
    assert str(Quantity('0C')) == '273.15 K'

    with pytest.raises(ValueError, message='fuzz: not a valid number.'):
        str(Quantity('fuzz'))

    assert '{:S}'.format(Quantity('h')) == "h = 6.6261e-27 erg-s -- Plank's constant"
    assert '{:S}'.format(Quantity('hbar')) == "ħ = 1.0546e-27 erg-s -- reduced Plank's constant"
    assert '{:S}'.format(Quantity('ħ')) == "ħ = 1.0546e-27 erg-s -- reduced Plank's constant"
    assert '{:S}'.format(Quantity('k')) == "k = 138.06 aerg/K -- Boltzmann's constant"
    assert '{:S}'.format(Quantity('q')) == 'q = 480.32 pFr -- elementary charge'
    assert '{:S}'.format(Quantity('c')) == 'c = 299.79 Mm/s -- speed of light'
    assert '{:S}'.format(Quantity('0C')) == '0°C = 273.15 K -- zero degrees Celsius in Kelvin'

    set_unit_system('mks')
    assert '{:.12q}'.format(Quantity('h')) == '662.607004e-36 J-s'
    assert '{:.12q}'.format(Quantity('hbar')) == '105.45718e-36 J-s'
    assert '{:.12q}'.format(Quantity('ħ')) == '105.45718e-36 J-s'
    assert '{:.12q}'.format(Quantity('k')) == '13.8064852e-24 J/K'
    assert '{:.12q}'.format(Quantity('q')) == '160.21766208e-21 C'
    assert '{:.12q}'.format(Quantity('c')) == '299.792458 Mm/s'
    assert '{:.12q}'.format(Quantity('0C')) == '273.15 K'
    assert '{:.12q}'.format(Quantity('eps0')) == '8.854187817 pF/m'
    assert '{:.12q}'.format(Quantity('mu0')) == '1.256637061436 uH/m'
    assert '{:.12q}'.format(Quantity('Z0')) == '376.730313461 Ohms'

    assert str(Quantity('h')) == '662.61e-36 J-s'
    assert str(Quantity('hbar')) == '105.46e-36 J-s'
    assert str(Quantity('ħ')) == '105.46e-36 J-s'
    assert str(Quantity('k')) == '13.806e-24 J/K'
    assert str(Quantity('q')) == '160.22e-21 C'
    assert str(Quantity('c')) == '299.79 Mm/s'
    assert str(Quantity('0C')) == '273.15 K'
    assert str(Quantity('eps0')) == '8.8542 pF/m'
    assert str(Quantity('mu0')) == '1.2566 uH/m'
    assert str(Quantity('Z0')) == '376.73 Ohms'

    assert '{:S}'.format(Quantity('h')) == "h = 662.61e-36 J-s -- Plank's constant"
    assert '{:S}'.format(Quantity('hbar')) == "ħ = 105.46e-36 J-s -- reduced Plank's constant"
    assert '{:S}'.format(Quantity('ħ')) == "ħ = 105.46e-36 J-s -- reduced Plank's constant"
    assert '{:S}'.format(Quantity('k')) == "k = 13.806e-24 J/K -- Boltzmann's constant"
    assert '{:S}'.format(Quantity('q')) == 'q = 160.22e-21 C -- elementary charge'
    assert '{:S}'.format(Quantity('c')) == 'c = 299.79 Mm/s -- speed of light'
    assert '{:S}'.format(Quantity('0C')) == '0°C = 273.15 K -- zero degrees Celsius in Kelvin'
    assert '{:S}'.format(Quantity('eps0')) == 'ε₀ = 8.8542 pF/m -- permittivity of free space'
    assert '{:S}'.format(Quantity('mu0')) == 'μ₀ = 1.2566 uH/m -- permeability of free space'
    assert '{:S}'.format(Quantity('Z0')) == 'Z₀ = 376.73 Ohms -- characteristic impedance of free space'

    add_constant('f_hy = 1420.405751786 MHz -- Frequency of hydrogen line')
    assert str(Quantity('f_hy')) == '1.4204 GHz'

    add_constant(Quantity('1420.405751786 MHz'), 'hline')
    assert str(Quantity('hline')) == '1.4204 GHz'
    add_constant(Quantity(4.80320427e-10, 'Fr'), 'q', 'esu gaussian')
    add_constant(Quantity(1.602176487e-20, 'abC'), alias='q', unit_systems='emu')
    assert str(Quantity('q')) == '160.22e-21 C'
    set_unit_system('cgs')
    assert str(Quantity('q')) == '480.32 pFr'
    set_unit_system('esu')
    assert str(Quantity('q')) == '480.32 pFr'
    set_unit_system('gaussian')
    assert str(Quantity('q')) == '480.32 pFr'
    set_unit_system('emu')
    assert str(Quantity('q')) == '16.022e-21 abC'
    set_unit_system('mks')

    with pytest.raises(NameError, message='No name specified.'):
        add_constant(Quantity(4.80320427e-10, 'Fr'), unit_systems='esu gaussian')
コード例 #19
0
    def run(cls, command, args, settings, options):
        # read command line
        cmdline = docopt(cls.USAGE, argv=[command] + args)
        archive = cmdline["--archive"]
        date = cmdline["--date"]

        # get the desired archive
        if date and not archive:
            archive = get_name_of_nearest_archive(settings, date)
        if not archive:
            archive = get_name_of_latest_archive(settings)
        output("Archive:", archive)

        # run borg
        borg = settings.run_borg(
            cmd="list",
            args=[settings.destination(archive)],
            emborg_opts=options,
        )
        out = borg.stdout

        # define available formats
        formats = dict(
            name="{path}",
            date="{day} {date} {time} {path}",
            size="{Size:<5.2r} {path}",
            owner="{owner:<8} {path}",
            group="{group:<8} {path}",
            long="{Size:<5.2r} {date} {time} {path}",
            full=
            "{permissions:<10} {owner:<6} {group:<6} {size:>8} {Date:YYMMDD HH:mm} {path}",
        )
        user_formats = settings.manifest_formats
        if user_formats:
            unknown = user_formats.keys() - formats.keys()
            if unknown:
                warn("unknown formats:",
                     ", ".join(unknown),
                     culprit="manifest_formats")
            formats.update(user_formats)

        # process sort options
        if cmdline["--sort-by-name"]:
            fmt = "name"

            def get_key(columns):
                return columns[7]

        elif cmdline["--sort-by-date"]:
            fmt = "date"

            def get_key(columns):
                date_time = " ".join(columns[5:7])
                return arrow.get(date_time, "YYYY-MM-DD HH:mm:ss")

        elif cmdline["--sort-by-size"]:
            fmt = "size"

            def get_key(columns):
                return int(columns[3])

        elif cmdline["--sort-by-owner"]:
            fmt = "owner"

            def get_key(columns):
                return columns[1]

        elif cmdline["--sort-by-group"]:
            fmt = "group"

            def get_key(columns):
                return columns[2]

        else:
            fmt = None
            get_key = None

        # process format options
        if cmdline["--name-only"]:
            fmt = "name"
        elif cmdline["--long"]:
            fmt = "long"
        elif cmdline["--full"]:
            fmt = "full"

        # sort the output
        lines = [l.split(maxsplit=7) for l in out.rstrip().splitlines()]
        if get_key:
            lines = sorted(lines, key=get_key)
        if cmdline["--reverse-sort"]:
            lines.reverse()

        # echo borg output if no formatting is necessary
        if not fmt:
            output(out)
            return

        # import QuantiPhy
        try:
            from quantiphy import Quantity

            Quantity.set_prefs(spacer="")
        except ImportError:
            comment("Could not import QuantiPhy.")

            def Quantity(value, units):
                return value

        # generate formatted output
        for columns in lines:
            output(
                formats[fmt].format(
                    permissions=columns[0],
                    owner=columns[1],
                    group=columns[2],
                    size=columns[3],
                    Size=Quantity(columns[3], "B"),
                    Date=arrow.get(" ".join(columns[5:7]),
                                   "YYYY-MM-DD HH:mm:ss"),
                    day=columns[4].rstrip(","),
                    date=columns[5],
                    time=columns[6],
                    path=columns[7],
                ),
                sep="\n",
            )
コード例 #20
0
ファイル: test_format.py プロジェクト: KenKundert/quantiphy
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'
コード例 #21
0
def test_constants():
    Quantity.set_prefs(spacer=None,
                       show_label=None,
                       label_fmt=None,
                       label_fmt_full=None)
    Quantity.set_prefs(show_desc=True)
    assert '{:.12q}'.format(Quantity('h')) == '662.607004e-36 J-s'
    assert '{:.12q}'.format(Quantity('hbar')) == '105.45718e-36 J-s'
    assert '{:.12q}'.format(Quantity('ħ')) == '105.45718e-36 J-s'
    assert '{:.12q}'.format(Quantity('k')) == '13.8064852e-24 J/K'
    assert '{:.12q}'.format(Quantity('q')) == '160.21766208e-21 C'
    assert '{:.12q}'.format(Quantity('c')) == '299.792458 Mm/s'
    assert '{:.12q}'.format(Quantity('0C')) == '273.15 K'
    assert '{:.12q}'.format(Quantity('eps0')) == '8.854187817 pF/m'
    assert '{:.12q}'.format(Quantity('mu0')) == '1.256637061436 uH/m'
    assert '{:.12q}'.format(
        Quantity('µ₀')) == '1.256637061436 uH/m'  # uses micro
    assert '{:.12q}'.format(Quantity('μ₀')) == '1.256637061436 uH/m'  # uses mu
    assert '{:.12q}'.format(Quantity('Z0')) == '376.730313461 Ohms'

    assert str(Quantity('h')) == '662.61e-36 J-s'
    assert str(Quantity('hbar')) == '105.46e-36 J-s'
    assert str(Quantity('ħ')) == '105.46e-36 J-s'
    assert str(Quantity('k')) == '13.806e-24 J/K'
    assert str(Quantity('q')) == '160.22e-21 C'
    assert str(Quantity('c')) == '299.79 Mm/s'
    assert str(Quantity('0C')) == '273.15 K'
    assert str(Quantity('eps0')) == '8.8542 pF/m'
    assert str(Quantity('mu0')) == '1.2566 uH/m'
    assert str(Quantity('µ₀')) == '1.2566 uH/m'  # uses micro
    assert str(Quantity('μ₀')) == '1.2566 uH/m'  # uses mu
    assert str(Quantity('Z0')) == '376.73 Ohms'

    assert '{:S}'.format(
        Quantity('h')) == "h = 662.61e-36 J-s -- Plank's constant"
    assert '{:S}'.format(
        Quantity('hbar')) == "ħ = 105.46e-36 J-s -- reduced Plank's constant"
    assert '{:S}'.format(
        Quantity('ħ')) == "ħ = 105.46e-36 J-s -- reduced Plank's constant"
    assert '{:S}'.format(
        Quantity('k')) == "k = 13.806e-24 J/K -- Boltzmann's constant"
    assert '{:S}'.format(
        Quantity('q')) == 'q = 160.22e-21 C -- elementary charge'
    assert '{:S}'.format(Quantity('c')) == 'c = 299.79 Mm/s -- speed of light'
    assert '{:S}'.format(
        Quantity('0C')) == '0°C = 273.15 K -- zero degrees Celsius in Kelvin'
    assert '{:S}'.format(
        Quantity('eps0')) == 'ε₀ = 8.8542 pF/m -- permittivity of free space'
    assert '{:S}'.format(
        Quantity('mu0')) == 'µ₀ = 1.2566 uH/m -- permeability of free space'
    assert '{:S}'.format(
        Quantity('µ₀')
    ) == 'µ₀ = 1.2566 uH/m -- permeability of free space'  # uses micro
    assert '{:S}'.format(Quantity(
        'μ₀')) == 'µ₀ = 1.2566 uH/m -- permeability of free space'  # uses mu
    assert '{:S}'.format(Quantity(
        'Z0')) == 'Z₀ = 376.73 Ohms -- characteristic impedance of free space'

    set_unit_system('cgs')
    assert '{:.12q}'.format(Quantity('h')) == '6.62607004e-27 erg-s'
    assert '{:.12q}'.format(Quantity('hbar')) == '1.0545718e-27 erg-s'
    assert '{:.12q}'.format(Quantity('ħ')) == '1.0545718e-27 erg-s'
    assert '{:.12q}'.format(Quantity('k')) == '138.064852 aerg/K'
    assert '{:.12q}'.format(Quantity('q')) == '480.320425 pFr'
    assert '{:.12q}'.format(Quantity('c')) == '299.792458 Mm/s'
    assert '{:.12q}'.format(Quantity('0C')) == '273.15 K'

    assert str(Quantity('h')) == '6.6261e-27 erg-s'
    assert str(Quantity('hbar')) == '1.0546e-27 erg-s'
    assert str(Quantity('ħ')) == '1.0546e-27 erg-s'
    assert str(Quantity('k')) == '138.06 aerg/K'
    assert str(Quantity('q')) == '480.32 pFr'
    assert str(Quantity('c')) == '299.79 Mm/s'
    assert str(Quantity('0C')) == '273.15 K'

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

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

    with pytest.raises(ValueError) as exception:
        str(Quantity(None, 'm', scale='in'))
    assert str(exception.value) == 'None: not a valid number.'
    assert isinstance(exception.value, InvalidNumber)
    assert isinstance(exception.value, QuantiPhyError)
    assert isinstance(exception.value, TypeError)
    assert exception.value.args == (None, )

    assert '{:S}'.format(
        Quantity('h')) == "h = 6.6261e-27 erg-s -- Plank's constant"
    assert '{:S}'.format(
        Quantity('hbar')) == "ħ = 1.0546e-27 erg-s -- reduced Plank's constant"
    assert '{:S}'.format(
        Quantity('ħ')) == "ħ = 1.0546e-27 erg-s -- reduced Plank's constant"
    assert '{:S}'.format(
        Quantity('k')) == "k = 138.06 aerg/K -- Boltzmann's constant"
    assert '{:S}'.format(
        Quantity('q')) == 'q = 480.32 pFr -- elementary charge'
    assert '{:S}'.format(Quantity('c')) == 'c = 299.79 Mm/s -- speed of light'
    assert '{:S}'.format(
        Quantity('0C')) == '0°C = 273.15 K -- zero degrees Celsius in Kelvin'

    set_unit_system('mks')
    assert '{:.12q}'.format(Quantity('h')) == '662.607004e-36 J-s'
    assert '{:.12q}'.format(Quantity('hbar')) == '105.45718e-36 J-s'
    assert '{:.12q}'.format(Quantity('ħ')) == '105.45718e-36 J-s'
    assert '{:.12q}'.format(Quantity('k')) == '13.8064852e-24 J/K'
    assert '{:.12q}'.format(Quantity('q')) == '160.21766208e-21 C'
    assert '{:.12q}'.format(Quantity('c')) == '299.792458 Mm/s'
    assert '{:.12q}'.format(Quantity('0C')) == '273.15 K'
    assert '{:.12q}'.format(Quantity('eps0')) == '8.854187817 pF/m'
    assert '{:.12q}'.format(Quantity('mu0')) == '1.256637061436 uH/m'
    assert '{:.12q}'.format(
        Quantity('µ₀')) == '1.256637061436 uH/m'  # uses micro
    assert '{:.12q}'.format(Quantity('μ₀')) == '1.256637061436 uH/m'  # uses mu
    assert '{:.12q}'.format(Quantity('Z0')) == '376.730313461 Ohms'

    assert str(Quantity('h')) == '662.61e-36 J-s'
    assert str(Quantity('hbar')) == '105.46e-36 J-s'
    assert str(Quantity('ħ')) == '105.46e-36 J-s'
    assert str(Quantity('k')) == '13.806e-24 J/K'
    assert str(Quantity('q')) == '160.22e-21 C'
    assert str(Quantity('c')) == '299.79 Mm/s'
    assert str(Quantity('0C')) == '273.15 K'
    assert str(Quantity('eps0')) == '8.8542 pF/m'
    assert str(Quantity('mu0')) == '1.2566 uH/m'
    assert str(Quantity('µ₀')) == '1.2566 uH/m'  # uses micro
    assert str(Quantity('μ₀')) == '1.2566 uH/m'  # uses mu
    assert str(Quantity('Z0')) == '376.73 Ohms'

    assert '{:S}'.format(
        Quantity('h')) == "h = 662.61e-36 J-s -- Plank's constant"
    assert '{:S}'.format(
        Quantity('hbar')) == "ħ = 105.46e-36 J-s -- reduced Plank's constant"
    assert '{:S}'.format(
        Quantity('ħ')) == "ħ = 105.46e-36 J-s -- reduced Plank's constant"
    assert '{:S}'.format(
        Quantity('k')) == "k = 13.806e-24 J/K -- Boltzmann's constant"
    assert '{:S}'.format(
        Quantity('q')) == 'q = 160.22e-21 C -- elementary charge'
    assert '{:S}'.format(Quantity('c')) == 'c = 299.79 Mm/s -- speed of light'
    assert '{:S}'.format(
        Quantity('0C')) == '0°C = 273.15 K -- zero degrees Celsius in Kelvin'
    assert '{:S}'.format(
        Quantity('eps0')) == 'ε₀ = 8.8542 pF/m -- permittivity of free space'
    assert '{:S}'.format(
        Quantity('mu0')) == 'µ₀ = 1.2566 uH/m -- permeability of free space'
    assert '{:S}'.format(
        Quantity('µ₀')
    ) == 'µ₀ = 1.2566 uH/m -- permeability of free space'  # uses micro
    assert '{:S}'.format(Quantity(
        'μ₀')) == 'µ₀ = 1.2566 uH/m -- permeability of free space'  # uses mu
    assert '{:S}'.format(Quantity(
        'Z0')) == 'Z₀ = 376.73 Ohms -- characteristic impedance of free space'

    add_constant('f_hy = 1420.405751786 MHz -- Frequency of hydrogen line')
    assert str(Quantity('f_hy')) == '1.4204 GHz'

    add_constant(Quantity('1420.405751786 MHz'), 'hline')
    assert str(Quantity('hline')) == '1.4204 GHz'
    add_constant(Quantity(4.80320427e-10, 'Fr'), 'q', 'esu gaussian')
    add_constant(Quantity(1.602176487e-20, 'abC'),
                 alias='q',
                 unit_systems='emu')
    assert str(Quantity('q')) == '160.22e-21 C'
    set_unit_system('cgs')
    assert str(Quantity('q')) == '480.32 pFr'
    set_unit_system('esu')
    assert str(Quantity('q')) == '480.32 pFr'
    set_unit_system('gaussian')
    assert str(Quantity('q')) == '480.32 pFr'
    set_unit_system('emu')
    assert str(Quantity('q')) == '16.022e-21 abC'
    set_unit_system('mks')

    with pytest.raises(NameError) as exception:
        add_constant(Quantity(4.80320427e-10, 'Fr'),
                     unit_systems='esu gaussian')
    assert str(exception.value) == 'no name specified.'
    assert isinstance(exception.value, MissingName)
    assert isinstance(exception.value, QuantiPhyError)
    assert isinstance(exception.value, NameError)
    assert exception.value.args == ()

    with pytest.raises(ValueError) as exception:
        add_constant(1)
    assert str(exception.value) == 'expected a quantity for value.'
    assert isinstance(exception.value, ExpectedQuantity)
    assert isinstance(exception.value, QuantiPhyError)
    assert isinstance(exception.value, ValueError)
    assert exception.value.args == ()

    with pytest.raises(KeyError) as exception:
        set_unit_system('nuts')
    assert str(exception.value) == 'nuts: unknown unit system.'
    assert isinstance(exception.value, UnknownUnitSystem)
    assert isinstance(exception.value, QuantiPhyError)
    assert isinstance(exception.value, KeyError)
    assert exception.value.args == ('nuts', )

    add_constant('f_hy = 1420.405751786 MHz',
                 alias=['hl', 'HL', 'hydrogen line'])
    assert str(Quantity('f_hy')) == '1.4204 GHz'
    assert str(Quantity('hl')) == '1.4204 GHz'
    assert str(Quantity('HL')) == '1.4204 GHz'
    assert str(Quantity('hydrogen line')) == '1.4204 GHz'
コード例 #22
0
def test_namespace():
    Quantity.reset_prefs()
    Quantity.set_prefs(spacer=None,
                       show_label=None,
                       label_fmt=None,
                       label_fmt_full=None)
    globals().update(
        Quantity.extract('''
        h_line = 1420.405751786 MHz -- Frequency of the hydrogen line
        k = 13.806488e-24 J/K -- Boltzmann's constant
        Temp = 300_K -- Temperature
        M = 2  -- Divide ratio of HF divider
        N = 8  -- Divide ratio of MF divider
        F = 2  -- Divide ratio of LF divider
        Fref = 156MHz  -- Reference frequency
        Kdet = 88.3uA  -- Gain of phase detector (Imax)
        Kvco = 9.07GHz/V  -- Gain of VCO
        Cs = 1.41pF  -- Shunt capacitance
        Cp = 59.7pF  -- Pole capacitance
        Rz = 2.24KOhms  -- Zero resistance
        Fstart = 1KHz  -- Lower frequency bound
        Fstop = 1GHz  -- Upper frequency bound
        Spd = 1.47E-24 A^2/Hz  -- Spectral density of the output noise of the PFD/CP
        FcorPD = 1.5MHz  -- PFD/CP flicker noise corner frequency
        JdivM = 2.43E-18 s/rt(Hz)  -- Spectral density of the output jitter of divM
        FcorDivM = 7MHz  -- divM flicker noise corner frequency
        JdivN = 4.47E-18 s/rt(Hz)  -- Spectral density of the output jitter of divN
        FcorDivN = 1.5MHz  -- divN flicker noise corner frequency
        JdivF = 1.82E-17 s/rt(Hz)  -- Spectral density of the output jitter of divF
        FcorDivF = 2MHz  -- divF flicker noise corner frequency
        Jbuf = 3.70E-18 s/rt(Hz)  -- Spectral density of the output jitter of output buffer
        FcorBuf = 2.5MHz  -- buf flicker noise corner frequency
        Lvco = -125.00 dBc/Hz -- Oscillator phase noise injected after VCO
        FcorVCO = 3MHz  -- VCO flicker noise corner frequency
        Lref = -110.00 dbc/Hz -- Oscillator phase noise injected at reference input
        FcorRef = 0_Hz  -- Freq. reference flicker noise corner frequency
        FmaskLFcor = 12kHz  -- Jitter generation mask low frequency corner
        FmaskHFbound = 5MHz  -- Jitter generation mask high frequency bound

        -- The remainder are built in constants
        plank = h  -- Plank's constant
        boltz = k  -- Boltzmann's constant
        ec = q  -- Elementary charge
        speed_of_light = c -- Speed of light
        zero_celsius = 0C -- Zero degree Celsius in Kelvin
        epsilon0 = eps0 -- Permittivity of free space
        mu0 = mu0 -- Permeability of free space
        Z0 = Z0 -- Characteristic impedance of free space
        c = c  -- speed of light
    '''))

    assert str(h_line) == '1.4204 GHz'
    assert str(k) == '13.806e-24 J/K'
    assert str(Temp) == '300 K'
    assert str(M) == '2'
    assert str(N) == '8'
    assert str(F) == '2'
    assert str(Fref) == '156 MHz'
    assert str(Kdet) == '88.3 uA'
    assert str(Kvco) == '9.07 GHz/V'
    assert str(Cs) == '1.41 pF'
    assert str(Cp) == '59.7 pF'
    assert str(Rz) == '2.24 kOhms'
    assert str(Fstart) == '1 kHz'
    assert str(Fstop) == '1 GHz'
    assert str(Spd) == '1.47e-24 A^2/Hz'
    assert str(FcorPD) == '1.5 MHz'
    assert str(JdivM) == '2.43 as/rt(Hz)'
    assert str(FcorDivM) == '7 MHz'
    assert str(JdivN) == '4.47 as/rt(Hz)'
    assert str(FcorDivN) == '1.5 MHz'
    assert str(JdivF) == '18.2 as/rt(Hz)'
    assert str(FcorDivF) == '2 MHz'
    assert str(Jbuf) == '3.7 as/rt(Hz)'
    assert str(FcorBuf) == '2.5 MHz'
    assert str(Lvco) == '-125 dBc/Hz'
    assert str(FcorVCO) == '3 MHz'
    assert str(Lref) == '-110 dbc/Hz'
    assert str(FcorRef) == '0 Hz'
    assert str(FmaskLFcor) == '12 kHz'
    assert str(FmaskHFbound) == '5 MHz'
    assert str(plank) == '662.61e-36 J-s'
    assert str(boltz) == '13.806e-24 J/K'
    assert str(ec) == '160.22e-21 C'
    assert str(speed_of_light) == '299.79 Mm/s'
    assert str(zero_celsius) == '273.15 K'
    assert str(epsilon0) == '8.8542 pF/m'
    assert str(mu0) == '1.2566 uH/m'
    assert str(Z0) == '376.73 Ohms'
コード例 #23
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'
コード例 #24
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
コード例 #25
0
def test_add():
    Quantity.set_prefs(spacer=None,
                       show_label=None,
                       label_fmt=None,
                       label_fmt_full=None)
    q1 = Quantity('1ns')
    q2 = Quantity('2ns')
    assert str(q1.add(q2)) == '3 ns'
    assert repr(q1.add(q2)) == "Quantity('3 ns')"
    assert str(q2.add(q1)) == '3 ns'
    assert repr(q2.add(q1)) == "Quantity('3 ns')"
    assert str(q1.add(q2, check_units=False)) == '3 ns'
    assert str(q1.add(q2, check_units=True)) == '3 ns'
    assert str(q1.add(q2, check_units='strict')) == '3 ns'
    assert str(q1.add(2e-9, check_units=False)) == '3 ns'
    assert str(q1.add(2e-9, check_units=True)) == '3 ns'
    with pytest.raises(TypeError) as exception:
        q1.add(2e-9, check_units='strict')
    q3 = Quantity('2nm')
    assert str(q1.add(q3, check_units=False)) == '3 ns'
    with pytest.raises(TypeError) as exception:
        q1.add(q3, check_units=True)
    with pytest.raises(TypeError) as exception:
        q1.add(q3, check_units='strict')

    q1.name = 'period'
    assert q1.add(q2).name == 'period'
    q1.desc = 'duration of one cycle'
    assert q1.add(q2).name == 'period'
    assert q1.add(q2).desc == 'duration of one cycle'

    class Dollars(Quantity):
        units = '$'
        prec = 2
        form = 'fixed'
        show_commas = True
        if sys.version_info.major == 3:
            minus = Quantity.minus_sign
        strip_zeros = False

    total = Dollars(0)
    assert str(total) == '$0.00'
    total = total.add(1000000)
    assert str(total) == '$1,000,000.00'
    total = total.add(Quantity('-2MHz'), check_units=False)
    if sys.version_info.major == 3:
        assert str(total) == '−$1,000,000.00'
    else:
        assert str(total) == '-$1,000,000.00'
    with pytest.raises(IncompatibleUnits) as exception:
        total.add(Quantity('-2MHz'), check_units=True)
    total = total.add(Quantity('$6M'), check_units=True)
    assert str(total) == '$5,000,000.00'

    class WholeDollars(Dollars):
        prec = 0

    total = WholeDollars(0)
    total.name = 'total'
    assert str(total) == '$0'
    total = total.add(1000000)
    assert str(total) == '$1,000,000'
    assert total.name == 'total'
    total = total.add(Quantity('-2MHz'), check_units=False)
    if sys.version_info.major == 3:
        assert str(total) == '−$1,000,000'
    else:
        assert str(total) == '-$1,000,000'
    assert total.name == 'total'
    with pytest.raises(IncompatibleUnits) as exception:
        total.add(Quantity('-2MHz'), check_units=True)
    total = total.add(Quantity('$6M'), check_units=True)
    assert str(total) == '$5,000,000'
    assert total.name == 'total'
コード例 #26
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(form='eng', show_units=False) == '1.4204e9'

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

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

    s = Quantity('1420405751.786 Hz').render(form='eng',
                                             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(form='si', show_units=False)
    assert t == '1.4204G'

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

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

    f = Quantity('14204.05751786MHz').render(form='si',
                                             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() is None

    q = Quantity('1420405751.786 Hz')
    assert q.is_infinite() is None

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

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

    q = Quantity('NaN Hz')
    assert q.is_infinite() is None

    q = Quantity('inf Hz')
    assert q.is_nan() is None

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

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

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

    q = Quantity('$∞')
    assert q.is_infinite() == 'inf'

    q = Quantity('∞Ω')
    assert q.is_infinite() == 'inf'

    # 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 == ''

    if py3:
        # check tight_units
        q = Quantity('90°')
        assert q.render() == '90°'

        q = Quantity('80°F')
        assert q.render() == '80 °F'

        q = Quantity('80°F')
        assert q.render() == '80 °F'
        q.tight_units = '''' % ° ' " ′ ″ °F °C '''.split()
        assert q.render() == '80°F'
コード例 #27
0
def test_temperature():
    Quantity.set_prefs(spacer=None,
                       show_label=None,
                       label_fmt=None,
                       label_fmt_full=None)
    Quantity.set_prefs(ignore_sf=True)
    if sys.version_info.major == 3:
        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'
    if sys.version_info.major == 3:
        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'
    if sys.version_info.major == 3:
        assert q.render(scale='°C') == '100 °C'
        assert q.render(scale='°F') == '212 °F'
        assert q.render(scale='°R') == '671.67 °R'

    if sys.version_info.major == 3:
        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'
    if sys.version_info.major == 3:
        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'

    if sys.version_info.major == 3:
        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'
コード例 #28
0
ファイル: test_format.py プロジェクト: KenKundert/quantiphy
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>'
コード例 #29
0
    L4 = 1.1034 * Lscale "H"
    C5 = 2.2873 * Cscale "F"
"""

try:
    from svg_schematic import (Schematic, Capacitor, Dot, Ground, Inductor,
                               Label, Resistor, Pin, Source, Wire)
    from inform import Error, error, os_error
    from quantiphy import Quantity
    from math import pi
except ImportError:
    print('Run `pip install --user -r requirements.txt`',
          'to install missing packages.')
    raise SystemExit

Quantity.set_prefs(map_sf=Quantity.map_sf_to_greek, prec=2)
globals().update(Quantity.extract(__doc__, predefined={'π': pi}))

try:
    with Schematic(filename='mfed.svg', line_width=2, background='none'):

        vin = Source(name='Vin', value='1 V', kind='sine')
        Ground(C=vin.n)
        rs = Resistor(name='Rs', value=Rref, n=vin.p, xoff=25)
        Wire([vin.p, rs.n])
        c1 = Capacitor(name='C1', value=C1, p=rs.p, xoff=25)
        Ground(C=c1.n)
        l2 = Inductor(name='L2', value=L2, n=c1.p, xoff=25)
        Wire([rs.p, l2.n])
        c3 = Capacitor(name='C3', value=C3, p=l2.p, xoff=25)
        Ground(C=c3.n)
コード例 #30
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'