Repository navigation
Conversation
- 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.
Or we can link to https://cosima-recipes.readthedocs.io/en/latest/03-Advanced-Recipes/Particle_tracking_with_Parcels.html ? |
erikvansebille
left a comment
There was a problem hiding this comment.
Very nice work, thanks for creating this PR! A few comments and questions below
| 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() |
There was a problem hiding this comment.
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
| 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 |
There was a problem hiding this comment.
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?
| 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. | ||
| """ |
There was a problem hiding this comment.
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] |
| (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] |
There was a problem hiding this comment.
Would this also work for multiple particles? In Xlinear, we have an extra colon at the end.
Parcels/src/parcels/interpolators/_xinterpolators.py
Lines 148 to 153 in a57e633
| vertical_dimensions=(sgrid.FaceNodePadding("st_ocean", "depth", sgrid.Padding.NONE),) | ||
| if "depth" in ds.dims | ||
| else None, |
There was a problem hiding this comment.
This is formatted a bit strange. Hard to read this way?
| assert "other data variables are ignored for this entry: ['V']" in caplog.text | ||
|
|
||
|
|
||
| def _mom5_synthetic(nx=6, ny=5, ntime=2): |
There was a problem hiding this comment.
Can you move this function to src/parcels/_datasets/structured/circulation_models.py?
| @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) |
There was a problem hiding this comment.
Can you move this to test_interpolation.py?
| 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 |
There was a problem hiding this comment.
Can you move this to test_advection.py?
| 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]) |
There was a problem hiding this comment.
Can you move this to test_interpolation.py?
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 |
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 andwton the cell centres (xt_ocean,yt_ocean),padding:low. MOM5 saveswtonly 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).wtis positive upward, so it is flipped to match depth (positive down).interpolators.BGrid_Velocityimplements the B-grid scheme of Delandmeter and van Sebille (2019), like v3'sbgrid_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_conventionsnow usesBGrid_Velocityby 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 getXLinear_Velocity(see also Rename _is_agrid #2692). The A-grid and C-grid defaults are unchanged.Notes:
xu_ocean/yu_ocean. ACCESS-OM2'sgeolon_c/geolat_care 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.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_sgridwith the defaultBGrid_Velocitygives bit-identical trajectories, depths and sampled temperature to the recipe's hand-written interpolator (100 particles, 4 days).Checklist
mainfor normal development,v3-supportfor v3 support)AI Disclosure
[This is Claude Code on behalf of @navidcy]