Skip to content

Commit 3c21377

Browse files
Merge pull request #1938 from OceanParcels/removing_field_towrite
Removing Field.to_write and FieldSet.to_write methods
2 parents 6c5f89e + 46afa8c commit 3c21377

12 files changed

Lines changed: 10 additions & 177 deletions

.github/workflows/ci.yml

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -76,10 +76,13 @@ jobs:
7676
with:
7777
environment-file: environment.yml
7878
- name: Integration test
79-
# TODO v4: Re-enable `tutorial_periodic_boundaries`, `tutorial_timevaryingdepthdimensions` and `tutorial_croco_3D` notebooks
80-
# TODO v4: Re-enable `tutorial_nemo_3D` notebook once 3D grids are implemented (https://github.com/OceanParcels/Parcels/pull/1936#issuecomment-2717666705)
79+
# TODO v4: Re-enable `tutorial_periodic_boundaries`
80+
# TODO v4: Re-enable `tutorial_timevaryingdepthdimensions`
81+
# TODO v4: Re-enable `tutorial_particle_field_interaction`
82+
# TODO v4: Re-enable `tutorial_croco_3D`
83+
# TODO v4: Re-enable `tutorial_nemo_3D` (https://github.com/OceanParcels/Parcels/pull/1936#issuecomment-2717666705)
8184
run: |
82-
coverage run -m pytest -v -s --nbval-lax -k "not documentation and not tutorial_periodic_boundaries and not tutorial_timevaryingdepthdimensions and not tutorial_croco_3D and not tutorial_nemo_3D" --html="${{ matrix.os }}_${{ matrix.python-version }}_integration_test_report.html" --self-contained-html docs/examples
85+
coverage run -m pytest -v -s --nbval-lax -k "not documentation and not tutorial_periodic_boundaries and not tutorial_timevaryingdepthdimensions and not tutorial_particle_field_interaction and not tutorial_croco_3D and not tutorial_nemo_3D" --html="${{ matrix.os }}_${{ matrix.python-version }}_integration_test_report.html" --self-contained-html docs/examples
8386
coverage xml
8487
- name: Codecov
8588
uses: codecov/codecov-action@v5.3.1

docs/examples/example_decaying_moving_eddy.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -99,10 +99,8 @@ def test_rotation_example(tmpdir):
9999

100100

101101
def main():
102-
fset_filename = "decaying_moving_eddy"
103102
outfile = "DecayingMovingParticle.zarr"
104103
fieldset = decaying_moving_eddy_fieldset()
105-
fieldset.write(fset_filename)
106104

107105
decaying_moving_example(fieldset, outfile)
108106

docs/examples/example_peninsula.py

Lines changed: 0 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -207,14 +207,6 @@ def test_peninsula_fieldset_AnalyticalAdvection(mesh, tmpdir):
207207
assert (err_adv <= 3.0e2).all()
208208

209209

210-
def fieldsetfile(mesh, tmpdir):
211-
"""Generate fieldset files for peninsula test."""
212-
filename = tmpdir.join("peninsula")
213-
fieldset = peninsula_fieldset(100, 50, mesh=mesh)
214-
fieldset.write(filename)
215-
return filename
216-
217-
218210
def test_peninsula_file(tmpdir):
219211
"""Open fieldset files and execute."""
220212
data_folder = parcels.download_example_dataset("Peninsula_data")
@@ -294,24 +286,10 @@ def main(args=None):
294286
)
295287
args = p.parse_args(args)
296288

297-
filename = "peninsula"
298289
if args.fieldset is not None:
299290
fieldset = peninsula_fieldset(args.fieldset[0], args.fieldset[1], mesh="flat")
300291
else:
301292
fieldset = peninsula_fieldset(100, 50, mesh="flat")
302-
fieldset.write(filename)
303-
304-
# Open fieldset file set
305-
filenames = {
306-
"U": f"{filename}U.nc",
307-
"V": f"{filename}V.nc",
308-
"P": f"{filename}P.nc",
309-
}
310-
variables = {"U": "vozocrtx", "V": "vomecrty", "P": "P"}
311-
dimensions = {"lon": "nav_lon", "lat": "nav_lat", "time": "time_counter"}
312-
fieldset = parcels.FieldSet.from_netcdf(
313-
filenames, variables, dimensions, allow_time_extrapolation=True
314-
)
315293

316294
outfile = "Peninsula"
317295

docs/examples/example_radial_rotation.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -86,10 +86,7 @@ def test_rotation_example(tmpdir):
8686

8787

8888
def main():
89-
filename = "radial_rotation"
9089
fieldset = radial_rotation_fieldset()
91-
fieldset.write(filename)
92-
9390
outfile = "RadialParticle"
9491
rotation_example(fieldset, outfile)
9592

docs/examples/example_stommel.py

Lines changed: 0 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -101,16 +101,12 @@ def stommel_example(
101101
outfile="StommelParticle.zarr",
102102
repeatdt=None,
103103
maxage=None,
104-
write_fields=True,
105104
custom_partition_function=False,
106105
):
107106
parcels.timer.fieldset = parcels.timer.Timer(
108107
"FieldSet", parent=parcels.timer.stommel
109108
)
110109
fieldset = stommel_fieldset(grid_type=grid_type)
111-
if write_fields:
112-
filename = "stommel"
113-
fieldset.write(filename)
114110
parcels.timer.fieldset.stop()
115111

