diff --git a/devito/data/data.py b/devito/data/data.py index 38bbc80b04..ba53e88b30 100644 --- a/devito/data/data.py +++ b/devito/data/data.py @@ -325,8 +325,11 @@ def __setitem__(self, glb_idx, val): # `val` is replicated, `self` is decomposed -> `val` gets decomposed glb_idx = self._normalize_index(glb_idx) glb_idx, val = self._process_args(glb_idx, val) - val_idx = [index_dist_to_repl(i, dec) for i, dec in - zip(glb_idx, self._decomposition, strict=True)] + val_idx = [owned_positions(i, dec) + if isinstance(i, slice) and dec is not None + else index_dist_to_repl(i, dec) + for i, dec in zip(glb_idx, self._decomposition, + strict=True)] if NONLOCAL in val_idx: # no-op return @@ -339,19 +342,11 @@ def __setitem__(self, glb_idx, val): # * one of them is 1 # Conceptually, below we apply the same rule val_idx = val_idx[len(val_idx)-len(val.shape):] - processed = [] - # Handle step size > 1 - for i, j in zip(glb_idx, val_idx, strict=False): - if isinstance(i, slice) and i.step is not None and i.step > 1 and \ - j.stop > j.start: - processed.append(slice(j.start, j.stop, 1)) - else: - processed.append(j) # An axis `val` broadcasts along carries the same value for every # rank, so it must be taken whole rather than cut down to this # rank's share of the destination val_idx = tuple(slice(None) if n == 1 else j - for j, n in zip(processed, val.shape, strict=True)) + for j, n in zip(val_idx, val.shape, strict=True)) elif is_windowed(val): # Read all of it, there is no decomposition to restrict it to val_idx = tuple(slice(0, s) for s in val.shape) @@ -384,6 +379,28 @@ def _normalize_index(self, idx): processed = [slice(i.start, i.stop, 1) if (isinstance(i, slice) and i.step is None) else i for i in items] + # Resolve slice bounds against the global axis size as NumPy does: + # with a negative step a `stop` of -1 means the last entry rather + # than "past the first one", and bounds beyond either end are clipped + naxes = min(self.ndim, len(self._modulo), len(self._decomposition)) + for axis, i in enumerate(processed[:naxes]): + if not isinstance(i, slice) or self._modulo[axis]: + continue + dec = self._decomposition[axis] + size = self.shape[axis] if dec is None else dec.size + if i.step > 0: + start, stop = (b if b is None or b >= 0 else max(b + size, 0) + for b in (i.start, i.stop)) + processed[axis] = slice(start, stop, i.step) + continue + start, stop, step = i.indices(size) + if not range(start, stop, step): + processed[axis] = slice(0, 0, 1) + continue + # Bounds left open stay open + start = None if i.start is None else start + stop = None if i.stop is None or stop < 0 else stop + processed[axis] = slice(start, stop, step) return as_tuple(processed) def _process_args(self, idx, val): @@ -399,17 +416,22 @@ def _process_args(self, idx, val): transform = [] for j, k in zip(idx, self._distributor.glb_shape, strict=True): if isinstance(j, slice) and j.step is not None and j.step < 0: - stop = None if j.start is None else j.start + 1 - if j.stop is None and j.start is None: - start = int(np.mod(k-1, -j.step)) - elif j.stop is None: - start = int(np.mod(j.start, -j.step)) + # The same entries in increasing order; `val` is flipped + # along this axis to match + selected = range(*j.indices(k)) + if selected: + processed.append(slice(selected[-1], selected[0] + 1, + -selected.step)) else: - start = j.stop + 1 - processed.append(slice(start, stop, -j.step)) - transform.append(slice(None, None, np.sign(j.step))) + processed.append(slice(0, 0, 1)) + transform.append(slice(None, None, -1)) else: processed.append(j) + if isinstance(j, slice): + transform.append(slice(None)) + # Axes indexed by an integer have no counterpart in `val`, and `val` + # may broadcast along leading axes + transform = transform[max(len(transform) - len(val.shape), 0):] if isinstance(val, Data) and len(transform) > 0 and \ len(val._distributor.shape) > len(val.shape): # Rebuild the distributor since the dimension of the slice diff --git a/devito/data/utils.py b/devito/data/utils.py index 45f6c376bc..0398f531b8 100644 --- a/devito/data/utils.py +++ b/devito/data/utils.py @@ -14,6 +14,7 @@ 'index_is_basic', 'is_windowed', 'loc_data_idx', + 'owned_positions', ] @@ -107,6 +108,32 @@ def index_dist_to_repl(idx, decomposition): raise ValueError(f"Cannot apply shift to type `{type(idx)}`") +def owned_positions(idx, decomposition): + """ + The positions, within the entries selected by the global slice `idx`, of + those owned by the calling rank. This is the part of a replicated value + that a rank writes when it is assigned through `idx`. + + Examples + -------- + The entries 1, 4, 7 and 10 are selected; the local subdomain [5, 7] owns + the third of them. + + >>> from devito.data import Decomposition + >>> d = Decomposition([[0, 1, 2], [3, 4], [5, 6, 7], [8, 9, 10, 11]], 2) + >>> owned_positions(slice(1, None, 3), d) + slice(2, 3, None) + """ + if decomposition.loc_empty: + return slice(0, 0) + start, stop, step = idx.indices(decomposition.size) + assert step > 0 + nselected = len(range(start, stop, step)) + first = max(0, -(-(decomposition.loc_abs_min - start) // step)) + last = min(nselected - 1, (decomposition.loc_abs_max - start) // step) + return slice(first, max(first, last + 1)) + + def convert_index(idx, decomposition, mode='glb_to_loc'): """Convert a global index into a local index or vise versa according to mode.""" if is_integer(idx) or isinstance(idx, slice): diff --git a/tests/test_data.py b/tests/test_data.py index 0438ea80ac..0f7df9e4ff 100644 --- a/tests/test_data.py +++ b/tests/test_data.py @@ -84,6 +84,32 @@ def test_negative_step(self): assert (np.array(u.data[0, 3::-1, 0, 0]) == dat[3::-1]).all() assert (np.array(u.data[0, 5:1:-1, 0, 0]) == dat[5:1:-1]).all() + @pytest.mark.parametrize('idx', [ + (3, slice(None, -1, -1)), + (3, slice(5, -1, -1)), + (slice(None), slice(7, None, -2)), + (slice(9, -4, -2), slice(None)), + (slice(1, 6, 3), slice(7, None, -3)), + (slice(-10, 5, 3), slice(2, 4)), + ]) + def test_slice_bounds_like_numpy(self, idx): + """ + Slices with a negative step or with bounds beyond either end select the + same entries as in NumPy, both when reading and when writing. + """ + grid = Grid(shape=(9, 7)) + f = Function(name='f', grid=grid) + full = np.arange(63, dtype=f.dtype).reshape(9, 7) + f.data[:] = full + assert np.array_equal(np.asarray(f.data[idx]), full[idx]) + + g = Function(name='g', grid=grid) + expected = np.zeros_like(full) + val = np.arange(expected[idx].size, dtype=f.dtype).reshape(expected[idx].shape) + expected[idx] = val + 1 + g.data[idx] = val + 1 + assert np.array_equal(np.asarray(g.data), expected) + def test_negative_start(self): """Test slicing with a negative start.""" grid = Grid(shape=(13,)) @@ -1217,6 +1243,39 @@ def test_slicing_ns(self, mode): else: assert np.all(u.data == [[5, 4], [1, 0]]) + @pytest.mark.parallel(mode=4) + def test_setitem_strided(self, mode): + """ + Assigning a replicated array through strided, negative-step or + negatively bounded slices writes the same entries as in NumPy. + """ + grid = Grid(shape=(9, 7)) + indices = [ + (1, slice(2, 7, 3)), + (slice(0, 9, 2), 1), + (slice(1, 9, 3), slice(None)), + (slice(None), slice(6, 0, -4)), + (slice(0, -3), slice(None, 1, -1)), + (slice(-8, -3, 2), slice(None, 6, 2)), + (slice(-5, 6, 2), slice(7, -3, -1)), + ] + for n, idx in enumerate(indices): + f = Function(name=f'f{n}', grid=grid) + expected = np.zeros(grid.shape, dtype=f.dtype) + val = np.arange(expected[idx].size, + dtype=f.dtype).reshape(expected[idx].shape) + 1 + expected[idx] = val + try: + f.data[idx] = val + failed = False + except ValueError: + failed = True + # Agree on the outcome so a failure on one rank can't hang the others + assert not grid.distributor.comm.allreduce(failed), idx + gathered = f.data_gather(rank=0) + if grid.distributor.myrank == 0: + assert np.array_equal(gathered, expected), idx + @pytest.mark.parallel(mode=4) def test_getitem(self, mode): # __getitem__ MPI slicing: indexing is local, never communicates --