From 1cc47da386d69a56938c4d62629f74afd2d20966 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Mon, 20 Apr 2026 10:25:13 -0700 Subject: [PATCH] [ind2pos] fix rounding and bounds --- gridlock/position.py | 4 ++-- gridlock/test/test_grid.py | 21 +++++++++++++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/gridlock/position.py b/gridlock/position.py index b705b99..6344ea4 100644 --- a/gridlock/position.py +++ b/gridlock/position.py @@ -47,13 +47,13 @@ class GridPosMixin(GridBase): else: low_bound = -0.5 high_bound = -0.5 - if (ind < low_bound).any() or (ind > self.shape - high_bound).any(): + if (ind < low_bound).any() or (ind > self.shape + high_bound).any(): raise GridError(f'Position outside of grid: {ind}') if round_ind: rind = numpy.clip(numpy.round(ind).astype(int), 0, self.shape - 1) sxyz = self.shifted_xyz(which_shifts) - position = [sxyz[a][rind[a]].astype(int) for a in range(3)] + position = [sxyz[a][rind[a]] for a in range(3)] else: sexyz = self.shifted_exyz(which_shifts) position = [numpy.interp(ind[a], numpy.arange(sexyz[a].size) - 0.5, sexyz[a]) diff --git a/gridlock/test/test_grid.py b/gridlock/test/test_grid.py index 6cb9edc..a9e3d9e 100644 --- a/gridlock/test/test_grid.py +++ b/gridlock/test/test_grid.py @@ -118,6 +118,27 @@ def test_draw_2shift_4x4() -> None: assert_allclose(arr, correct) +def test_ind2pos_round_preserves_float_centers() -> None: + grid = Grid([[0, 1, 3], [0, 2], [0, 1]], shifts=[[0, 0, 0]]) + + pos = grid.ind2pos(numpy.array([1, 0, 0]), which_shifts=0) + + assert_allclose(pos, [2.0, 1.0, 0.5]) + + +def test_ind2pos_enforces_bounds_for_rounded_and_fractional_indices() -> None: + grid = Grid([[0, 1, 3], [0, 2], [0, 1]], shifts=[[0, 0, 0]]) + + with pytest.raises(GridError): + grid.ind2pos(numpy.array([2, 0, 0]), which_shifts=0, check_bounds=True) + + edge_pos = grid.ind2pos(numpy.array([1.5, 0.5, 0.5]), which_shifts=0, round_ind=False, check_bounds=True) + assert_allclose(edge_pos, [3.0, 2.0, 1.0]) + + with pytest.raises(GridError): + grid.ind2pos(numpy.array([1.6, 0.5, 0.5]), which_shifts=0, round_ind=False, check_bounds=True) + + def test_draw_polygon_accepts_coplanar_nx3_vertices() -> None: grid = Grid([[0, 1, 2], [0, 1, 2], [0, 1]], shifts=[[0, 0, 0]]) arr_2d = grid.allocate(0)