116112
parcels.timer.pset = parcels.timer.Timer("Pset", parent=parcels.timer.stommel)
@@ -184,14 +180,12 @@ def test_stommel_fieldset(grid_type, tmpdir):
184180
method=method["RK4"],
185181
grid_type=grid_type,
186182
outfile=outfile,
187-
write_fields=False,
188183
)
189184
psetRK45 = stommel_example(
190185
1,
191186
method=method["RK45"],
192187
grid_type=grid_type,
193188
outfile=outfile,
194-
write_fields=False,
195189
)
196190
assert np.allclose(psetRK4.lon, psetRK45.lon, rtol=1e-3)
197191
assert np.allclose(psetRK4.lat, psetRK45.lat, rtol=1.1e-3)
@@ -251,12 +245,6 @@ def main(args=None):
251245
type=int,
252246
help="max age of the particles (after which particles are deleted)",
253247
)
254-
p.add_argument(
255-
"-wf",
256-
"--write_fields",
257-
default=True,
258-
help="Write the hydrodynamic fields to NetCDF",
259-
)
260248
p.add_argument(
261249
"-cpf",
262250
"--custom_partition_function",
@@ -274,7 +262,6 @@ def main(args=None):
274262
outfile=args.outfile,
275263
repeatdt=args.repeatdt,
276264
maxage=args.maxage,
277-
write_fields=args.write_fields,
278265
custom_partition_function=args.custom_partition_function,
279266
)
280267
parcels.timer.stommel.stop()

parcels/field.py

Lines changed: 0 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import collections
22
import math
33
import warnings
4-
from pathlib import Path
54
from typing import TYPE_CHECKING, cast
65

76
import dask.array as da
@@ -134,9 +133,6 @@ class Field:
134133
allow_time_extrapolation : bool
135134
boolean whether to allow for extrapolation in time
136135
(i.e. beyond the last available time snapshot)
137-
to_write : bool
138-
Write the Field in NetCDF format at the same frequency as the ParticleFile outputdt,
139-
using a filenaming scheme based on the ParticleFile name
140136
141137
"""
142138

@@ -157,7 +153,6 @@ def __init__(
157153
interp_method: InterpMethod = "linear",
158154
allow_time_extrapolation: bool | None = None,
159155
gridindexingtype: GridIndexingType = "nemo",
160-
to_write: bool = False,
161156
data_full_zdim=None,
162157
):
163158
if not isinstance(name, tuple):
@@ -176,7 +171,6 @@ def __init__(
176171
self._grid = Grid.create_grid(lon, lat, depth, time, time_origin=time_origin, mesh=mesh)
177172
self.igrid = -1
178173
self.fieldtype = self.name if fieldtype is None else fieldtype
179-
self.to_write = to_write
180174
if self.grid.mesh == "flat" or (self.fieldtype not in unitconverters_map.keys()):
181175
self.units = UnitConverter()
182176
elif self.grid.mesh == "spherical":
@@ -631,53 +625,6 @@ def eval(self, time, z, y, x, particle=None, applyConversion=True):
631625
else:
632626
return value
633627

634-
def write(self, filename, varname=None):
635-
"""Write a :class:`Field` to a netcdf file.
636-
637-
Parameters
638-
----------
639-
filename : str
640-
Basename of the file (i.e. '{filename}{Field.name}.nc')
641-
varname : str
642-
Name of the field, to be appended to the filename. (Default value = None)
643-
"""
644-
filepath = str(Path(f"{filename}{self.name}.nc"))
645-
if varname is None:
646-
varname = self.name
647-
# Derive name of 'depth' variable for NEMO convention
648-
vname_depth = f"depth{self.name.lower()}"
649-
650-
# Create DataArray objects for file I/O
651-
if self.grid._gtype == GridType.RectilinearZGrid:
652-
nav_lon = xr.DataArray(
653-
self.grid.lon + np.zeros((self.grid.ydim, self.grid.xdim), dtype=np.float32),
654-
coords=[("y", self.grid.lat), ("x", self.grid.lon)],
655-
)
656-
nav_lat = xr.DataArray(
657-
self.grid.lat.reshape(self.grid.ydim, 1) + np.zeros(self.grid.xdim, dtype=np.float32),
658-
coords=[("y", self.grid.lat), ("x", self.grid.lon)],
659-
)
660-
elif self.grid._gtype == GridType.CurvilinearZGrid:
661-
nav_lon = xr.DataArray(self.grid.lon, coords=[("y", range(self.grid.ydim)), ("x", range(self.grid.xdim))])
662-
nav_lat = xr.DataArray(self.grid.lat, coords=[("y", range(self.grid.ydim)), ("x", range(self.grid.xdim))])
663-
else:
664-
raise NotImplementedError("Field.write only implemented for RectilinearZGrid and CurvilinearZGrid")
665-
666-
attrs = {"units": "seconds since " + str(self.grid.time_origin)} if self.grid.time_origin.calendar else {}
667-
time_counter = xr.DataArray(self.grid.time, dims=["time_counter"], attrs=attrs)
668-
vardata = xr.DataArray(
669-
self.data.reshape((self.grid.tdim, self.grid.zdim, self.grid.ydim, self.grid.xdim)),
670-
dims=["time_counter", vname_depth, "y", "x"],
671-
)
672-
# Create xarray Dataset and output to netCDF format
673-
attrs = {"parcels_mesh": self.grid.mesh}
674-
dset = xr.Dataset(
675-
{varname: vardata},
676-
coords={"nav_lon": nav_lon, "nav_lat": nav_lat, "time_counter": time_counter, vname_depth: self.grid.depth},
677-
attrs=attrs,
678-
)
679-
dset.to_netcdf(filepath, unlimited_dims="time_counter")
680-
681628
def _rescale_and_set_minmax(self, data):
682629
data[np.isnan(data)] = 0
683630
return data

parcels/fieldset.py

Lines changed: 0 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -6,15 +6,13 @@
66

77
import numpy as np
88

9-
from parcels._compat import MPI
109
from parcels._typing import GridIndexingType, InterpMethodOption, Mesh
1110
from parcels.field import Field, VectorField
1211
from parcels.grid import Grid
1312
from parcels.gridset import GridSet
1413
from parcels.particlefile import ParticleFile
1514
from parcels.tools._helpers import fieldset_repr
1615
from parcels.tools.converters import TimeConverter
17-
from parcels.tools.loggers import logger
1816
from parcels.tools.warnings import FieldSetWarning
1917

2018
__all__ = ["FieldSet"]
@@ -1003,26 +1001,6 @@ def add_constant(self, name, value):
10031001
"""
10041002
setattr(self, name, value)
10051003

