Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 9 additions & 7 deletions src/parcels/_core/field.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
{
Expand Down
19 changes: 19 additions & 0 deletions tests/test_convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
)
Loading