diff --git a/src/parcels/_core/field.py b/src/parcels/_core/field.py index d3ca0a209..f0995cfed 100644 --- a/src/parcels/_core/field.py +++ b/src/parcels/_core/field.py @@ -319,14 +319,16 @@ def __getitem__(self, key): def _update_particles_ei(particles, grid_positions: dict, field: Field): """Update the element index (ei) of the particles""" if particles is not None: + + def _maybe_clip(axis): + # Helper function to clip the axis indices to be within the valid range of the grid dimensions (#3062) + if axis not in field.grid.axes: + return grid_positions[axis]["index"] + dim = field.grid.get_axis_dim(axis) + return (np.clip(grid_positions[axis]["index"], 0, dim - 1),) + if isinstance(field.grid, XGrid): - particles.ei[:, field.igrid] = field.grid.ravel_index( - { - "X": grid_positions["X"]["index"], - "Y": grid_positions["Y"]["index"], - "Z": grid_positions["Z"]["index"], - } - ) + particles.ei[:, field.igrid] = field.grid.ravel_index({axis: _maybe_clip(axis) for axis in ["X", "Y", "Z"]}) elif isinstance(field.grid, UxGrid): particles.ei[:, field.igrid] = field.grid.ravel_index( { diff --git a/tests/test_convert.py b/tests/test_convert.py index ac7f9ceae..523196ad4 100644 --- a/tests/test_convert.py +++ b/tests/test_convert.py @@ -372,3 +372,22 @@ def test_mom6_to_sgrid_withdepth(): V = V.expand_dims(depth=[0], axis=1) with pytest.raises(ValueError, match="has more than 2 spatial dimensions"): convert.mom6_to_sgrid(fields={"U": U, "V": V}, coords=coords) + + +def test_mom6_to_sgrid_clip_ei(): + U = parcels.tutorial.open_dataset("MOM6_example_data/U")["ssu"] + V = parcels.tutorial.open_dataset("MOM6_example_data/V")["ssv"] + coords = parcels.tutorial.open_dataset("MOM6_example_data/static") + ds = convert.mom6_to_sgrid(fields={"U": U, "V": V}, coords=coords) + fieldset = FieldSet.from_sgrid_conventions(ds) + + X = coords.geolon.isel(xh=-1) + Y = coords.geolat.isel(xh=-1) + + pset = parcels.ParticleSet(fieldset=fieldset, x=X, y=Y) + + pset.execute( + [parcels.kernels.AdvectionRK2], + runtime=np.timedelta64(12, "h"), + dt=np.timedelta64(1, "h"), + )