1006-
def write(self, filename):
1007-
"""Write FieldSet to NetCDF file using NEMO convention.
1008-
1009-
Parameters
1010-
----------
1011-
filename : str
1012-
Basename of the output fileset.
1013-
"""
1014-
if MPI is None or MPI.COMM_WORLD.Get_rank() == 0:
1015-
logger.info(f"Generating FieldSet output with basename: {filename}")
1016-
1017-
if hasattr(self, "U"):
1018-
self.U.write(filename, varname="vozocrtx")
1019-
if hasattr(self, "V"):
1020-
self.V.write(filename, varname="vomecrty")
1021-
1022-
for v in self.get_fields():
1023-
if isinstance(v, Field) and (v.name != "U") and (v.name != "V"):
1024-
v.write(filename)
1025-
10261004
def computeTimeChunk(self, time=0.0, dt=1):
10271005
"""Load a chunk of three data time steps into the FieldSet.
10281006
This is used when FieldSet uses data imported from netcdf,

parcels/tools/_helpers.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,6 @@ def field_repr(field: Field) -> str:
7575
grid : {field.grid!r}
7676
extrapolate time: {field.allow_time_extrapolation!r}
7777
gridindexingtype: {field.gridindexingtype!r}
78-
to_write : {field.to_write!r}
7978
"""
8079
return textwrap.dedent(out).strip()
8180

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ platforms = ["win-64", "linux-64", "osx-64", "osx-arm64"]
4646

4747
[tool.pixi.tasks]
4848
tests = "pytest"
49-
tests-notebooks = "pytest -v -s --nbval-lax -k 'not documentation and not tutorial_periodic_boundaries and not tutorial_timevaryingdepthdimensions and not tutorial_croco_3D and not tutorial_nemo_3D'" # TODO v4: Re-enable `tutorial_periodic_boundaries`, `tutorial_timevaryingdepthdimensions`, `tutorial_croco_3D`, `tutorial_nemo_3D` notebooks
49+
tests-notebooks = "pytest -v -s --nbval-lax -k 'not documentation and not tutorial_periodic_boundaries and not tutorial_timevaryingdepthdimensions and not tutorial_particle_field_interaction and not tutorial_croco_3D and not tutorial_nemo_3D'" # TODO v4: Mirror ci.yml for notebooks being run
5050
coverage = "coverage run -m pytest && coverage html"
5151
typing = "mypy parcels"
5252
pre-commit = "pre-commit run --all-files"

tests/test_advection.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -459,7 +459,6 @@ def test_stationary_eddy_vertical():
459459
pset.execute(AdvectionRK4_3D, dt=dt, endtime=endtime)
460460
exp_lon = [truth_stationary(x, z, pset[0].time)[0] for x, z in zip(lon, depth, strict=True)]
461461
exp_depth = [truth_stationary(x, z, pset[0].time)[1] for x, z in zip(lon, depth, strict=True)]
462-
print(pset, exp_lon)
463462
assert np.allclose(pset.lon, exp_lon, rtol=1e-5)
464463
assert np.allclose(pset.lat, lat, rtol=1e-5)
465464
assert np.allclose(pset.depth, exp_depth, rtol=1e-5)

0 commit comments

Comments
 (0)