Skip to content

Pint + uncertainties in 2022 #1611

@MichaelTiemannOSC

Description

@MichaelTiemannOSC

Pint, Pandas, and Pint-Pandas have all made such great strides in the past year. With just a little more work, I believe we can support uncertainties in Pint in a clean way using PintPandas (see hgrecco/pint-pandas#139). Alas, Pint trips itself when passing notes to itself because the formatting of uncertainties is not actually Python. When the Python tokenizer sees something like 4.4+/-0.9 meter the parser complains missing unary operator "/"

What unary operator, you might ask? The / between the + and the -.

Here's the testcase:

import pytest

from pint import DimensionalityError
from pint.testsuite import QuantityTestCase, helpers

from pint.facets.plain.quantity import PlainQuantity as Quantity
from pint.facets.measurement.objects import Measurement

from pint.compat import HAS_UNCERTAINTIES
assert(HAS_UNCERTAINTIES)
from uncertainties import ufloat, UFloat
from uncertainties import unumpy as unp

Q_ = Quantity
M_ = Measurement

@helpers.requires_uncertainties()
class TestUncertainties(QuantityTestCase):
    def test_uncertainties_fmt(self):
        from numpy.testing import assert_almost_equal
	from uncertainties import ufloat

        u1 = ufloat(1.2, 0.34)
        u2 = ufloat(5.6, 0.78)
        q1_u = module_registry.Quantity(u2 - u1, "m")
        q1_str = str(q1_u)
        q1_str = "{:.4uS}".format(q1_u)
        q1_m = q1_u.magnitude
        q2_u = module_registry.Quantity(q1_str)
        # Not equal because the uncertainties are differently random!                                                                                                                                                                                                                   
        assert q1_u != q2_u
        q2_m = q2_u.magnitude

        assert_almost_equal(q2_m.nominal_value, q1_m.nominal_value, decimal=9)
        assert_almost_equal(q2_m.std_dev, q1_m.std_dev, decimal=4)

	q3_str = "12.34(5678)e-066 m"
        q3_u = module_registry.Quantity(q3_str)
	q3_m = q3_u.magnitude
        assert q3_m < 1

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions