Skip to content

Commit

Permalink
Fix Batch.__eq__ to work also for scalar values
Browse files Browse the repository at this point in the history
  • Loading branch information
dantp-ai committed Aug 2, 2024
1 parent 6154292 commit f81e225
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
22 changes: 22 additions & 0 deletions test/base/test_batch.py
Original file line number Diff line number Diff line change
Expand Up @@ -544,6 +544,28 @@ def test_nested_shapes_different() -> None:
batch2 = Batch(a=Batch(a=[1, 4]), b=[4, 5])
assert batch1 != batch2

@staticmethod
def test_array_scalars() -> None:
batch1 = Batch(a={"b": 1})
batch2 = Batch(a={"b": 1})
assert batch1 == batch2

batch3 = Batch(a={"c": 2})
assert batch1 != batch3

batch4 = Batch(b={"b": 1})
assert batch1 != batch4

batch5 = Batch(a={"b": 10})
assert batch1 != batch5

batch6 = Batch(a={"b": [1]})
assert batch1 == batch6

batch7 = Batch(a=1, b=5)
batch8 = Batch(a=1, b=5)
assert batch7 == batch8

@staticmethod
def test_slice_equal() -> None:
batch1 = Batch(a=[1, 2, 3])
Expand Down
10 changes: 10 additions & 0 deletions tianshou/data/batch.py
Original file line number Diff line number Diff line change
Expand Up @@ -678,6 +678,16 @@ def __eq__(self, other: Any) -> bool:

this_batch_no_torch_tensor: Batch = Batch.to_numpy(self)
other_batch_no_torch_tensor: Batch = Batch.to_numpy(other)
# DeepDiff 7.0.1 cannot compare 0-dimensional arrays
# so, we ensure with this transform that all array values have at least 1 dim
this_batch_no_torch_tensor.apply_values_transform(
values_transform=np.atleast_1d,
inplace=True,
)
other_batch_no_torch_tensor.apply_values_transform(
values_transform=np.atleast_1d,
inplace=True,
)
this_dict = this_batch_no_torch_tensor.to_dict(recursive=True)
other_dict = other_batch_no_torch_tensor.to_dict(recursive=True)

Expand Down

0 comments on commit f81e225

Please sign in to comment.