Skip to content

Commit 35b59a4

Browse files
Merge pull request #1942 from OceanParcels/removing_fieldtype_argument
Removing fieldtype argument from Field constructor
2 parents c5273e2 + b9d022a commit 35b59a4

File tree

5 files changed

+29
-92
lines changed

5 files changed

+29
-92
lines changed

docs/examples/tutorial_kernelloop.ipynb

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,9 @@
118118
" \"V\": \"northward_eulerian_current_velocity\",\n",
119119
"}\n",
120120
"dimensions = {\"lat\": \"lat\", \"lon\": \"lon\", \"time\": \"time\"}\n",
121-
"fieldset = parcels.FieldSet.from_netcdf(filenames, variables, dimensions)\n",
121+
"fieldset = parcels.FieldSet.from_netcdf(\n",
122+
" filenames, variables, dimensions, allow_time_extrapolation=True\n",
123+
")\n",
122124
"# uppermost layer in the hydrodynamic data\n",
123125
"fieldset.mindepth = fieldset.U.depth[0]"
124126
]
@@ -137,11 +139,15 @@
137139
" lon=fieldset.U.lon,\n",
138140
" lat=fieldset.U.lat,\n",
139141
" mesh=\"spherical\",\n",
140-
" fieldtype=\"U\",\n",
141142
")\n",
142143
"VWind = parcels.Field(\n",
143-
" \"VWind\", np.zeros((ydim, xdim), dtype=np.float32), grid=UWind.grid, fieldtype=\"V\"\n",
144+
" \"VWind\",\n",
145+
" np.zeros((ydim, xdim), dtype=np.float32),\n",
146+
" grid=UWind.grid,\n",
144147
")\n",
148+
"UWind.units = parcels.tools.converters.GeographicPolar()\n",
149+
"VWind.units = parcels.tools.converters.Geographic()\n",
150+
"\n",
145151
"fieldset_wind = parcels.FieldSet(UWind, VWind)\n",
146152
"\n",
147153
"fieldset.add_field(fieldset_wind.U, name=\"UWind\")\n",

docs/examples/tutorial_unitconverters.ipynb

