Skip to content

Update tensor.where to allow for case with only condition #844

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

Merged
merged 8 commits into from
Jun 24, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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
11 changes: 10 additions & 1 deletion pytensor/tensor/basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -760,7 +760,16 @@
"""if cond then ift else iff"""


where = switch
def where(cond, ift=None, iff=None):
# Raise an error if only one of ift or iff is passed
if (ift is None and iff is not None) or (ift is not None and iff is None):
raise Exception("Either both or none of the parameters should be passed")

Check warning on line 766 in pytensor/tensor/basic.py

View check run for this annotation

Codecov / codecov/patch

pytensor/tensor/basic.py#L766

Added line #L766 was not covered by tests
# Normal switch incase both arguements are passed
elif ift is not None and iff is not None:
return switch(cond, ift, iff)
# Add case when only condition is passed
else:
return as_tensor(cond).nonzero()


@scalar_elemwise
Expand Down
9 changes: 9 additions & 0 deletions tests/tensor/test_basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@
triu_indices,
triu_indices_from,
vertical_stack,
where,
zeros_like,
)
from pytensor.tensor.blockwise import Blockwise
Expand Down Expand Up @@ -4608,3 +4609,11 @@ def core_np(x, y):
vectorize_pt(x_test, y_test),
vectorize_np(x_test, y_test),
)


def test_where_for_only_condition():
a = np.array([1, 2, 3, 4, 5])
cond = a <= 3
pt_result = where(cond)[0].eval()
np_result = np.where(cond)[0]
np.testing.assert_allclose(pt_result, np_result)
Loading