Skip to content

Add convert.mom5_to_sgrid and the BGrid_Velocity interpolator - #3097

Open
navidcy wants to merge 1 commit into
Parcels-code:mainfrom
navidcy:mom5-to-sgrid
Open

navidcy wants to merge 1 commit into
Parcels-code:mainfrom
navidcy:mom5-to-sgrid

Conversation

@navidcy

@navidcy navidcy commented Dec 2, 2026 •

Copy link
Copy Markdown

Description

Adds MOM5 (Arakawa B-grid) support, as suggested in COSIMA/cosima-recipes#744 (comment). The code comes from the COSIMA Parcels recipe.

  • convert.mom5_to_sgrid(fields=..., coords=None) attaches the SGRID metadata to MOM5 output: U and V on the corners (xu_ocean, yu_ocean), tracers and wt on the cell centres (xt_ocean, yt_ocean), padding:low. MOM5 saves wt only at the bottoms of the cells (sw_ocean), so the sea surface is added as the first vertical node (depth = [0, *sw_ocean], with W = 0 there). wt is positive upward, so it is flipped to match depth (positive down).
  • interpolators.BGrid_Velocity implements the B-grid scheme of Delandmeter and van Sebille (2019), like v3's bgrid_velocity/bgrid_w_velocity: U and V are bilinear in the horizontal at the vertical level of the cell, and W is linear in the vertical at the cell centre.
  • FieldSet.from_sgrid_conventions now uses BGrid_Velocity by default when U and V are on the horizontal nodes and either W is on the horizontal faces or U and V are on the vertical faces. Without this, 3D B-grid data would silently get XLinear_Velocity (see also Rename _is_agrid #2692). The A-grid and C-grid defaults are unchanged.

Notes:

  • The node coordinates are the 1D xu_ocean/yu_ocean. ACCESS-OM2's geolon_c/geolat_c are NaN over land-masked tiles, and U and V are along the grid lines (not rotated; FieldSet.from_mom does not consider grid rotation #1509), so this is exact only on the regular lat–lon part of a tripolar grid. The docstring says so.
  • No periodic halo is added; the docstring explains how.
  • There is no docs notebook, since it would need MOM5 example data in parcels-data. I'm happy to add one with a small ACCESS-OM2 subset if you'd like.

Testing: new tests on a small synthetic MOM5 grid, covering the metadata, the surface node, the sign of W, the interpolated values, 2D/3D advection and tracer sampling. The full test suite passes locally, and so do ruff and mypy. On ACCESS-OM2 0.1° output, mom5_to_sgrid with the default BGrid_Velocity gives bit-identical trajectories, depths and sampled temperature to the recipe's hand-written interpolator (100 particles, 4 days).

Checklist

  • Tests added
  • This PR targets the correct branch (main for normal development, v3-support for v3 support)

AI Disclosure

  • This PR contains AI-generated content.
    • I have tested any AI-generated content in my PR.
    • I take responsibility for any AI-generated content in my PR.
    • Describe how you used it (e.g., by pasting your prompt): Claude Code ported the B-grid interpolator and grid metadata from the COSIMA recipe into a converter, an interpolator and tests, prompted with "let's open a PR to put this in parcels".

[This is Claude Code on behalf of @navidcy]

- convert.mom5_to_sgrid attaches SGRID metadata to MOM5 (B-grid) output. The sea
  surface is added as the first vertical node, where W is zero, since MOM5 saves wt
  only at the bottoms of the cells.
- interpolators.BGrid_Velocity interpolates velocities on a B-grid following
  Delandmeter and van Sebille (2019), as v3's bgrid_velocity and bgrid_w_velocity.
- FieldSet.from_sgrid_conventions uses BGrid_Velocity by default for B-grid velocities.
@navidcy

navidcy commented Dec 2, 2026

Copy link
Copy Markdown
Author

There is no docs notebook, since it would need MOM5 example data in parcels-data. I'm happy to add one with a small ACCESS-OM2 subset if you'd like.

Or we can link to https://cosima-recipes.readthedocs.io/en/latest/03-Advanced-Recipes/Particle_tracking_with_Parcels.html ?

@erikvansebille erikvansebille left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very nice work, thanks for creating this PR! A few comments and questions below

Comment on lines +231 to +236
if _is_bgrid(self.data, self.grid.sgrid_metadata, components):
interp_method = BGrid_Velocity()
elif _is_agrid(self.data, u=components[0], v=components[1]):
interp_method = XLinear_Velocity()
else:
interp_method = CGrid_Velocity()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We may want to streamline/consolidate this logic in another PR, perhaps as part of #2692. For example, _is_agrid could use the same function parameters. But for now, this is fine

Comment on lines +590 to +606
def _is_bgrid(ds: xr.Dataset, metadata: sgrid.SGrid2DMetadata, components: Sequence[str]) -> bool:
"""Check if the velocities are on a B-grid (e.g., MOM5).

On a B-grid, U and V are both on the horizontal nodes (the corners of the cells), while W is on the horizontal
faces (the centres of the cells), and U and V are on the vertical faces (the vertical centres of the cells).
Without W and a vertical axis, the velocities can't be told apart from an A-grid, where the interpolation in the
horizontal is the same.
"""
u, v = components[0], components[1]
if set(ds[u].dims) != set(ds[v].dims):
return False
fnp_x, fnp_y = metadata.face_dimensions
if not {fnp_x.node, fnp_y.node} <= set(ds[u].dims):
return False
if len(components) == 3 and {fnp_x.face, fnp_y.face} <= set(ds[components[2]].dims):
return True
return metadata.vertical_dimensions is not None and metadata.vertical_dimensions[0].face in ds[u].dims

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't understand this function. How can it differentiate between an A-grid and a B-grid if it doesn't look at the W-component?

Can you expand this function so that it is clearer what the assumptions are?

Comment on lines +338 to +356
Interpolation kernel for velocity fields on a B-Grid (e.g., MOM5).
Following Delandmeter and Van Sebille (2019), the horizontal velocities U and V, which are on the corners of
the cells, are interpolated bilinearly in the horizontal, using their values at the vertical level of the cell
(so they don't change with depth within a cell). The vertical velocity W, which is on the tops and bottoms of the
cells, is interpolated linearly in the vertical (so it doesn't change in the horizontal within a cell).
"""

def interp(
self,
particle_positions: dict[str, float | np.ndarray],
grid_positions: dict[ptyping.XgridAxis, dict[str, int | float | np.ndarray]],
vectorfield: VectorField,
):
"""Interpolation kernel for velocity fields on a B-Grid.

Following Delandmeter and Van Sebille (2019), U and V are interpolated bilinearly in the horizontal and are
constant in the vertical within a cell, while W is interpolated linearly in the vertical and is constant in
the horizontal within a cell.
"""

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A bit overkill to put essentially the same information in the doctoring of the class and the interp function?

"Y": (yi, np.clip(yi + 1, 0, data.shape[2] - 1)),
"X": (xi, np.clip(xi + 1, 0, data.shape[3] - 1)),
},
)[0]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why the [0] here?

Comment on lines +389 to +392
(1 - xsi) * (1 - eta) * corner_data[0, 0]
+ xsi * (1 - eta) * corner_data[0, 1]
+ (1 - xsi) * eta * corner_data[1, 0]
+ xsi * eta * corner_data[1, 1]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would this also work for multiple particles? In Xlinear, we have an extra colon at the end.

value = (
(1 - xsi) * (1 - eta) * corner_data[0, 0, :]
+ xsi * (1 - eta) * corner_data[0, 1, :]
+ (1 - xsi) * eta * corner_data[1, 0, :]
+ xsi * eta * corner_data[1, 1, :]
)

Comment thread src/parcels/convert.py
Comment on lines +690 to +692
vertical_dimensions=(sgrid.FaceNodePadding("st_ocean", "depth", sgrid.Padding.NONE),)
if "depth" in ds.dims
else None,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is formatted a bit strange. Hard to read this way?

Comment thread tests/test_convert.py
assert "other data variables are ignored for this entry: ['V']" in caplog.text


def _mom5_synthetic(nx=6, ny=5, ntime=2):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you move this function to src/parcels/_datasets/structured/circulation_models.py?

Comment thread tests/test_convert.py
Comment on lines +646 to +678
@pytest.mark.parametrize(
"x, y, z",
[
(-98.2, -62.3, 7.0), # in the first vertical cell, between the surface and sw_ocean[0]
(-96.4, -61.1, 25.0),
(-99.9, -64.6, 59.0),
],
)
def test_bgrid_velocity_interpolation(x, y, z):
u, v, wt, _ = _mom5_synthetic()
ds = convert.mom5_to_sgrid(fields={"U": u, "V": v, "W": wt})
fieldset = FieldSet.from_sgrid_conventions(ds)

xu = u["xu_ocean"].values
i = np.searchsorted(xu, x) - 1 # corner to the west of the particle
xsi = (x - xu[i]) / (xu[i + 1] - xu[i])
nodes = np.array([0.0, 10.0, 30.0, 60.0])
k = np.searchsorted(nodes, z) - 1 # vertical cell of the particle
zeta = (z - nodes[k]) / (nodes[k + 1] - nodes[k])

# U and V: bilinear between the corners (here they only change along X), using the values of the cell's level
u_expected = 0.1 + 0.01 * (i + xsi) + 0.1 * k
v_expected = 0.05 - 0.01 * (i + xsi) + 0.1 * k
# W: linear between the top and the bottom of the cell, using the values of the tracer cell (i + 1) the particle
# is in. W is zero at the surface, and is -wt (positive downward) below
wt_nodes = np.concatenate([[0.0], 1e-4 * (np.arange(3) + 1) + 1e-5 * (i + 1)])
w_expected = -((1 - zeta) * wt_nodes[k] + zeta * wt_nodes[k + 1])

deg2m = 1852 * 60.0
uvw = fieldset.UVW[0.0, z, y, x]
np.testing.assert_allclose(uvw[0], u_expected / (deg2m * np.cos(np.radians(y))), rtol=1e-6)
np.testing.assert_allclose(uvw[1], v_expected / deg2m, rtol=1e-6)
np.testing.assert_allclose(uvw[2], w_expected, rtol=1e-6)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you move this to test_interpolation.py?

Comment thread tests/test_convert.py
Comment on lines +681 to +692
def test_mom5_advection_3d():
u, v, wt, temp = _mom5_synthetic()
ds = convert.mom5_to_sgrid(fields={"U": u, "V": v, "W": wt, "T": temp})
fieldset = FieldSet.from_sgrid_conventions(ds)
fieldset.T.interp_method = parcels.interpolators.CGrid_Tracer()

pset = parcels.ParticleSet(fieldset, x=[-98.0, -97.0], y=[-62.0, -61.0], z=[15.0, 40.0])
pset.execute(parcels.kernels.AdvectionRK2_3D, runtime=np.timedelta64(12, "h"), dt=np.timedelta64(1, "h"))

assert np.isfinite(pset.x).all() and np.isfinite(pset.y).all() and np.isfinite(pset.z).all()
assert (pset.x > [-98.0, -97.0]).all() # U is positive
assert (pset.z < [15.0, 40.0]).all() # wt is positive (upward), so the particles rise

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you move this to test_advection.py?

Comment thread tests/test_convert.py
Comment on lines +695 to +702
def test_mom5_tracer_is_constant_in_cell():
u, v, wt, temp = _mom5_synthetic()
ds = convert.mom5_to_sgrid(fields={"U": u, "V": v, "W": wt, "T": temp})
fieldset = FieldSet.from_sgrid_conventions(ds)
fieldset.T.interp_method = parcels.interpolators.CGrid_Tracer()

# temp is 10 - k in vertical cell k, which is between the vertical nodes [0, 10, 30, 60]
np.testing.assert_array_equal(fieldset.T[0.0, [5.0, 15.0, 40.0], [-62.0] * 3, [-98.0] * 3], [10.0, 9.0, 8.0])

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you move this to test_interpolation.py?

@github-project-automation github-project-automation Bot moved this from Backlog to Ready in Parcels development Dec 3, 2026
@erikvansebille

Copy link
Copy Markdown
Member

There is no docs notebook, since it would need MOM5 example data in parcels-data. I'm happy to add one with a small ACCESS-OM2 subset if you'd like.

Or we can link to https://cosima-recipes.readthedocs.io/en/latest/03-Advanced-Recipes/Particle_tracking_with_Parcels.html ?

I'd prefer to include it also in a notebook in our own docs - especially because we compile and run these on RTD, so will notice if something breaks. Could you add a small ACCESS-OM2 subset to https://github.com/Parcels-code/parcels-data/tree/main/data, and then a short tutorial to https://github.com/Parcels-code/Parcels/blob/main/docs/user_guide/convert_mom6.ipynb (which we should rename to convert_mom and give sections for MOM5 and MOM6 - I don't think we need two notebooks). Feel free to link to the COSIMA recipe for more details!

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Ready

Development

Successfully merging this pull request may close these issues.

2 participants