Lines changed: 0 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -326,31 +326,6 @@
326326
"print(fieldset.Ustokes[0, 0, 40, -5])\n",
327327
"print(fieldset.Ustokes[0, 0, 40, -5] * 1852 * 60 * np.cos(40 * np.pi / 180))"
328328
]
329-
},
330-
{
331-
"attachments": {},
332-
"cell_type": "markdown",
333-
"metadata": {},
334-
"source": [
335-
"Alternatively, the UnitConverter can be set when the `FieldSet` or `Field` is created by using the `fieldtype` argument (use a dictionary in the case of `FieldSet` construction.\n"
336-
]
337-
},
338-
{
339-
"cell_type": "code",
340-
"execution_count": null,
341-
"metadata": {},
342-
"outputs": [],
343-
"source": [
344-
"fieldset.add_field(\n",
345-
" parcels.Field(\n",
346-
" \"Ustokes2\",\n",
347-
" np.ones((ydim, xdim), dtype=np.float32),\n",
348-
" grid=fieldset.U.grid,\n",
349-
" fieldtype=\"U\",\n",
350-
" )\n",
351-
")\n",
352-
"print(fieldset.Ustokes2[0, 0, 40, -5])"
353-
]
354329
}
355330
],
356331
"metadata": {

parcels/field.py

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -123,8 +123,6 @@ class Field:
123123
grid : parcels.grid.Grid
124124
:class:`parcels.grid.Grid` object containing all the lon, lat depth, time
125125
mesh and time_origin information. Can be constructed from any of the Grid objects
126-
fieldtype : str
127-
Type of Field to be used for UnitConverter (either 'U', 'V', 'Kh_zonal', 'Kh_meridional' or None)
128126
time_origin : parcels.tools.converters.TimeConverter
129127
Time origin of the time axis (only if grid is None)
130128
interp_method : str
@@ -148,7 +146,6 @@ def __init__(
148146
time=None,
149147
grid=None,
150148
mesh: Mesh = "flat",
151-
fieldtype=None,
152149
time_origin: TimeConverter | None = None,
153150
interp_method: InterpMethod = "linear",
154151
allow_time_extrapolation: bool | None = None,
@@ -170,13 +167,12 @@ def __init__(
170167
time_origin = TimeConverter(0)
171168
self._grid = Grid.create_grid(lon, lat, depth, time, time_origin=time_origin, mesh=mesh)
172169
self.igrid = -1
173-
self.fieldtype = self.name if fieldtype is None else fieldtype
174-
if self.grid.mesh == "flat" or (self.fieldtype not in unitconverters_map.keys()):
175-
self.units = UnitConverter()
176-
elif self.grid.mesh == "spherical":
177-
self.units = unitconverters_map[self.fieldtype]
178-
else:
179-
raise ValueError("Unsupported mesh type. Choose either: 'spherical' or 'flat'")
170+
self.units = UnitConverter()
171+
if self.grid.mesh == "spherical":
172+
try:
173+
self.units = unitconverters_map[self.name]
174+
except KeyError:
175+
pass
180176
if isinstance(interp_method, dict):
181177
if self.name in interp_method:
182178
self.interp_method = interp_method[self.name]
@@ -216,6 +212,16 @@ def __init__(
216212
def __repr__(self) -> str:
217213
return field_repr(self)
218214

215+
@property
216+
def units(self):
217+
return self._units
218+
219+
@units.setter
220+
def units(self, value):
221+
if not isinstance(value, UnitConverter):
222+
raise ValueError(f"Units must be a UnitConverter object, got {type(value)}")
223+
self._units = value
224+
219225
@property
220226
def grid(self):
221227
return self._grid

parcels/fieldset.py

Lines changed: 0 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -279,7 +279,6 @@ def from_netcdf(
279279
filenames,
280280
variables,
281281
dimensions,
282-
fieldtype=None,
283282
mesh: Mesh = "spherical",
284283
allow_time_extrapolation: bool | None = None,
285284
**kwargs,
@@ -305,9 +304,6 @@ def from_netcdf(
305304
Note that dimensions can also be a dictionary of dictionaries if
306305
dimension names are different for each variable
307306
(e.g. dimensions['U'], dimensions['V'], etc).
308-
fieldtype :
309-
Optional dictionary mapping fields to fieldtypes to be used for UnitConverter.
310-
(either 'U', 'V', 'Kh_zonal', 'Kh_meridional' or None) (Default value = None)
311307
mesh : str
312308
String indicating the type of mesh coordinates and
313309
units used during velocity interpolation, see also `this tutorial <../examples/tutorial_unitconverters.ipynb>`__:
@@ -353,7 +349,6 @@ def from_netcdf(
353349
# Use dimensions[var] if it's a dict of dicts
354350
dims = dimensions[var] if var in dimensions else dimensions
355351
cls.checkvaliddimensionsdict(dims)
356-
fieldtype = fieldtype[var] if (fieldtype and var in fieldtype) else fieldtype
357352

358353
grid = None
359354

@@ -364,7 +359,6 @@ def from_netcdf(
364359
grid=grid,
365360
mesh=mesh,
366361
allow_time_extrapolation=allow_time_extrapolation,
367-
fieldtype=fieldtype,
368362
**kwargs,
369363
)
370364

@@ -426,9 +420,6 @@ def from_nemo(
426420
(for indexing details: https://www.nemo-ocean.eu/doc/img360.png )
427421
In 3D, the depth is the one corresponding to W nodes
428422
The gridindexingtype is set to 'nemo'. See also the Grid indexing documentation on oceanparcels.org
429-
fieldtype :
430-
Optional dictionary mapping fields to fieldtypes to be used for UnitConverter.
431-
(either 'U', 'V', 'Kh_zonal', 'Kh_meridional' or None)
432423
mesh : str
433424
String indicating the type of mesh coordinates and
434425
units used during velocity interpolation, see also `this tutorial <../examples/tutorial_unitconverters.ipynb>`__:
@@ -635,9 +626,6 @@ def from_c_grid_dataset(
635626
which are located on the corners of the cells.
636627
(for indexing details: https://www.nemo-ocean.eu/doc/img360.png )
637628
In 3D, the depth is the one corresponding to W nodes.
638-
fieldtype :
639-
Optional dictionary mapping fields to fieldtypes to be used for UnitConverter.
640-
(either 'U', 'V', 'Kh_zonal', 'Kh_meridional' or None)
641629
mesh : str
642630
String indicating the type of mesh coordinates and
643631
units used during velocity interpolation, see also `this tutorial <../examples/tutorial_unitconverters.ipynb>`__:
@@ -738,9 +726,6 @@ def from_mom5(
738726
Note that W is normally directed upward in MOM5, but Parcels requires W
739727
in the positive z-direction (downward) so W is multiplied by -1.
740728
T node is at the cell centre, and constant per cell.
741-
fieldtype :
742-
Optional dictionary mapping fields to fieldtypes to be used for UnitConverter.
743-
(either 'U', 'V', 'Kh_zonal', 'Kh_meridional' or None)
744729
mesh : str
745730
String indicating the type of mesh coordinates and
746731
units used during velocity interpolation, see also the `Unit converters tutorial <../examples/tutorial_unitconverters.ipynb>`__:
@@ -841,9 +826,6 @@ def from_b_grid_dataset(
841826
W nodes are at the centre of the horizontal interfaces.
842827
They are interpolated linearly (as a function of z) in the cell.
843828
T node is at the cell centre, and constant per cell.
844-
fieldtype :
845-
Optional dictionary mapping fields to fieldtypes to be used for UnitConverter.
846-
(either 'U', 'V', 'Kh_zonal', 'Kh_meridional' or None)
847829
mesh : str
848830
String indicating the type of mesh coordinates and
849831
units used during velocity interpolation, see also `this tutorial <../examples/tutorial_unitconverters.ipynb>`__:
@@ -908,9 +890,6 @@ def from_xarray_dataset(cls, ds, variables, dimensions, mesh="spherical", allow_
908890
Note that dimensions can also be a dictionary of dictionaries if
909891
dimension names are different for each variable
910892
(e.g. dimensions['U'], dimensions['V'], etc).
911-
fieldtype :
912-
Optional dictionary mapping fields to fieldtypes to be used for UnitConverter.
913-
(either 'U', 'V', 'Kh_zonal', 'Kh_meridional' or None)
914893
mesh : str
915894
String indicating the type of mesh coordinates and
916895
units used during velocity interpolation, see also `this tutorial <../examples/tutorial_unitconverters.ipynb>`__:

tests/test_fieldset.py

Lines changed: 4 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,6 @@
1313
Variable,
1414
)
1515
from parcels.field import Field, VectorField
16-
from parcels.tools.converters import (
17-
GeographicPolar,
18-
UnitConverter,
19-
)
2016
from tests.utils import TEST_DATA
2117

2218

@@ -161,31 +157,6 @@ def test_fieldset_from_modulefile():
161157
FieldSet.from_modulefile(nemo_error_fname, modulename="none_returning_function")
162158

163159

164-
def test_field_from_netcdf_fieldtypes():
165-
filenames = {
166-
"varU": {
167-
"lon": str(TEST_DATA / "mask_nemo_cross_180lon.nc"),
168-
"lat": str(TEST_DATA / "mask_nemo_cross_180lon.nc"),
169-
"data": str(TEST_DATA / "Uu_eastward_nemo_cross_180lon.nc"),
170-
},
171-
"varV": {
172-
"lon": str(TEST_DATA / "mask_nemo_cross_180lon.nc"),
173-
"lat": str(TEST_DATA / "mask_nemo_cross_180lon.nc"),
174-
"data": str(TEST_DATA / "Vv_eastward_nemo_cross_180lon.nc"),
175-
},
176-
}
177-
variables = {"varU": "U", "varV": "V"}
178-
dimensions = {"lon": "glamf", "lat": "gphif"}
179-
180-
# first try without setting fieldtype
181-
fset = FieldSet.from_nemo(filenames, variables, dimensions)
182-
assert isinstance(fset.varU.units, UnitConverter)
183-
184-
# now try with setting fieldtype
185-
fset = FieldSet.from_nemo(filenames, variables, dimensions, fieldtype={"varU": "U", "varV": "V"})
186-
assert isinstance(fset.varU.units, GeographicPolar)
187-
188-
189160
def test_fieldset_from_agrid_dataset():
190161
filenames = {
191162
"lon": str(TEST_DATA / "mask_nemo_cross_180lon.nc"),
@@ -250,18 +221,18 @@ def test_add_duplicate_field(dupobject):
250221
fieldset.add_field(field2)
251222

252223

253-
@pytest.mark.parametrize("fieldtype", ["normal", "vector"])
254-
def test_add_field_after_pset(fieldtype):
224+
@pytest.mark.parametrize("field_type", ["normal", "vector"])
225+
def test_add_field_after_pset(field_type):
255226
data, dimensions = generate_fieldset_data(100, 100)
256227
fieldset = FieldSet.from_data(data, dimensions)
257228
pset = ParticleSet(fieldset, Particle, lon=0, lat=0) # noqa ; to trigger fieldset._check_complete
258229
field1 = Field("field1", fieldset.U.data, lon=fieldset.U.lon, lat=fieldset.U.lat)
259230
field2 = Field("field2", fieldset.U.data, lon=fieldset.U.lon, lat=fieldset.U.lat)
260231
vfield = VectorField("vfield", field1, field2)
261232
with pytest.raises(RuntimeError):
262-
if fieldtype == "normal":
233+
if field_type == "normal":
263234
fieldset.add_field(field1)
264-
elif fieldtype == "vector":
235+
elif field_type == "vector":
265236
fieldset.add_vector_field(vfield)
266237

267238

0 commit comments

Comments
 (0)