Example #1
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'
Example #2
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'
Example #3
0
    def _plot(self):

        # create plot
        fig = plt.figure()
        ax = plt.subplot(111)
        ax.scatter(self.times,
                   self.frequencies,
                   color="#00A2FF",
                   label='Frequency')

        # grid
        plt.grid(b=True,
                 which='major',
                 color='k',
                 linestyle='-',
                 alpha=0.2,
                 linewidth=0.3)
        plt.grid(b=True,
                 which='minor',
                 color='k',
                 linestyle='-',
                 alpha=0.15,
                 linewidth=0.15)
        plt.minorticks_on()

        # limits
        #ax.set_xlim([freq.min(),freq.max()])

        #plt.xticks([0,len(freq)], freq)

        # layout
        fig.set_tight_layout(True)
        plt.rcParams.update({'font.size': 8})

        avg = Quantity(self.frequencies.mean(), "Hz")
        avg = SetPrecisionToResolution(avg, self.resolution / 10.0)
        std = Quantity(self.frequencies.std(), "Hz")

        ax.annotate(
            "Sample rate: %s, gate time: %s\nmean: %s, std: %s" %
            (Quantity(self.rate, "Hz").render(), Quantity(
                self.gate, "s").render(), avg.render(), std.render()),
            xy=(1, 0),
            xycoords='axes fraction',
            fontsize=8,
            xytext=(-5, 5),
            textcoords='offset points',
            ha='right',
            va='bottom')

        # axis labels
        plt.xlabel("Time [s]")
        plt.ylabel("Frequency [Hz]")

        #PYTHON....There's a matplotlib bug coming up here'
        with warnings.catch_warnings():
            warnings.simplefilter(action='ignore', category=FutureWarning)
            plt.show()
Example #4
0
def test_add():
    total = Quantity(0, '$')
    for contribution in [1.23, 4.56, 7.89]:
        total = total.add(contribution)
    assert total.render() == '$13.68'
    for contribution in [1.23, 4.56, 8.89]:
        total = total.add(contribution, check_units=True)
    assert total.render() == '$28.36'
    for contribution in [1.23, 4.56, 9.89]:
        total = total.add(Quantity(contribution, '$'), check_units=True)
    assert total.render() == '$44.04'
    try:
        total = total.add(Quantity(contribution, 'lbs'), check_units=True)
        assert False
    except TypeError:
        assert True
Example #5
0
    def _collect_data(self):

        state, index = self.scope.locate_buffer(
            channel=self.channel,
            samples=int(self.samples),
            segment=0,
            mode=self.scope.m.RatioModes.raw,
            downsample=0)

        while self.stopRequested == False:

            starttime = time.time()
            status = self.scope.collect_segment(segment=0,
                                                timebase=self.timebase)
            status, data = self.scope.get_buffer_volts(0)
            endtime = time.time()
            self.timeCounter += endtime - starttime
            self.times = np.append(self.times, self.timeCounter)

            freq = float(self._number_of_crossings(data, 0.0)) / self.gate
            freq = TruncateToResolution(freq, self.resolution)
            self.frequencies = np.append(self.frequencies, freq)
            freq = Quantity(freq, "Hz")
            freq = SetPrecisionToResolution(freq, self.resolution)

            self.frequencyLabel._text = "Frequency: %s" % freq.render()
            #try:
            #	freqDerivative = np.gradient(self.frequencies)[-1]
            #	self.frequencyDerivativeLabel._text = "Frequency': %s" % freqDerivative
            #except:
            #	None

            avg = Quantity(self.frequencies.mean(), "Hz")
            avg = SetPrecisionToResolution(avg, self.resolution / 10.0)
            self.meanLabel._text = "Average:   %s" % avg.render()

            self.stdLabel._text = "Deviation: %s" % Quantity(
                self.frequencies.std(), "Hz").render()

            self.gateCounter += 1
            self.sampleCounter += self.samples
            self.gatesLabel._text = "Gates:     %s" % Quantity(
                self.gateCounter).render()
            self.timeLabel._text = "Time:      %s" % Quantity(
                self.timeCounter, "s").render()
            self.totalSamplesLabel._text = "Samples:   %s" % Quantity(
                self.sampleCounter, "S").render()

            self.screen.force_update()

        self.stopButton.disabled = True
        self.startButton.disabled = False
        self.plotButton.disabled = False
        self.saveButton.disabled = False
