Describe the bug
_extract_grid_from_like() in xrspatial/rasterize.py (around line 1948) takes px/py from the first coordinate interval of like and then treats the grid as regular. Around line 2283, the output DataArray reuses like.coords verbatim. The rasterizer only works on a uniform grid.
If like has non-uniform x or y spacing, rasterize(..., like=...) returns a DataArray whose coords (copied from the irregular like) no longer line up with the uniform grid the pixels were written to. The output silently mislabels where each cell lives.
Reproduce
import numpy as np
import xarray as xr
from shapely.geometry import box
from xrspatial.rasterize import rasterize
x = np.array([0.0, 1.0, 2.5, 3.5]) # non-uniform
y = np.array([3.0, 2.0, 1.0, 0.0])
like = xr.DataArray(np.zeros((4, 4)), dims=('y','x'), coords={'y': y, 'x': x})
out = rasterize([(box(0, 0, 3.5, 3.0), 1.0)], like=like)
# out.x is [0, 1, 2.5, 3.5] but the data sits on a uniform grid.
Expected behavior
Two options:
(a) Detect irregular grids in _extract_grid_from_like() and raise ValueError, naming the offending axis and the largest deviation. This is what rasterio does and is the safer default.
(b) Regularize the like grid before rasterizing and document the coercion.
Prefer (a).
Implementation notes
- Check the full coord vector is uniformly spaced within a numeric tolerance. Use
numpy.allclose on the diffs, not strict equality. Affine-derived coords drift.
- Name the axis (x or y) and report the largest deviation in the error message.
- A sibling issue covers ascending-y
like. Order the uniform-spacing check so it does not interfere with the ascending-y work in that other PR.
- The helper sits on the numpy path, but dask, cupy, and dask+cupy all call into it, so one fix covers every backend.
Tests
- Non-uniform x:
ValueError raised, axis named.
- Non-uniform y: same.
- Uniformly spaced like: existing happy path unchanged.
Describe the bug
_extract_grid_from_like()inxrspatial/rasterize.py(around line 1948) takespx/pyfrom the first coordinate interval oflikeand then treats the grid as regular. Around line 2283, the output DataArray reuseslike.coordsverbatim. The rasterizer only works on a uniform grid.If
likehas non-uniform x or y spacing,rasterize(..., like=...)returns a DataArray whose coords (copied from the irregularlike) no longer line up with the uniform grid the pixels were written to. The output silently mislabels where each cell lives.Reproduce
Expected behavior
Two options:
(a) Detect irregular grids in
_extract_grid_from_like()and raiseValueError, naming the offending axis and the largest deviation. This is what rasterio does and is the safer default.(b) Regularize the like grid before rasterizing and document the coercion.
Prefer (a).
Implementation notes
numpy.allcloseon the diffs, not strict equality. Affine-derived coords drift.like. Order the uniform-spacing check so it does not interfere with the ascending-y work in that other PR.Tests
ValueErrorraised, axis named.