Skip to content

fix: compare complex real and imaginary components separately in _array_all_equal - #4688

Open
ApacheWang wants to merge 2 commits into
zarr-developers:mainfrom
ApacheWang:fix/all-equal-complex-nan-components
Open

ApacheWang wants to merge 2 commits into
zarr-developers:mainfrom
ApacheWang:fix/all-equal-complex-nan-components

Conversation

@ApacheWang

Copy link
Copy Markdown

Summary

Fix _array_all_equal() in src/zarr/core/buffer/core.py so complex arrays compared with equal_nan=True compare their real and imaginary components separately instead of treating any complex value containing a NaN component as equal.

Root Cause

  • When checking whether an encoded chunk is entirely equal to the array's fill_value (NDBuffer.all_equal(..., equal_nan=True)), _array_all_equal delegates directly to np.array_equal(_data, other, equal_nan=True) (src/zarr/core/buffer/core.py:575).
  • In NumPy, np.array_equal with equal_nan=True treats any complex number where either the real or imaginary component is NaN as equal to any other complex number with a NaN component (so complex(nan, 7) and complex(0, nan) compare equal to complex(nan, 0)).
  • Consequently, writing non-fill complex values such as nan + 7j or 0 + nanj into a chunk whose fill_value is nan + 0j causes all_equal to return True, silently dropping the chunk as fill-only.

Changes

  • When equal_nan is True and _data.dtype.kind == "c", check both np.array_equal(_data.real, other.real, equal_nan=True) and np.array_equal(_data.imag, other.imag, equal_nan=True).
  • Add regression test test_all_equal_compares_complex_nan_components in tests/test_buffer.py covering (nan+0j, nan+7j), (0+nanj, 7+nanj), and (nan+0j, 0+nanj).

Verification

  • Baseline RED (7612281): test_all_equal_compares_complex_nan_components fails on all 3 cases (3 failed) because all_equal wrongly returns True for differing finite/NaN components.
  • With fix GREEN: All 1,806 test_all_equal cases in tests/test_buffer.py pass (1806 passed).
  • ruff check, ruff format --check, and git diff --check pass cleanly on both modified files.

Signed-off-by: bc15575202581 <bc15575202581@gmail.com>
Signed-off-by: bc15575202581 <bc15575202581@gmail.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant