Exemplo n.º 1
0
def test_issue_86():
    a = PintArray([1, 2], ureg.m)
    b_listlike = [1 * ureg.km, 1 * ureg.m]
    units = b_listlike[0].units
    b_pa = PintArray([v.m_as(units) for v in b_listlike], units)

    assert np.all(a + b_listlike == a + b_pa)
Exemplo n.º 2
0
def test_issue_88():
    q_m = ureg.Quantity([1, 2], "m")
    a = PintArray(q_m)
    helpers.assert_quantity_almost_equal(q_m, a.quantity)

    q_mm = ureg.Quantity([1000, 2000], "mm")
    b = PintArray(q_mm, "m")
    helpers.assert_quantity_almost_equal(q_m, b.quantity)
Exemplo n.º 3
0
 def test_pintarray_creation(self):
     x = ureg.Quantity([1, 2, 3], "m")
     ys = [
         PintArray.from_1darray_quantity(x),
         PintArray._from_sequence([item for item in x]),
     ]
     for y in ys:
         self.assertQuantityAlmostEqual(x, y.quantity)
 def test_pintarray_creation(self):
     x = ureg.Quantity([1.0, 2.0, 3.0], "m")
     ys = [
         PintArray.from_1darray_quantity(x),
         PintArray._from_sequence([item for item in x]),
     ]
     for y in ys:
         helpers.assert_quantity_almost_equal(x, y.quantity)
Exemplo n.º 5
0
 def test_mismatched_dimensions(self):
     x_and_ys = [
         (PintArray.from_1darray_quantity(ureg.Quantity([5], "m")), [1, 1]),
         (PintArray.from_1darray_quantity(ureg.Quantity([5, 5, 5],
                                                        "m")), [1, 1]),
         (PintArray.from_1darray_quantity(self.Q_([5, 5], "m")), [1]),
     ]
     for x, y in x_and_ys:
         for op in comparative_ops + arithmetic_ops:
             self.assertRaises(ValueError, op, x, y)
    def test_offset_concat(self):
        q_a = ureg.Quantity(np.arange(5), ureg.Unit("degC"))
        q_b = ureg.Quantity(np.arange(6), ureg.Unit("degC"))

        a = pd.Series(PintArray(q_a))
        b = pd.Series(PintArray(q_b))

        result = pd.concat([a, b], axis=1)
        expected = pd.Series(PintArray(np.concatenate([q_b, q_b]), dtype="pint[degC]"))
        self.assert_equal(result, expected)
 def test_mismatched_dimensions(self):
     x_and_ys = [
         (PintArray.from_1darray_quantity(ureg.Quantity([5.0], "m")), [1, 1]),
         (
             PintArray.from_1darray_quantity(ureg.Quantity([5.0, 5.0, 5.0], "m")),
             [1, 1],
         ),
         (PintArray.from_1darray_quantity(self.Q_([5.0, 5.0], "m")), [1]),
     ]
     for x, y in x_and_ys:
         for op in comparative_ops + arithmetic_ops:
             with pytest.raises(ValueError):
                 op(x, y)
Exemplo n.º 8
0
    def convert_unit(self, unit):
        """
        convert the unit of the series

        :param str/pint.Unit unit:
        :return:
        """
        if unit is None:
            if isinstance(self._series.dtype, PintType):
                self._series = pd.Series(self._series.pint.magnitude,
                                         index=self._series.index)
        else:
            unit = coerce_unit(unit)
            if not isinstance(self._series.dtype, PintType):
                self._series = pd.Series(
                    PintArray(self._series.values, dtype=unit),
                    index=self._series.index,
                )
            else:
                if ureg.is_compatible_with(self._unit, unit):
                    self._series = self._series.pint.to(unit)
                else:
                    raise ValueError(
                        f'{unit} unit is not compatible with {self._unit}')
        self._unit = unit
        return self
    def test_initialisation(self, data):
        # fails with plain array
        # works with PintArray
        df = pd.DataFrame(
            {
                "length": pd.Series([2.0, 3.0], dtype="pint[m]"),
                "width": PintArray([2.0, 3.0], dtype="pint[m]"),
                "distance": PintArray([2.0, 3.0], dtype="m"),
                "height": PintArray([2.0, 3.0], dtype=ureg.m),
                "depth": PintArray.from_1darray_quantity(
                    ureg.Quantity([2.0, 3.0], ureg.m)
                ),
            }
        )

        for col in df.columns:
            assert all(df[col] == df.length)
    def test_pintarray_operations(self):
        # Perform operations with Quantities and PintArrays
        # The resulting Quantity and PintArray.Data should be the same
        # a op b == c
        # warnings ignored here as it these tests are to ensure
        # pint array behaviour is the same as quantity
        def test_op(a_pint, a_pint_array, b_, coerce=True):
            try:
                result_pint = op(a_pint, b_)
                if coerce:
                    # a PintArray is returned from arithmetics, so need the data
                    c_pint_array = op(a_pint_array, b_).quantity
                else:
                    # a boolean array is returned from comparatives
                    c_pint_array = op(a_pint_array, b_)

                helpers.assert_quantity_almost_equal(result_pint, c_pint_array)

            except Exception as caught_exception:
                with pytest.raises(type(caught_exception)):
                    op(a_pint_array, b)

        a_pints = [
            ureg.Quantity([3.0, 4.0], "m"),
            ureg.Quantity([3.0, 4.0], ""),
        ]

        a_pint_arrays = [PintArray.from_1darray_quantity(q) for q in a_pints]

        bs = [
            2,
            ureg.Quantity(3, "m"),
            [1.0, 3.0],
            [3.3, 4.4],
            ureg.Quantity([6.0, 6.0], "m"),
            ureg.Quantity([7.0, np.nan]),
        ]

        for a_pint, a_pint_array in zip(a_pints, a_pint_arrays):
            for b in bs:
                for op in arithmetic_ops:
                    test_op(a_pint, a_pint_array, b)
                for op in comparative_ops:
                    test_op(a_pint, a_pint_array, b, coerce=False)
