Skip to content

Commit

Permalink
Raise if no nearest site is found, ensure unique does not change orde…
Browse files Browse the repository at this point in the history
…r of sites, add some tests
  • Loading branch information
rafa-guedes committed Dec 5, 2023
1 parent 18cd912 commit ed6fd75
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 8 deletions.
34 changes: 34 additions & 0 deletions tests/core/test_sel.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,40 @@ def test_dset_sel_nearest_unique(self):
)
assert dset[attrs.SITENAME].size == len(self.lons_exact)

def test_dset_sel_nearest_dont_tolerate_missing(self):
"""Assert missing values raise by default."""
with pytest.raises(AssertionError):
dset = self.dset.spec.sel(
lons=self.lons,
lats=self.lats,
method="nearest",
unique=True,
tolerance=0.01,
)

def test_dset_sel_nearest_tolerate_missing(self):
"""Assert missing values are ignored if specified."""
dset = self.dset.spec.sel(
lons=self.lons,
lats=self.lats,
method="nearest",
unique=True,
tolerance=0.01,
missing="ignore",
)

def test_dset_sel_nearest_at_least_one(self):
"""Assert some site needs to be found even if missing=ignore."""
with pytest.raises(ValueError):
dset = self.dset.spec.sel(
lons=np.array(self.lons)+10,
lats=self.lats,
method="nearest",
unique=True,
tolerance=0.01,
missing="ignore",
)

def test_dset_sel_none(self):
"""Assert that sel/none method runs."""
dset = self.dset.spec.sel(
Expand Down
24 changes: 16 additions & 8 deletions wavespectra/core/select.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,24 +176,32 @@ def sel_nearest(
if closest_dist > tolerance:
if missing == "raise":
raise AssertionError(
f"Nearest site from (lat={lat}, lon={lon}) is {closest_dist:g} "
f"deg away but tolerance is {tolerance:g} deg."
f"Nearest site in dataset from ({lon, lat}) is {closest_dist:g} "
f"deg away but tolerance is {tolerance:g} deg"
)
elif missing == "ignore":
logger.debug(
f"No site within tolerance={tolerance} deg from (lat={lat}, "
f"lon={lon}), skipping"
f"No site in dataset within tolerance={tolerance} deg "
f"from requested location ({lon, lat}), skipping"
)
continue
if exact and closest_dist > 0:
raise AssertionError(
f"Exact match required but no site at (lat={lat}, lon={lon}), "
f"Exact match required but no site in dataset at ({lon, lat}), "
f"nearest site is {closest_dist} deg away."
)
if unique and closest_id in station_ids:
logger.debug(
f"Nearest site at ({lon, lat}) is repeated, skipping "
f"because unique=True"
)
continue
station_ids.append(closest_id)
if unique:
station_ids = list(set(station_ids))

if not station_ids:
raise ValueError(
f"No site in dataset found within tolerance={tolerance} deg of any site "
f"{list(zip(coords.lons, coords.lats))}"
)
dsout = dset.isel(**{attrs.SITENAME: station_ids})

# Return longitudes in the convention provided
Expand Down

0 comments on commit ed6fd75

Please sign in to comment.