-
Notifications
You must be signed in to change notification settings - Fork 171
Expand file tree
/
Copy pathtest_field.py
More file actions
276 lines (225 loc) · 9.69 KB
/
test_field.py
File metadata and controls
276 lines (225 loc) · 9.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
from __future__ import annotations
import numpy as np
import pytest
import uxarray as ux
import xarray as xr
from parcels import Field, UxGrid, VectorField, XGrid
from parcels._datasets.structured.generic import T as T_structured
from parcels._datasets.structured.generic import datasets as datasets_structured
from parcels._datasets.unstructured.generic import datasets as datasets_unstructured
from parcels.interpolators import UxPiecewiseConstantFace, UxPiecewiseLinearNode, XLinear
def test_field_init_param_types():
data = datasets_structured["ds_2d_left"]
grid = XGrid.from_dataset(data, mesh="flat")
with pytest.raises(TypeError, match="Expected a string for variable name, got int instead."):
Field(name=123, data=data["data_g"], grid=grid, interp_method=XLinear)
for name in ["a b", "123"]:
with pytest.raises(
ValueError,
match=r"Received invalid Python variable name.*: not a valid identifier. HINT: avoid using spaces, special characters, and starting with a number.",
):
Field(name=name, data=data["data_g"], grid=grid, interp_method=XLinear)
with pytest.raises(
ValueError,
match=r"Received invalid Python variable name.*: it is a reserved keyword. HINT: avoid using the following names:.*",
):
Field(name="while", data=data["data_g"], grid=grid, interp_method=XLinear)
with pytest.raises(
ValueError,
match="Expected `data` to be a uxarray.UxDataArray or xarray.DataArray",
):
Field(name="test", data=123, grid=grid, interp_method=XLinear)
with pytest.raises(ValueError, match="Expected `grid` to be a parcels UxGrid, or parcels XGrid"):
Field(name="test", data=data["data_g"], grid=123, interp_method=XLinear)
@pytest.mark.parametrize(
"data,grid",
[
pytest.param(
ux.UxDataArray(),
XGrid.from_dataset(datasets_structured["ds_2d_left"], mesh="flat"),
id="uxdata-grid",
),
pytest.param(
xr.DataArray(),
UxGrid(
datasets_unstructured["stommel_gyre_delaunay"].uxgrid,
z=datasets_unstructured["stommel_gyre_delaunay"].coords["nz"],
mesh="flat",
),
id="xarray-uxgrid",
),
],
)
def test_field_incompatible_combination(data, grid):
with pytest.raises(ValueError, match="Incompatible data-grid combination."):
Field(
name="test_field",
data=data,
grid=grid,
interp_method=XLinear,
)
@pytest.mark.parametrize(
"data,grid",
[
pytest.param(
datasets_structured["ds_2d_left"]["data_g"],
XGrid.from_dataset(datasets_structured["ds_2d_left"], mesh="flat"),
id="ds_2d_left",
), # TODO: Perhaps this test should be expanded to cover more datasets?
],
)
def test_field_init_structured_grid(data, grid):
"""Test creating a field."""
field = Field(
name="test_field",
data=data,
grid=grid,
interp_method=XLinear,
)
assert field.name == "test_field"
assert field.data.equals(data)
assert field.grid == grid
def test_field_init_fail_on_float_time_dim():
"""Test field initialisation fails when given float array as time dimension.
(users are expected to use timedelta64 or datetime).
"""
ds = datasets_structured["ds_2d_left"].copy()
ds["time"] = (
ds["time"].dims,
np.arange(0, T_structured, dtype="float64"),
ds["time"].attrs,
)
data = ds["data_g"]
grid = XGrid.from_dataset(ds, mesh="flat")
with pytest.raises(
ValueError,
match="Error getting time interval.*. Are you sure that the time dimension on the xarray dataset is stored as timedelta, datetime or cftime datetime objects\?",
):
Field(
name="test_field",
data=data,
grid=grid,
interp_method=XLinear,
)
@pytest.mark.parametrize(
"data,grid",
[
pytest.param(
datasets_structured["ds_2d_left"]["data_g"],
XGrid.from_dataset(datasets_structured["ds_2d_left"], mesh="flat"),
id="ds_2d_left",
),
],
)
def test_field_time_interval(data, grid):
"""Test creating a field."""
field = Field(name="test_field", data=data, grid=grid, interp_method=XLinear)
assert field.time_interval.left == np.datetime64("2000-01-01")
assert field.time_interval.right == np.datetime64("2001-01-01")
def test_vectorfield_init_different_time_intervals():
# Tests that a VectorField raises a ValueError if the component fields have different time domains.
...
def test_field_invalid_interpolator():
ds = datasets_structured["ds_2d_left"]
grid = XGrid.from_dataset(ds, mesh="flat")
def invalid_interpolator_wrong_signature(particle_positions, grid_positions, invalid):
return 0.0
# Test invalid interpolator with wrong signature
with pytest.raises(ValueError, match=".*incorrect name.*"):
Field(
name="test",
data=ds["data_g"],
grid=grid,
interp_method=invalid_interpolator_wrong_signature,
)
@pytest.mark.parametrize("fill_value", [-999.99, 0.0, 42, None])
def test_field_land_value(fill_value):
ds = datasets_structured["ds_2d_left"].copy()
if fill_value is not None:
ds["data_g"].attrs["_FillValue"] = fill_value
grid = XGrid.from_dataset(ds, mesh="flat")
field = Field(name="test_field", data=ds["data_g"], grid=grid, interp_method=XLinear)
if fill_value is None:
assert field.land_value == 0.0
else:
assert field.land_value == fill_value
def test_vectorfield_invalid_interpolator():
ds = datasets_structured["ds_2d_left"]
grid = XGrid.from_dataset(ds, mesh="flat")
def invalid_interpolator_wrong_signature(particle_positions, grid_positions, invalid):
return 0.0
# Create component fields
U = Field(name="U", data=ds["data_g"], grid=grid, interp_method=XLinear)
V = Field(name="V", data=ds["data_g"], grid=grid, interp_method=XLinear)
# Test invalid interpolator with wrong signature
with pytest.raises(ValueError, match=".*incorrect name.*"):
VectorField(
name="UV",
U=U,
V=V,
vector_interp_method=invalid_interpolator_wrong_signature,
)
def test_field_unstructured_z_linear():
"""Tests correctness of piecewise constant and piecewise linear interpolation methods on an unstructured grid with a vertical coordinate.
The example dataset is a FESOM2 square Delaunay grid with uniform z-coordinate. Cell centered and layer registered data are defined to be
linear functions of the vertical coordinate. This allows for testing of exactness of the interpolation methods.
"""
ds = datasets_unstructured["fesom2_square_delaunay_uniform_z_coordinate"].copy(deep=True)
# Change the pressure values to be linearly dependent on the vertical coordinate
for k, z in enumerate(ds.coords["nz1"]):
ds["p"].values[:, k, :] = z
# Change the vertical velocity values to be linearly dependent on the vertical coordinate
for k, z in enumerate(ds.coords["nz"]):
ds["W"].values[:, k, :] = z
grid = UxGrid(ds.uxgrid, z=ds.coords["nz"], mesh="flat")
# Note that the vertical coordinate is required to be the position of the layer interfaces ("nz"), not the mid-layers ("nz1")
P = Field(name="p", data=ds.p, grid=grid, interp_method=UxPiecewiseConstantFace)
# Test above first cell center - for piecewise constant, should return the depth of the first cell center
assert np.isclose(
P.eval(time=[0], z=[10.0], y=[30.0], x=[30.0], applyConversion=False),
55.555557,
)
# Test below first cell center, but in the first layer - for piecewise constant, should return the depth of the first cell center
assert np.isclose(
P.eval(time=[0], z=[65.0], y=[30.0], x=[30.0], applyConversion=False),
55.555557,
)
# Test bottom layer - for piecewise constant, should return the depth of the of the bottom layer cell center
assert np.isclose(
P.eval(time=[0], z=[900.0], y=[30.0], x=[30.0], applyConversion=False),
944.44445801,
)
W = Field(name="W", data=ds.W, grid=grid, interp_method=UxPiecewiseLinearNode)
assert np.isclose(
W.eval(time=[0], z=[10.0], y=[30.0], x=[30.0], applyConversion=False),
10.0,
)
assert np.isclose(
W.eval(time=[0], z=[65.0], y=[30.0], x=[30.0], applyConversion=False),
65.0,
)
assert np.isclose(
W.eval(time=[0], z=[900.0], y=[30.0], x=[30.0], applyConversion=False),
900.0,
)
def test_field_constant_in_time():
"""Tests field evaluation for a field with no time interval (i.e., constant in time)."""
ds = datasets_unstructured["stommel_gyre_delaunay"]
grid = UxGrid(ds.uxgrid, z=ds.coords["nz"], mesh="flat")
# Note that the vertical coordinate is required to be the position of the layer interfaces ("nz"), not the mid-layers ("nz1")
P = Field(name="p", data=ds.p, grid=grid, interp_method=UxPiecewiseConstantFace)
# Assert that the field can be evaluated at any time, and returns the same value
time = np.datetime64("2000-01-01T00:00:00")
P1 = P.eval(time=time, z=[10.0], y=[30.0], x=[30.0], applyConversion=False)
P2 = P.eval(
time=time + np.timedelta64(1, "D"),
z=[10.0],
y=[30.0],
x=[30.0],
applyConversion=False,
)
assert np.isclose(P1, P2)
def test_field_unstructured_grid_creation(): ...
def test_field_interpolation(): ...
def test_field_interpolation_out_of_spatial_bounds(): ...
def test_field_interpolation_out_of_time_bounds(): ...