diff --git a/changes/4688.bugfix.md b/changes/4688.bugfix.md new file mode 100644 index 0000000000..bb0b0faddb --- /dev/null +++ b/changes/4688.bugfix.md @@ -0,0 +1 @@ +Compare real and imaginary components separately in _array_all_equal when equal_nan=True so complex chunks with one finite component and one NaN component are no longer treated as equal to (NaN+NaNj) fill values and dropped. diff --git a/src/zarr/core/buffer/core.py b/src/zarr/core/buffer/core.py index d2cd4a795b..850ecec5aa 100644 --- a/src/zarr/core/buffer/core.py +++ b/src/zarr/core/buffer/core.py @@ -572,6 +572,12 @@ def _array_all_equal(data: NDArrayLike, other: Any, equal_nan: bool) -> bool: return bool(np.array_equal(_data.view(bitwise_dtype), other.view(bitwise_dtype))) # use array_equal to obtain equal_nan=True functionality _data, other = np.broadcast_arrays(data, other) + if equal_nan and _data.dtype.kind == "c": + # NumPy treats a NaN in either component as a NaN for the whole value. + return bool( + np.array_equal(_data.real, other.real, equal_nan=True) + and np.array_equal(_data.imag, other.imag, equal_nan=True) + ) return bool( np.array_equal( _data, diff --git a/tests/test_buffer.py b/tests/test_buffer.py index 307abfe499..71c94a4d8e 100644 --- a/tests/test_buffer.py +++ b/tests/test_buffer.py @@ -307,6 +307,22 @@ def test_all_equal_distinguishes_negative_zero(dtype: str) -> None: assert not cpu.NDBuffer.from_numpy_array(positive).all_equal(-0.0) +@pytest.mark.parametrize( + ("fill", "value"), + [ + (complex(np.nan, 0), complex(np.nan, 7)), + (complex(0, np.nan), complex(7, np.nan)), + (complex(np.nan, 0), complex(0, np.nan)), + ], +) +def test_all_equal_compares_complex_nan_components(fill: complex, value: complex) -> None: + data = np.full((2, 3), fill, dtype=np.complex64) + assert cpu.NDBuffer.from_numpy_array(data).all_equal(fill) + + data[1, 2] = value + assert not cpu.NDBuffer.from_numpy_array(data).all_equal(fill) + + @pytest.mark.parametrize("kind", ["M8", "m8"]) @pytest.mark.parametrize("byteorder", ["<", ">"]) @pytest.mark.parametrize("scale_factor", [2, 2**31 - 1])