Skip to content

Commit 486c5b6

Browse files
Merge pull request #2364 from Parcels-code/error_when_dims_have_no_axis
Raise error when creating Field with dimensions without axis
2 parents 5f2e8ec + da5645f commit 486c5b6

File tree

3 files changed

+19
-1
lines changed

3 files changed

+19
-1
lines changed

src/parcels/_core/field.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
from parcels._core.utils.string import _assert_str_and_python_varname
2222
from parcels._core.utils.time import TimeInterval
2323
from parcels._core.uxgrid import UxGrid
24-
from parcels._core.xgrid import XGrid, _transpose_xfield_data_to_tzyx
24+
from parcels._core.xgrid import XGrid, _transpose_xfield_data_to_tzyx, assert_all_field_dims_have_axis
2525
from parcels._python import assert_same_function_signature
2626
from parcels._reprs import default_repr
2727
from parcels._typing import VectorType
@@ -103,6 +103,7 @@ def __init__(
103103
_assert_compatible_combination(data, grid)
104104

105105
if isinstance(grid, XGrid):
106+
assert_all_field_dims_have_axis(data, grid.xgcm_grid)
106107
data = _transpose_xfield_data_to_tzyx(data, grid.xgcm_grid)
107108

108109
self.name = name

src/parcels/_core/xgrid.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,16 @@ def _drop_field_data(ds: xr.Dataset) -> xr.Dataset:
4848
return ds.drop_vars(ds.data_vars)
4949

5050

51+
def assert_all_field_dims_have_axis(da: xr.DataArray, xgcm_grid: xgcm.Grid) -> None:
52+
ax_dims = [(get_axis_from_dim_name(xgcm_grid.axes, dim), dim) for dim in da.dims]
53+
for dim in ax_dims:
54+
if dim[0] is None:
55+
raise ValueError(
56+
f'Dimension "{dim[1]}" has no axis attribute. '
57+
f'HINT: You may want to add an {{"axis": A}} to your DataSet["{dim[1]}"], where A is one of "X", "Y", "Z" or "T"'
58+
)
59+
60+
5161
def _transpose_xfield_data_to_tzyx(da: xr.DataArray, xgcm_grid: xgcm.Grid) -> xr.DataArray:
5262
"""
5363
Transpose a DataArray of any shape into a 4D array of order TZYX. Uses xgcm to determine

tests/test_xgrid.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,13 @@ def test_invalid_depth():
136136
XGrid.from_dataset(ds)
137137

138138

139+
def test_dim_without_axis():
140+
ds = xr.Dataset({"z1d": (["depth"], [0])}, coords={"depth": [0]})
141+
grid = XGrid.from_dataset(ds)
142+
with pytest.raises(ValueError, match='Dimension "depth" has no axis attribute*'):
143+
Field("z1d", ds["z1d"], grid, XLinear)
144+
145+
139146
def test_vertical1D_field():
140147
nz = 11
141148
ds = xr.Dataset(

0 commit comments

Comments
 (0)