From 6cdcdccc763da8ee4bfd811fc2196360249f263a Mon Sep 17 00:00:00 2001 From: AryanRG Date: Mon, 16 Nov 2026 18:57:04 +0530 Subject: [PATCH 1/2] fix: normalize vectorized histogram bin indices --- src/boost_histogram/histogram.py | 14 +++++++++++++- tests/test_histogram_indexing.py | 10 ++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/src/boost_histogram/histogram.py b/src/boost_histogram/histogram.py index 2d27630e..ca3e4a89 100644 --- a/src/boost_histogram/histogram.py +++ b/src/boost_histogram/histogram.py @@ -1330,7 +1330,19 @@ def _compute_vectorized_index(self, indexes: list[Any]) -> tuple[Any, ...]: for i, ind in enumerate(indexes): offset = 1 if self.axes[i].traits.underflow else 0 if isinstance(ind, np.ndarray): - view_index.append(ind + offset) + # Resolve negative and out-of-range values like scalar + # indexing on the flow=False view before shifting onto the + # flow=True view, so they cannot silently select flow bins. + if not np.issubdtype(ind.dtype, np.integer): + msg = ( + f"Vectorized indexing on axis {i} requires an integer " + f"array, not {ind.dtype}" + ) + raise IndexError(msg) + size = self._hist.axis(i).size + if ind.size and (ind.min() < -size or ind.max() >= size): + raise IndexError("histogram index is out of range") + view_index.append(ind.astype(np.intp, copy=False) % size + offset) elif isinstance(ind, slice): if ind.step is not None or not all( s is None or isinstance(s, int) for s in (ind.start, ind.stop) diff --git a/tests/test_histogram_indexing.py b/tests/test_histogram_indexing.py index 992e2d05..d6ec7922 100644 --- a/tests/test_histogram_indexing.py +++ b/tests/test_histogram_indexing.py @@ -755,6 +755,16 @@ def test_vectorized_get_flow_offset(): idx = np.array([0, 4]) assert h[idx] == approx(np.array([h[0], h[4]])) + # Negative array indices count from the end, like scalar indices, + # instead of landing in the underflow bin + assert h[np.array([-1, -5])] == approx(np.array([h[-1], h[-5]])) + h[np.array([-1])] = 99 + assert h[4] == 99 + assert h.view(flow=True)[0] == 0 + + with pytest.raises(IndexError, match="out of range"): + h[np.array([5])] + def test_vectorized_get_accumulator_storage(): h = bh.Histogram(bh.axis.Regular(5, 0, 5), storage=bh.storage.Weight()) From 1bc63a3b408af0d6dd3bdc6e5ce572cb354a943f Mon Sep 17 00:00:00 2001 From: Henry Schreiner Date: Tue, 17 Nov 2026 09:35:43 -0500 Subject: [PATCH 2/2] refactor: normalize index arrays with scalars in _compute_uhi_index Name the axis in the out-of-range error, wrap negatives in place on one copy, and test non-integer arrays, setitem, and multi-axis cases. Assisted-by: ClaudeCode:claude-opus-5-5 --- src/boost_histogram/histogram.py | 36 ++++++++++++++++--------------- tests/test_histogram_indexing.py | 37 ++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 17 deletions(-) diff --git a/src/boost_histogram/histogram.py b/src/boost_histogram/histogram.py index ca3e4a89..49352072 100644 --- a/src/boost_histogram/histogram.py +++ b/src/boost_histogram/histogram.py @@ -1226,17 +1226,29 @@ def _compute_uhi_index(self, index: InnerIndexing, axis: int) -> SimpleIndexing: if callable(index): return index(self.axes[axis]) - # NumPy integer arrays pass through untouched; they trigger vectorized - # gather/scatter in __getitem__/__setitem__ rather than per-element access. + # Arrays get the same range check and wrap as scalars; they trigger + # vectorized gather/scatter in __getitem__/__setitem__. if isinstance(index, np.ndarray): - return index + if not np.issubdtype(index.dtype, np.integer): + msg = ( + f"Vectorized indexing on axis {axis} requires an integer " + f"array, not {index.dtype}" + ) + raise IndexError(msg) + size: int = self._hist.axis(axis).size + if index.size and (index.min() < -size or index.max() >= size): + msg = f"histogram index is out of range on axis {axis}" + raise IndexError(msg) + arr = index.astype(np.intp) + np.add(arr, size, out=arr, where=arr < 0) + return arr if isinstance(index, float): raise TypeError(f"Index {index} must be an integer, not float") if isinstance(index, SupportsIndex): idx = int(index) - size: int = self._hist.axis(axis).size + size = self._hist.axis(axis).size if not -size <= idx < size: raise IndexError("histogram index is out of range") return idx % size @@ -1330,19 +1342,9 @@ def _compute_vectorized_index(self, indexes: list[Any]) -> tuple[Any, ...]: for i, ind in enumerate(indexes): offset = 1 if self.axes[i].traits.underflow else 0 if isinstance(ind, np.ndarray): - # Resolve negative and out-of-range values like scalar - # indexing on the flow=False view before shifting onto the - # flow=True view, so they cannot silently select flow bins. - if not np.issubdtype(ind.dtype, np.integer): - msg = ( - f"Vectorized indexing on axis {i} requires an integer " - f"array, not {ind.dtype}" - ) - raise IndexError(msg) - size = self._hist.axis(i).size - if ind.size and (ind.min() < -size or ind.max() >= size): - raise IndexError("histogram index is out of range") - view_index.append(ind.astype(np.intp, copy=False) % size + offset) + # Already wrapped to 0..size-1 by _compute_uhi_index (a copy) + np.add(ind, offset, out=ind) + view_index.append(ind) elif isinstance(ind, slice): if ind.step is not None or not all( s is None or isinstance(s, int) for s in (ind.start, ind.stop) diff --git a/tests/test_histogram_indexing.py b/tests/test_histogram_indexing.py index d6ec7922..b8679a5a 100644 --- a/tests/test_histogram_indexing.py +++ b/tests/test_histogram_indexing.py @@ -766,6 +766,43 @@ def test_vectorized_get_flow_offset(): h[np.array([5])] +@pytest.mark.parametrize("bad", [np.array([5]), np.array([-6]), np.array([0, 5])]) +def test_vectorized_out_of_range(bad): + h = bh.Histogram(bh.axis.Regular(4, 0, 4), bh.axis.Regular(5, 0, 5)) + view = h.view(flow=True).copy() + + with pytest.raises(IndexError, match="axis 1"): + h[np.array([0]), bad] + with pytest.raises(IndexError, match="axis 1"): + h[np.array([0]), bad] = 1 + with pytest.raises(IndexError, match="axis 1"): + h[0, bad] = 1 + assert h.view(flow=True) == approx(view) + + +def test_vectorized_negative_set_second_axis(): + h = bh.Histogram(bh.axis.Regular(4, 0, 4), bh.axis.Regular(5, 0, 5)) + h[np.array([1]), np.array([-1])] = 3 + assert h[1, 4] == 3 + assert h.view(flow=True)[:, 0].sum() == 0 + + +@pytest.mark.parametrize( + "bad", + [ + np.array([True, False, True, False, True]), + np.array([0.0, 1.0]), + np.array([0, 1], dtype=object), + ], +) +def test_vectorized_rejects_non_integer_arrays(bad): + h = bh.Histogram(bh.axis.Regular(5, 0, 5)) + with pytest.raises(IndexError, match="integer array"): + h[bad] + with pytest.raises(IndexError, match="integer array"): + h[bad] = 1 + + def test_vectorized_get_accumulator_storage(): h = bh.Histogram(bh.axis.Regular(5, 0, 5), storage=bh.storage.Weight()) h.fill([0, 0, 1, 2, 3], weight=[1, 2, 3, 4, 5])