Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add scalar support to where #679

Merged
merged 1 commit into from
Jan 21, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions cubed/array_api/searching_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,5 +88,13 @@ def _searchsorted(x, y, side):


def where(condition, x1, x2, /):
x1_is_scalar = isinstance(x1, (int, float, complex, bool))
x2_is_scalar = isinstance(x2, (int, float, complex, bool))
if x1_is_scalar and x2_is_scalar:
raise TypeError("At least one of x1 and x2 must be an array in where")
elif x1_is_scalar:
x1 = x2._promote_scalar(x1)
elif x2_is_scalar:
x2 = x1._promote_scalar(x2)
dtype = result_type(x1, x2)
return elemwise(nxp.where, condition, x1, x2, dtype=dtype)
16 changes: 16 additions & 0 deletions cubed/tests/test_array_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -794,6 +794,22 @@ def test_searchsorted_sorter_not_implemented():
xp.searchsorted(xp.asarray([1, 0]), xp.asarray([1]), sorter=xp.asarray([1, 0]))


def test_where_scalars():
condition = xp.asarray(
[[True, False, True], [False, True, False], [True, False, True]], chunks=(2, 2)
)
a = xp.asarray([[1, 2, 3], [4, 5, 6], [7, 8, 9]], chunks=(2, 2))

b = xp.where(condition, a, 0)
assert_array_equal(b.compute(), np.array([[1, 0, 3], [0, 5, 0], [7, 0, 9]]))

c = xp.where(condition, 0, a)
assert_array_equal(c.compute(), np.array([[0, 2, 0], [4, 0, 6], [0, 8, 0]]))

with pytest.raises(TypeError):
xp.where(condition, 0, 1)


# Statistical functions


Expand Down
Loading