Exemplo n.º 11
0
    def prepend(self, value):
        """
        prepend a new value to a series with frequency

        :param float/int value: the value to prepend
        :return: the series with the new prepended value
        :rtype: TimestampSeries
        """
        if not self.freq:
            raise ValueError('cannot prepend to series without freq')
        if self.empty:
            raise ValueError('cannot prepend to empty series, '
                             'use __setitem__: ts[timestamp] = value instead')
        values = [value]
        if self.unit:
            values = PintArray(values, dtype=self.unit)
        self._series = (pd.Series(
            values,
            index=[self._series.index.shift(periods=1, freq=-self.freq)[0]
                   ]).append(self._series))
        return self
Exemplo n.º 12
0
def test_issue_71():
    a = PintArray([1, 2], ureg.m)
    s = pickle.dumps(a)
    b = pickle.loads(s)
    assert np.all(a == b)
Exemplo n.º 13
0
def _quantify_series(series, unit):
    if unit:
        return PintArray(series, unit)
    return series
Exemplo n.º 14
0
class TestSeriesAccessors(object):
    @pytest.mark.parametrize(
        "attr",
        [
            "debug_used",
            "default_format",
            "dimensionality",
            "dimensionless",
            "force_ndarray",
            "shape",
            "u",
            "unitless",
            "units",
        ],
    )
    def test_series_scalar_property_accessors(self, data, attr):
        s = pd.Series(data)
        assert getattr(s.pint, attr) == getattr(data.quantity, attr)

    @pytest.mark.parametrize(
        "attr",
        [
            "m",
            "magnitude",
            # 'imag', # failing, not sure why
            # 'real', # failing, not sure why
        ],
    )
    def test_series_property_accessors(self, data, attr):
        s = pd.Series(data)
        assert all(
            getattr(s.pint, attr) == pd.Series(getattr(data.quantity, attr)))

    @pytest.mark.parametrize(
        "attr_args",
        [
            ("check", ({
                "[length]": 1
            })),
            ("compatible_units", ()),
            # ('format_babel', ()), Needs babel installed?
            # ('plus_minus', ()), Needs uncertanties
            # ('to_tuple', ()),
            ("tolist", ()),
        ],
    )
    def test_series_scalar_method_accessors(self, data, attr_args):
        attr = attr_args[0]
        args = attr_args[1]
        s = pd.Series(data)
        assert getattr(s.pint, attr)(*args) == getattr(data.quantity,
                                                       attr)(*args)

    @pytest.mark.parametrize(
        "attr_args",
        [
            ("ito", ("mi", )),
            ("ito_base_units", ()),
            ("ito_reduced_units", ()),
            ("ito_root_units", ()),
            ("put", (1, 1 * ureg.nm)),
        ],
    )
    def test_series_inplace_method_accessors(self, data, attr_args):
        attr = attr_args[0]
        args = attr_args[1]
        from copy import deepcopy

        s = pd.Series(deepcopy(data))
        getattr(s.pint, attr)(*args)
        getattr(data.quantity, attr)(*args)
        assert all(s.values == data)

    @pytest.mark.parametrize(
        "attr_args",
        [
            ("clip", (10 * ureg.nm, 20 * ureg.nm)),
            (
                "from_tuple",
                (PintArray(np.arange(1, 101),
                           dtype=ureg.m).quantity.to_tuple(), ),
            ),
            ("m_as", ("mi", )),
            ("searchsorted", (10 * ureg.nm, )),
            ("to", ("m")),
            ("to_base_units", ()),
            ("to_compact", ()),
            ("to_reduced_units", ()),
            ("to_root_units", ()),
            # ('to_timedelta', ()),
        ],
    )
    def test_series_method_accessors(self, data, attr_args):
        attr = attr_args[0]
        args = attr_args[1]
        s = pd.Series(data)
        assert all(
            getattr(s.pint, attr)(*args) == getattr(data.quantity, attr)(
                *args))