|
10 | 10 | from parcels._datasets.structured.generic import T, X, Y, Z, datasets |
11 | 11 | from parcels.grid import Grid as OldGrid |
12 | 12 | from parcels.tools.converters import TimeConverter |
13 | | -from parcels.xgrid import ( |
14 | | - XGrid, |
15 | | - _generate_cells, |
16 | | -) |
| 13 | +from parcels.xgrid import XGrid, _generate_cells, _search_1d_array |
17 | 14 |
|
18 | 15 | GridTestCase = namedtuple("GridTestCase", ["Grid", "attr", "expected"]) |
19 | 16 |
|
@@ -187,3 +184,56 @@ def _assert_point_is( |
187 | 184 | raise ValueError(f"Invalid method: {direction}") |
188 | 185 |
|
189 | 186 | np.testing.assert_allclose(reference_cell + delta, test_cell) |
| 187 | + |
| 188 | + |
| 189 | +@pytest.mark.parametrize( |
| 190 | + "ds", |
| 191 | + [ |
| 192 | + pytest.param(datasets["ds_2d_left"], id="1D lon/lat"), |
| 193 | + pytest.param(datasets["2d_left_rotated"], id="2D lon/lat"), |
| 194 | + ], |
| 195 | +) # for key, ds in datasets.items()]) |
| 196 | +def test_xgrid_search_cpoints(ds): |
| 197 | + grid = XGrid(xgcm.Grid(ds, periodic=False)) |
| 198 | + lat_array, lon_array = get_2d_fpoint_mesh(grid) |
| 199 | + lat_array, lon_array = corner_to_cell_center_points(lat_array, lon_array) |
| 200 | + |
| 201 | + for xi in range(grid.xdim - 1): |
| 202 | + for yi in range(grid.ydim - 1): |
| 203 | + lat, lon = lat_array[yi, xi], lon_array[yi, xi] |
| 204 | + (zi_test, yi_test, xi_test), bcoords = grid.search(0, lat, lon, ei=None, search2D=True) |
| 205 | + assert xi == xi_test |
| 206 | + assert yi == yi_test |
| 207 | + assert zi_test == 0 |
| 208 | + |
| 209 | + # assert np.isclose(bcoords[0], 0.5) #? Should this not be the case with the cell center points? |
| 210 | + # assert np.isclose(bcoords[1], 0.5) |
| 211 | + |
| 212 | + |
| 213 | +def get_2d_fpoint_mesh(grid: XGrid): |
| 214 | + lat, lon = grid.lat, grid.lon |
| 215 | + if lon.ndim == 1: |
| 216 | + lat, lon = np.meshgrid(lat, lon, indexing="ij") |
| 217 | + return lat, lon |
| 218 | + |
| 219 | + |
| 220 | +def corner_to_cell_center_points(lat, lon): |
| 221 | + """Convert F points to C points.""" |
| 222 | + lon_c = (lon[:-1, :-1] + lon[:-1, 1:]) / 2 |
| 223 | + lat_c = (lat[:-1, :-1] + lat[1:, :-1]) / 2 |
| 224 | + return lat_c, lon_c |
| 225 | + |
| 226 | + |
| 227 | +@pytest.mark.parametrize( |
| 228 | + "array, x, expected_xi, expected_xsi", |
| 229 | + [ |
| 230 | + (np.array([1, 2, 3, 4, 5]), 1.1, 0, 0.1), |
| 231 | + (np.array([1, 2, 3, 4, 5]), 2.1, 1, 0.1), |
| 232 | + (np.array([1, 2, 3, 4, 5]), 3.1, 2, 0.1), |
| 233 | + (np.array([1, 2, 3, 4, 5]), 4.5, 3, 0.5), |
| 234 | + ], |
| 235 | +) |
| 236 | +def test_search_1d_array(array, x, expected_xi, expected_xsi): |
| 237 | + xi, xsi = _search_1d_array(array, x) |
| 238 | + assert xi == expected_xi |
| 239 | + assert np.isclose(xsi, expected_xsi) |
0 commit comments