Skip to content

Commit

Permalink
Raise an error for zero increment grid (GenericMappingTools#1484)
Browse files Browse the repository at this point in the history
Raise GMTInvalidInput error when xarray.DataArray
grid input has zero increment coordinates to prevent
segmentation fault in the PyGMT clib API.

Co-authored-by: Dongdong Tian <[email protected]>
Co-authored-by: Wei Ji <[email protected]>
  • Loading branch information
3 people authored and Josh Sixsmith committed Dec 21, 2022
1 parent b4a4eb8 commit 09a07ef
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 4 deletions.
10 changes: 6 additions & 4 deletions pygmt/clib/conversion.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ def dataarray_to_matrix(grid):
"""
if len(grid.dims) != 2:
raise GMTInvalidInput(
"Invalid number of grid dimensions '{}'. Must be 2.".format(len(grid.dims))
f"Invalid number of grid dimensions '{len(grid.dims)}'. Must be 2."
)
# Extract region and inc from the grid
region = []
Expand All @@ -96,9 +96,11 @@ def dataarray_to_matrix(grid):
coord_inc = coord_incs[0]
if not np.allclose(coord_incs, coord_inc):
raise GMTInvalidInput(
"Grid appears to have irregular spacing in the '{}' dimension.".format(
dim
)
f"Grid appears to have irregular spacing in the '{dim}' dimension."
)
if coord_inc == 0:
raise GMTInvalidInput(
f"Grid has a zero increment in the '{dim}' dimension."
)
region.extend(
[
Expand Down
18 changes: 18 additions & 0 deletions pygmt/tests/test_clib.py
Original file line number Diff line number Diff line change
Expand Up @@ -743,6 +743,24 @@ def test_dataarray_to_matrix_inc_fails():
dataarray_to_matrix(grid)


def test_dataarray_to_matrix_zero_inc_fails():
"""
Check that dataarray_to_matrix fails for zero increments grid.
"""
data = np.ones((5, 5), dtype="float32")
x = np.linspace(0, 1, 5)
y = np.zeros_like(x)
grid = xr.DataArray(data, coords=[("y", y), ("x", x)])
with pytest.raises(GMTInvalidInput):
dataarray_to_matrix(grid)

y = np.linspace(0, 1, 5)
x = np.zeros_like(x)
grid = xr.DataArray(data, coords=[("y", y), ("x", x)])
with pytest.raises(GMTInvalidInput):
dataarray_to_matrix(grid)


def test_get_default():
"""
Make sure get_default works without crashing and gives reasonable results.
Expand Down

0 comments on commit 09a07ef

Please sign in to comment.