Skip to content

Commit

Permalink
Merge pull request #1539 from keewis/where-quantity-condition
Browse files Browse the repository at this point in the history
avoid the `RecursionError` raised by `np.where`
  • Loading branch information
jules-ch committed Oct 4, 2022
2 parents 208d36a + e259c64 commit 9db2b29
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 0 deletions.
2 changes: 2 additions & 0 deletions CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ Pint Changelog
(Issue #1030, #574)
- Added angular frequency documentation page.
- Move ASV benchmarks to dedicated folder. (Issue #1542)
- Fix a recursion error that would be raised when passing quantities to `cond` and `x`.
(Issue #1510, #1530)

0.19.2 (2022-04-23)
-------------------
Expand Down
6 changes: 6 additions & 0 deletions pint/facets/numpy/numpy_func.py
Original file line number Diff line number Diff line change
Expand Up @@ -552,6 +552,12 @@ def _interp(x, xp, fp, left=None, right=None, period=None):

@implements("where", "function")
def _where(condition, *args):
if not getattr(condition, "_is_multiplicative", True):
raise ValueError(
"Invalid units of the condition: Boolean value of Quantity with offset unit is ambiguous."
)

condition = getattr(condition, "magnitude", condition)
args, output_wrap = unwrap_and_wrap_consistent_units(*args)
return output_wrap(np.where(condition, *args))

Expand Down
12 changes: 12 additions & 0 deletions pint/testsuite/test_numpy.py
Original file line number Diff line number Diff line change
Expand Up @@ -1103,6 +1103,18 @@ def test_where(self):
0 * self.ureg.J,
)

helpers.assert_quantity_equal(
np.where([-1, 0, 1] * self.ureg.m, [1, 2, 1] * self.ureg.s, np.nan),
[1, np.nan, 1] * self.ureg.s,
)
with pytest.raises(
ValueError,
match=".*Boolean value of Quantity with offset unit is ambiguous",
):
np.where(
self.ureg.Quantity([-1, 0, 1], "degC"), [1, 2, 1] * self.ureg.s, np.nan
)

@helpers.requires_array_function_protocol()
def test_fabs(self):
helpers.assert_quantity_equal(
Expand Down

0 comments on commit 9db2b29

Please sign in to comment.