diff --git a/src/boost_histogram/histogram.py b/src/boost_histogram/histogram.py index 2d27630e..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,7 +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): - view_index.append(ind + 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 992e2d05..b8679a5a 100644 --- a/tests/test_histogram_indexing.py +++ b/tests/test_histogram_indexing.py @@ -755,6 +755,53 @@ 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])] + + +@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())