class Currency:
    def __init__(self, tokens, price=0):
        self.tokens = Quantity(tokens, self.UNITS)
        if price < 0:
            raise Error('price must not be negative.', culprit=self.name())
        self.price = Dollars(price)

    def in_tokens(self):
        return self.tokens

    def in_dollars(self, price=None):
        price = self.price if price is None else price
        return Dollars(self.tokens * price)

    def name(self):
        return self.__class__.__name__

    def __str__(self):
        return self.tokens.render()

    def __float__(self):
        return float(self.tokens)

    @classmethod
    def converter(cls, to, data):
        try:
            # SYMBOL is not unique
            #return UnitConversion(to, (cls.SYMBOL, cls.UNITS), data[cls.UNITS][to[-1]])
            return UnitConversion(to, cls.UNITS, data[cls.UNITS][to[-1]])
        except KeyError as e:
            comment(f'missing price in {e}.', culprit=cls.UNITS)

    @classmethod
    def names(cls):
        for s in cls.__subclasses__():
            yield s.__name__

    @classmethod
    def units(cls):
        for s in cls.__subclasses__():
            yield s.UNITS

    @classmethod
    def currencies(cls):
        for s in sorted(cls.__subclasses__(), key=lambda s: s.__name__):
            yield s

    @classmethod
    def currency(cls, name):
        for s in cls.__subclasses__():
            if name == s.__name__:
                return s
Example #7
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
Example #8
0
def test_plus_minus():
    with Quantity.prefs(
        spacer = None,
        show_label = None,
        label_fmt = None,
        label_fmt_full = None,
        show_desc = False,
        prec = 4,
        plus = Quantity.plus_sign,
        minus = Quantity.minus_sign,
        map_sf = Quantity.map_sf_to_sci_notation,
    ):
        qpp=Quantity('+1Ms')
        qpm=Quantity('+1us')
        qmp=Quantity('-1Ms')
        qmm=Quantity('-1us')

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

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

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

        assert qpp.render(form='sia') == '1 Ms'
        assert qpm.render(form='sia') == '1 us'
        assert qmp.render(form='sia') == '−1 Ms'
        assert qmm.render(form='sia') == '−1 us'
Example #9
0
def test_mass():
    with Quantity.prefs(
        spacer=None, show_label=None, label_fmt=None, label_fmt_full=None,
        ignore_sf=False
    ):
        q=Quantity('1 g')
        assert q.render() == '1 g'
        assert q.render(scale='oz') == '35.274 moz'
        assert q.render(scale='lb') == '2.2046 mlb'
        assert q.render(scale='lbs') == '2.2046 mlbs'

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

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

        q=Quantity('1 lbs', scale='g')
        assert q.render() == '453.59 g'
Example #10
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'
Example #11
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'
Example #12
0
def test_simple_scaling():
    Quantity.reset_prefs()
    with Quantity.prefs(
        spacer=None, show_label=None, label_fmt=None, label_fmt_full=None
    ):
        q=Quantity('1kg', scale=2)
        qs=Quantity('2ms')
        assert q.render() == '2 kg'
        assert qs.render() == '2 ms'
        assert q.render(scale=0.001) == '2 g'
        assert str(q.scale(0.001)) == '2 g'
        assert q.render(scale=qs) == '4 g'
        assert str(q.scale(qs)) == '4 g'
        with pytest.raises(KeyError) as exception:
            q.render(scale='fuzz')
        assert str(exception.value) == "unable to convert between 'fuzz' and 'g'."
        assert isinstance(exception.value, UnknownConversion)
        assert isinstance(exception.value, QuantiPhyError)
        assert isinstance(exception.value, KeyError)
        assert exception.value.args == ('fuzz', 'g')
        with pytest.raises(KeyError) as exception:
            q.scale('fuzz')
        assert str(exception.value) == "unable to convert between 'fuzz' and 'g'."
        assert isinstance(exception.value, UnknownConversion)
        assert isinstance(exception.value, QuantiPhyError)
        assert isinstance(exception.value, KeyError)
        assert exception.value.args == ('fuzz', 'g')

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

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

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

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

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

        q=Quantity('-40 dBV', scale=adB)
        assert q.render() == '10 mV'
        assert q.render(scale=dB) == '-40 dBV'
        assert str(q.scale(dB)) == '-40 dBV'
