Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions xrspatial/convolution.py
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,12 @@ def custom_kernel(kernel):
"The kernel received was of type {} and needs to be "
"of type `ndarray`".format(type(kernel))
)
elif kernel.ndim != 2:
raise ValueError(
"Received a custom kernel that is not a 2D array.",
"A custom kernel needs to be a 2D array, the supplied kernel "
"has shape {}.".format(kernel.shape)
)
else:
rows, cols = kernel.shape

Expand Down
14 changes: 13 additions & 1 deletion xrspatial/tests/test_convolution.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import pytest
import xarray as xr

from xrspatial.convolution import circle_kernel, convolve_2d
from xrspatial.convolution import circle_kernel, convolve_2d, custom_kernel


KERNEL = circle_kernel(1, 1, 1)
Expand All @@ -28,6 +28,18 @@ def test_convolve_2d_rejects_wrong_ndim():
convolve_2d(np.zeros(10, dtype=np.float64), KERNEL)


@pytest.mark.parametrize("bad_kernel", [
np.ones(3, dtype=np.float32), # 1D
np.ones((3, 3, 3), dtype=np.float32), # 3D
])
def test_custom_kernel_rejects_non_2d(bad_kernel):
# Regression for #2842: custom_kernel must raise a clear error for a
# non-2D kernel instead of leaking "not enough values to unpack" from
# the `rows, cols = kernel.shape` line.
with pytest.raises(ValueError, match="not a 2D array"):
custom_kernel(bad_kernel)


def test_convolve_2d_accepts_float64():
# Positive path: a float64 raster still works end-to-end.
data = np.arange(25, dtype=np.float64).reshape(5, 5)
Expand Down
18 changes: 18 additions & 0 deletions xrspatial/tests/test_focal.py
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,24 @@ def test_apply_small_kernel_not_rejected_1284():
assert out.shape == (50, 50)


@pytest.mark.parametrize("entry_point", [
lambda agg, kernel: apply(agg, kernel),
lambda agg, kernel: focal_stats(agg, kernel, stats_funcs=['mean']),
lambda agg, kernel: hotspots(agg, kernel),
])
@pytest.mark.parametrize("bad_kernel", [
np.ones(3, dtype=np.float32), # 1D
np.ones((3, 3, 3), dtype=np.float32), # 3D
])
def test_entry_points_reject_non_2d_kernel_2842(entry_point, bad_kernel):
# Regression for #2842: a non-2D kernel must raise a clear, descriptive
# error rather than the raw "not enough values to unpack" ValueError
# leaking out of custom_kernel's `rows, cols = kernel.shape`.
raster = xr.DataArray(np.ones((10, 10), dtype=np.float32))
with pytest.raises(ValueError, match="not a 2D array"):
entry_point(raster, bad_kernel)


def test_convolution_numpy(
convolve_2d_data,
convolution_custom_kernel,
Expand Down
Loading