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 1 commit
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
21 changes: 18 additions & 3 deletions pytensor/tensor/basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -761,15 +761,30 @@


def where(cond, ift=None, iff=None):
# Normal switch incase both arguements are passed
"""
where(condition, [ift, iff])
Return elements chosen from `ift` or `iff` depending on `condition`.

Note: When only condition is provided, this function is a shorthand for `as_tensor(condition).nonzero()`.

Parameters
----------
condition : tensor_like, bool
Where True, yield `ift`, otherwise yield `iff`.
x, y : tensor_like
Values from which to choose.

Returns
-------
out : TensorVariable
A tensor with elements from `ift` where `condition` is True, and elements from `iff` elsewhere.
"""
if ift is not None and iff is not None:
return switch(cond, ift, iff)
# Add case when only condition is passed
elif ift is None and iff is None:
return as_tensor(cond).nonzero()
# Raise an error if only one arguement is passed
else:
raise Exception("Either both or none of the parameters should be passed")

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

View check run for this annotation

Codecov / codecov/patch

pytensor/tensor/basic.py#L787

Added line #L787 was not covered by tests


@scalar_elemwise
Expand Down
15 changes: 4 additions & 11 deletions tests/tensor/test_basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -4613,19 +4613,12 @@ def core_np(x, y):

@pytest.mark.parametrize(
"ift, iff",
[(None, None), (7, 10), (7, None)],
[(None, None), (7, 10), pytest.param(7, None, marks=[pytest.mark.xfail])],
ids=["both none", "both valid", "one none"],
)
def test_where_for_only_condition(ift, iff):
a = np.array([1, 2, 3, 4, 5])
cond = a < 3
if ift is not None and iff is not None:
pt_result = function([], where(cond, ift, iff))()
np_result = np.where(cond, ift, iff)
np.testing.assert_allclose(pt_result, np_result)
elif ift is None and iff is None:
pt_result = function([], where(cond))()
np_result = np.where(cond)
np.testing.assert_allclose(pt_result, np_result)
else:
pytest.raises(Exception, where, cond, ift)
np_result = np.where(*[x for x in [cond, ift, iff] if x is not None])
pt_result = function([], where(cond, ift, iff))()
np.testing.assert_allclose(np_result, pt_result)
Loading