Skip to content

Commit

Permalink
Merge pull request #1821 from OceanParcels/v/test-suite
Browse files Browse the repository at this point in the history
Move Field tests to separate file
  • Loading branch information
VeckoTheGecko authored Jan 10, 2025
2 parents 7586d7d + 3dcdf53 commit 02eb9a7
Show file tree
Hide file tree
Showing 4 changed files with 71 additions and 64 deletions.
1 change: 0 additions & 1 deletion parcels/_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ class ParcelsAST(ast.AST):
"bgrid_w_velocity",
"cgrid_velocity",
"linear_invdist_land_tracer",
"nearest",
"bgrid_tracer",
"cgrid_tracer",
] # corresponds with `tracer_interp_method`
Expand Down
1 change: 0 additions & 1 deletion tests/test_advection.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,6 @@ def test_advection_zonal(lon, lat, depth, mode):
}
dimensions = {"lon": lon, "lat": lat}
fieldset2D = FieldSet.from_data(data2D, dimensions, mesh="spherical", transpose=True)
assert fieldset2D.U._creation_log == "from_data"

pset2D = ParticleSet(fieldset2D, pclass=ptype[mode], lon=np.zeros(npart) + 20.0, lat=np.linspace(0, 80, npart))
pset2D.execute(AdvectionRK4, runtime=timedelta(hours=2), dt=timedelta(seconds=30))
Expand Down
70 changes: 70 additions & 0 deletions tests/test_field.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import cftime
import numpy as np
import pytest
import xarray as xr

from parcels import Field
from parcels.tools.converters import (
_get_cftime_calendars,
_get_cftime_datetimes,
)
from tests.utils import TEST_DATA


def test_field_from_netcdf_variables():
filename = str(TEST_DATA / "perlinfieldsU.nc")
dims = {"lon": "x", "lat": "y"}

variable = "vozocrtx"
f1 = Field.from_netcdf(filename, variable, dims)
variable = ("U", "vozocrtx")
f2 = Field.from_netcdf(filename, variable, dims)
variable = {"U": "vozocrtx"}
f3 = Field.from_netcdf(filename, variable, dims)

assert np.allclose(f1.data, f2.data, atol=1e-12)
assert np.allclose(f1.data, f3.data, atol=1e-12)

with pytest.raises(AssertionError):
variable = {"U": "vozocrtx", "nav_lat": "nav_lat"} # multiple variables will fail
f3 = Field.from_netcdf(filename, variable, dims)


@pytest.mark.parametrize("with_timestamps", [True, False])
def test_field_from_netcdf(with_timestamps):
filenames = {
"lon": str(TEST_DATA / "mask_nemo_cross_180lon.nc"),
"lat": str(TEST_DATA / "mask_nemo_cross_180lon.nc"),
"data": str(TEST_DATA / "Uu_eastward_nemo_cross_180lon.nc"),
}
variable = "U"
dimensions = {"lon": "glamf", "lat": "gphif"}
if with_timestamps:
timestamp_types = [[[2]], [[np.datetime64("2000-01-01")]]]
for timestamps in timestamp_types:
Field.from_netcdf(filenames, variable, dimensions, interp_method="cgrid_velocity", timestamps=timestamps)
else:
Field.from_netcdf(filenames, variable, dimensions, interp_method="cgrid_velocity")


@pytest.mark.parametrize(
"calendar, cftime_datetime", zip(_get_cftime_calendars(), _get_cftime_datetimes(), strict=True)
)
def test_field_nonstandardtime(calendar, cftime_datetime, tmpdir):
xdim = 4
ydim = 6
filepath = tmpdir.join("test_nonstandardtime.nc")
dates = [getattr(cftime, cftime_datetime)(1, m, 1) for m in range(1, 13)]
da = xr.DataArray(
np.random.rand(12, xdim, ydim), coords=[dates, range(xdim), range(ydim)], dims=["time", "lon", "lat"], name="U"
)
da.to_netcdf(str(filepath))

dims = {"lon": "lon", "lat": "lat", "time": "time"}
try:
field = Field.from_netcdf(filepath, "U", dims)
except NotImplementedError:
field = None