Example #13
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'
Example #14
0
def to_rkm(q, prec=None, show_units=None, strip_zeros=None, strip_code=None):
    '''To RKM

    Convert a quantiphy.Quantity to an RKM string.

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

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

    sf = value[-1]
    if sf and sf in q.output_sf:
        value = value[:-1]
    elif units:
        sf = ''
    else:
        sf = rkm_base_code
    if '.' not in value:
        value += '.'
    if strip_zeros:
        value = value.rstrip('0')
    if value.startswith('0.') and value[-1] != '.':
        value = value[1:]
    if not sf:
        if units:
            sf = units
            units = ''
        else:
            sf = rkm_base_code
    if strip_code and sf == rkm_base_code:
        value = value.rstrip('.')
    if is_negative:
        value = '-' + value
    value = value.replace('-', _minus_sign)
    return value.replace('.', _map_sf.get(sf, sf)+units)
Example #15
0
def test_writer():
    q = Quantity('mem = 1GiB', binary=True)

    res = str(q)
    exp = '1.0737 GB'
    assert res == exp, res

    res = q.binary()
    exp = '1 GiB'
    assert res == exp, res

    res = q.render(form='binary')
    exp = '1 GiB'
    assert res == exp, res

    res = '{q:b}'.format(**locals())
    exp = '1 GiB'
    assert res == exp, res

    res = q.binary(prec=2, strip_zeros=False)
    exp = '1.00 GiB'
    assert res == exp, res

    res = '{q:#0.2b}'.format(**locals())
    exp = '1.00 GiB'
    assert res == exp, res

    res = q.binary(show_label=True)
    exp = 'mem = 1 GiB'
    assert res == exp, res

    res = '{q:B}'.format(**locals())
    exp = 'mem = 1 GiB'
    assert res == exp, res

    res = q.binary(show_label=True, scale='b')
    exp = 'mem = 8 Gib'
    assert res == exp, res

    res = '{q:Bb}'.format(**locals())
    exp = 'mem = 8 Gib'
    assert res == exp, res

    res = q.binary(strip_zeros=False)
    exp = '1.0000 GiB'
    assert res == exp, res

    res = '{q:#b}'.format(**locals())
    exp = '1.0000 GiB'
    assert res == exp, res

    res = q.binary(strip_zeros=True, strip_radix=False)
    exp = '1. GiB'
    assert res == exp, res

    q = Quantity('1GB', binary=True)

    res = str(q)
    exp = '1 GB'
    assert res == exp, res

    res = q.binary()
    exp = '953.67 MiB'
    assert res == exp, res

    res = '{q:b}'.format(**locals())
    exp = '953.67 MiB'
    assert res == exp, res

    res = q.binary(prec=2)
    exp = '954 MiB'
    assert res == exp, res

    res = '{q:0.2b}'.format(**locals())
    exp = '954 MiB'
    assert res == exp, res
Example #16
0
def test_scale():
    Quantity.reset_prefs()
    secs = Quantity('86400 s')
    days = secs.scale('day')
    assert secs.render() == '86.4 ks'
    assert days.render() == '1 day'
Example #17
0
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'
Example #18
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
Example #19
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'
Example #20
0
def test_temperature():
    Quantity.reset_prefs()
    with Quantity.prefs(
        spacer=None, show_label=None, label_fmt=None, label_fmt_full=None,
        ignore_sf=True
    ):
        q=Quantity('100 °C')
        assert q.render() == '100 °C'
        assert q.render(scale='C') == '100 C'
        assert q.render(scale='°C') == '100 °C'
        assert q.render(scale='K') == '373.15 K'
        assert q.render(scale='°F') == '212 °F'
        assert q.render(scale='F') == '212 F'
        assert q.render(scale='°R') == '671.67 °R'
        assert q.render(scale='R') == '671.67 R'

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

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

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

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

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

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

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

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

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

        q=Quantity('491.67 R', scale='K')
        assert q.render() == '273.15 K'
Example #21
0
def test_misc():
    Quantity.reset_prefs()
    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 == ''

    # check some exceptions
    with pytest.raises(ValueError) as exception:
        q = Quantity('f_hy = 1420405751;786 Hz')
    assert str(exception.value) == '1420405751;786 Hz: not a valid number.'
    assert isinstance(exception.value, InvalidNumber)
    assert isinstance(exception.value, QuantiPhyError)
    assert isinstance(exception.value, ValueError)
    assert exception.value.args == ('1420405751;786 Hz', )

    # check some exceptions
    with pytest.raises(ValueError) as exception:
        q = Quantity('# nan')
    assert str(exception.value) == '# nan: not a valid number.'
    assert isinstance(exception.value, InvalidNumber)
    assert isinstance(exception.value, QuantiPhyError)
    assert isinstance(exception.value, ValueError)
    assert exception.value.args == ('# nan', )

    # 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'
Example #22
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'
Example #23
0
def test_distance():
    Quantity.reset_prefs()
    with Quantity.prefs(
        spacer=None, show_label=None, label_fmt=None, label_fmt_full=None,
        ignore_sf=False
    ):
        q=Quantity('1_m')
        assert q.render() == '1 m'
        assert q.render(scale='cm', form='eng') == '100 cm'
        assert q.render(scale='mm', form='eng') == '1e3 mm'
        assert q.render(scale='um', form='eng') == '1e6 um'
        assert q.render(scale='μm', form='eng') == '1e6 μm'
        assert q.render(scale='nm', form='eng') == '1e9 nm'
        assert q.render(scale='Å', form='eng') == '10e9 Å'
        assert q.render(scale='angstrom', form='eng') == '10e9 angstrom'
        assert q.render(scale='mi') == '621.37 umi'
        assert q.render(scale='mile') == '621.37 umile'
        assert q.render(scale='miles') == '621.37 umiles'
        assert q.render(scale='in') == '39.37 in'
        assert q.render(scale='inch') == '39.37 inch'
        assert q.render(scale='inches') == '39.37 inches'

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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