Skip to content

Commit

Permalink
chore: bufix, add test to combine_mask_fns
Browse files Browse the repository at this point in the history
  • Loading branch information
supersergiy committed May 3, 2024
1 parent 286ec14 commit f25a5c5
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 6 deletions.
19 changes: 19 additions & 0 deletions tests/unit/tensor_ops/test_mask.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,3 +248,22 @@ def test_normalize_kernel(kernel, width, expected_kernel):
def test_normalize_kernel_exc(kernel, width, expected_exc):
with pytest.raises(expected_exc):
mask._normalize_kernel(kernel, width, device=None) # pylint: disable=protected-access


def test_combine_mask_fns():
data = torch.Tensor([0, 1, 2, 3])
expected = torch.Tensor([1, 1, 1, 0]).bool()

result = mask.combine_mask_fns(
data,
fns=[
lambda x: x % 2 == 0,
lambda x: x == 1,
],
)
assert_array_equal(result, expected)


def test_combine_mask_fns_exc():
with pytest.raises(ValueError):
mask.combine_mask_fns(data=torch.zeros((10, 10)), fns=[])
13 changes: 7 additions & 6 deletions zetta_utils/tensor_ops/mask.py
Original file line number Diff line number Diff line change
Expand Up @@ -304,15 +304,16 @@ def mask_out_with_fn(
return result


@builder.register("combine_mask_fns") # type: ignore
@builder.register("combine_mask_fns")
@supports_dict
@skip_on_empty_data
@typechecked
def combine_mask_fns(
data: TensorTypeVar, fns: Sequence[Callable[[TensorTypeVar], TensorTypeVar]]
) -> TensorTypeVar: # pragma: no cover # no logic
assert len(fns) > 0
masks_t = [convert.to_torch(fn(data)) for fn in fns]
result_t = reduce(torch.Tensor.add_, masks_t, torch.zeros_like(masks_t[0]))
) -> TensorTypeVar:
if len(fns) == 0:
raise ValueError("Length of `fns` passed to `combine_mask_fns` cannot be 0. ")

masks_t = [convert.to_torch(fn(data) != 0).bool() for fn in fns]
result_t = reduce(torch.Tensor.logical_or_, masks_t, torch.zeros_like(masks_t[0]).bool())
result = convert.astype(result_t, data)
return result

0 comments on commit f25a5c5

Please sign in to comment.