if field is not None:
assert field.grid.time_origin.calendar == calendar
63 changes: 1 addition & 62 deletions tests/test_fieldset.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import sys
from datetime import timedelta

import cftime
import dask
import dask.array as da
import numpy as np
Expand All @@ -29,8 +28,6 @@
GeographicPolar,
TimeConverter,
UnitConverter,
_get_cftime_calendars,
_get_cftime_datetimes,
)
from tests.common_kernels import DoNothing
from tests.utils import TEST_DATA
Expand Down Expand Up @@ -61,6 +58,7 @@ def test_fieldset_from_data(xdim, ydim):
"""Simple test for fieldset initialisation from data."""
data, dimensions = generate_fieldset_data(xdim, ydim)
fieldset = FieldSet.from_data(data, dimensions)
assert fieldset.U._creation_log == "from_data"
assert len(fieldset.U.data.shape) == 3
assert len(fieldset.V.data.shape) == 3
assert np.allclose(fieldset.U.data[0, :], data["U"], rtol=1e-12)
Expand Down Expand Up @@ -139,65 +137,6 @@ def test_fieldset_from_parcels(xdim, ydim, tmpdir):
assert np.allclose(fieldset.V.data[0, :], data["V"], rtol=1e-12)


def test_field_from_netcdf_variables():
filename = str(TEST_DATA / "perlinfieldsU.nc")
dims = {"lon": "x", "lat": "y"}

variable = "vozocrtx"
f1 = Field.from_netcdf(filename, variable, dims)
variable = ("U", "vozocrtx")
f2 = Field.from_netcdf(filename, variable, dims)
variable = {"U": "vozocrtx"}
f3 = Field.from_netcdf(filename, variable, dims)

assert np.allclose(f1.data, f2.data, atol=1e-12)
assert np.allclose(f1.data, f3.data, atol=1e-12)

with pytest.raises(AssertionError):
variable = {"U": "vozocrtx", "nav_lat": "nav_lat"} # multiple variables will fail
f3 = Field.from_netcdf(filename, variable, dims)


@pytest.mark.parametrize(
"calendar, cftime_datetime", zip(_get_cftime_calendars(), _get_cftime_datetimes(), strict=True)
)
def test_fieldset_nonstandardtime(
calendar, cftime_datetime, tmpdir, filename="test_nonstandardtime.nc", xdim=4, ydim=6
):
filepath = tmpdir.join(filename)
dates = [getattr(cftime, cftime_datetime)(1, m, 1) for m in range(1, 13)]
da = xr.DataArray(
np.random.rand(12, xdim, ydim), coords=[dates, range(xdim), range(ydim)], dims=["time", "lon", "lat"], name="U"
)
da.to_netcdf(str(filepath))

dims = {"lon": "lon", "lat": "lat", "time": "time"}
try:
field = Field.from_netcdf(filepath, "U", dims)
except NotImplementedError:
field = None

if field is not None:
assert field.grid.time_origin.calendar == calendar


@pytest.mark.parametrize("with_timestamps", [True, False])
def test_field_from_netcdf(with_timestamps):
filenames = {
"lon": str(TEST_DATA / "mask_nemo_cross_180lon.nc"),
"lat": str(TEST_DATA / "mask_nemo_cross_180lon.nc"),
"data": str(TEST_DATA / "Uu_eastward_nemo_cross_180lon.nc"),
}
variable = "U"
dimensions = {"lon": "glamf", "lat": "gphif"}
if with_timestamps:
timestamp_types = [[[2]], [[np.datetime64("2000-01-01")]]]
for timestamps in timestamp_types:
Field.from_netcdf(filenames, variable, dimensions, interp_method="cgrid_velocity", timestamps=timestamps)
else:
Field.from_netcdf(filenames, variable, dimensions, interp_method="cgrid_velocity")


def test_fieldset_from_modulefile():
nemo_fname = str(TEST_DATA / "fieldset_nemo.py")
nemo_error_fname = str(TEST_DATA / "fieldset_nemo_error.py")
Expand Down

0 comments on commit 02eb9a7

Please sign in to comment.