You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@sedona.apache.org by ji...@apache.org on 2026/10/01 06:37:58 UTC
(sedona) branch master updated: [GH-3425] Align rasterization boundary handling with GDAL's half-open cells (#3428)
This is an automated email from the ASF dual-hosted git repository.
jiayuasu pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/sedona.git
The following commit(s) were added to refs/heads/master by this push:
new 2d5bc1ecb30 [GH-3425] Align rasterization boundary handling with GDAL's half-open cells (#3428)
2d5bc1ecb30 is described below
commit 2d5bc1ecb30ab3e5047f2c60e14398af88bf9036
Author: Jia Yu <ji...@apache.org>
AuthorDate: Wed Sep 30 23:37:51 2026 -0700
[GH-3425] Align rasterization boundary handling with GDAL's half-open cells (#3428)
---
.../sedona/common/raster/PixelFunctionEditors.java | 7 +-
.../sedona/common/raster/RasterBandEditors.java | 17 +
.../sedona/common/raster/RasterConstructors.java | 8 +-
.../apache/sedona/common/raster/Rasterization.java | 377 +++++++++++++++------
.../sedona/common/raster/FunctionEditorsTest.java | 20 +-
.../common/raster/RasterConstructorsTest.java | 66 ++--
.../sedona/common/raster/RasterizationTest.java | 364 ++++++++++++++++++--
.../api/sql/Raster-Band-Accessors/RS_ZonalStats.md | 2 +-
.../sql/Raster-Band-Accessors/RS_ZonalStatsAll.md | 2 +-
docs/api/sql/Raster-Operators/RS_AsRaster.md | 4 +-
docs/api/sql/Raster-Operators/RS_Clip.md | 2 +-
docs/api/sql/Raster-Operators/RS_SetValues.md | 2 +-
python/tests/sql/test_rasterize_parity.py | 72 ++++
.../org/apache/sedona/sql/rasteralgebraTest.scala | 21 +-
14 files changed, 783 insertions(+), 181 deletions(-)
diff --git a/common/src/main/java/org/apache/sedona/common/raster/PixelFunctionEditors.java b/common/src/main/java/org/apache/sedona/common/raster/PixelFunctionEditors.java
index 4d17e601c50..604455c4cbf 100644
--- a/common/src/main/java/org/apache/sedona/common/raster/PixelFunctionEditors.java
+++ b/common/src/main/java/org/apache/sedona/common/raster/PixelFunctionEditors.java
@@ -160,6 +160,12 @@ public class PixelFunctionEditors {
// the background with it.
rasterizedGeom =
RasterConstructors.asRaster(geom, raster, bandDataType, allTouched, value, null);
+ WritableRaster rasterCopied = makeCopiedRaster(raster);
+ if (rasterizedGeom == null) {
+ // The geometry only touches the raster's boundary and burns none of its pixels, so nothing
+ // changes.
+ return RasterUtils.clone(rasterCopied, raster.getSampleDimensions(), raster, null, true);
+ }
Raster rasterizedGeomData = RasterUtils.getRaster(rasterizedGeom.getRenderedImage());
double colX = RasterAccessors.getUpperLeftX(rasterizedGeom),
@@ -168,7 +174,6 @@ public class PixelFunctionEditors {
widthGeometryRaster = RasterAccessors.getWidth(rasterizedGeom);
int heightOriginalRaster = RasterAccessors.getHeight(raster),
widthOriginalRaster = RasterAccessors.getWidth(raster);
- WritableRaster rasterCopied = makeCopiedRaster(raster);
// Converting geometry to raster and then iterating through them
int[] pixelLocation = RasterUtils.getGridCoordinatesFromWorld(raster, colX, rowY);
diff --git a/common/src/main/java/org/apache/sedona/common/raster/RasterBandEditors.java b/common/src/main/java/org/apache/sedona/common/raster/RasterBandEditors.java
index 634fbf190e9..f1d6ccae8b3 100644
--- a/common/src/main/java/org/apache/sedona/common/raster/RasterBandEditors.java
+++ b/common/src/main/java/org/apache/sedona/common/raster/RasterBandEditors.java
@@ -375,6 +375,23 @@ public class RasterBandEditors {
// mask logic would then misread as covered pixels.
GridCoverage2D maskRaster =
RasterConstructors.asRaster(geometry, raster, bandType, allTouched, 150, null);
+ if (maskRaster == null) {
+ // The geometry only touches the raster's boundary and burns none of its pixels, so every
+ // pixel is outside it: the clipped raster is all nodata, and there is nothing to crop it to.
+ if (crop) {
+ if (lenient) {
+ return null;
+ }
+ throw new IllegalArgumentException("Geometry does not cover any pixel of the raster.");
+ }
+ return RasterUtils.clone(
+ writableRaster,
+ raster.getGridGeometry(),
+ new GridSampleDimension[] {raster.getSampleDimension(band - 1)},
+ raster,
+ noDataValue,
+ true);
+ }
Raster maskData = RasterUtils.getRaster(maskRaster.getRenderedImage());
double[] maskMetadata = RasterAccessors.metadata(maskRaster);
int maskWidth = (int) maskMetadata[2], maskHeight = (int) maskMetadata[3];
diff --git a/common/src/main/java/org/apache/sedona/common/raster/RasterConstructors.java b/common/src/main/java/org/apache/sedona/common/raster/RasterConstructors.java
index 5f64822e4b1..9d19ce4d6e2 100644
--- a/common/src/main/java/org/apache/sedona/common/raster/RasterConstructors.java
+++ b/common/src/main/java/org/apache/sedona/common/raster/RasterConstructors.java
@@ -118,7 +118,10 @@ public class RasterConstructors {
* are set to this value
* @param useGeometryExtent The way to generate extent of the resultant raster. Use the extent of
* the geometry to convert if true, else use the extent of the reference raster
- * @return Rasterized Geometry
+ * @return Rasterized Geometry, or null when useGeometryExtent is true and the geometry neither
+ * burns nor overlaps any pixel of the reference raster (for example a polygon that only
+ * touches its boundary, or a line along its right or bottom edge), so there is nothing to
+ * crop to
* @throws FactoryException
*/
public static GridCoverage2D asRaster(
@@ -161,6 +164,9 @@ public class RasterConstructors {
List<Object> objects =
Rasterization.rasterize(
geom, raster, pixelType, value, useGeometryExtent, allTouched, noDataValue);
+ if (objects == null) {
+ return null;
+ }
WritableRaster writableRaster = (WritableRaster) objects.get(0);
GridCoverage2D rasterized = (GridCoverage2D) objects.get(1);
diff --git a/common/src/main/java/org/apache/sedona/common/raster/Rasterization.java b/common/src/main/java/org/apache/sedona/common/raster/Rasterization.java
index 449caadbfa7..7512a0097d7 100644
--- a/common/src/main/java/org/apache/sedona/common/raster/Rasterization.java
+++ b/common/src/main/java/org/apache/sedona/common/raster/Rasterization.java
@@ -35,9 +35,9 @@ import org.geotools.coverage.grid.GridCoverageFactory;
import org.geotools.geometry.jts.JTS;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.locationtech.jts.algorithm.CGAlgorithmsDD;
+import org.locationtech.jts.algorithm.Orientation;
import org.locationtech.jts.geom.*;
-import org.locationtech.jts.geom.prep.PreparedGeometry;
-import org.locationtech.jts.geom.prep.PreparedGeometryFactory;
+import org.locationtech.jts.geom.util.PolygonExtracter;
public class Rasterization {
protected static List<Object> rasterize(
@@ -72,6 +72,12 @@ public class Rasterization {
ReferencedEnvelope rasterExtent = raster.getEnvelope2D();
ReferencedEnvelope geomExtent = rasterizeGeomExtent(geom, raster, metadata, allTouched);
+ if (geomExtent == null && useGeometryExtent) {
+ // The geometry's window holds no cell of the raster, for example a point on the raster's
+ // right or bottom edge or a polygon that only touches one of its edges, so there is no
+ // extent to crop the output to.
+ return null;
+ }
RasterizationParams params =
calculateRasterizationParams(raster, useGeometryExtent, metadata, geomExtent, pixelType);
@@ -80,6 +86,15 @@ public class Rasterization {
rasterizeGeometry(raster, metadata, geom, params, geomExtent, value, allTouched);
+ if (useGeometryExtent && !params.anyBurned && !overlapsRasterArea(geom, rasterExtent)) {
+ // The window can hold cells that the geometry only touches, for example the corner cell of a
+ // polygon meeting the raster at that corner, or the edge column of a line along the
+ // raster's right edge. Under GDAL's half-open rule it burns none of them and it overlaps no
+ // pixel's area, so there is nothing to crop the output to either. A polygon that overlaps a
+ // pixel without covering its centre keeps its cropped, unburned output.
+ return null;
+ }
+
// Create a GridCoverage2D for the rasterized result
GridCoverageFactory coverageFactory = new GridCoverageFactory();
GridCoverage2D rasterized;
@@ -149,7 +164,7 @@ public class Rasterization {
rasterizeGeometryCollection(raster, metadata, geom, params, value, allTouched);
break;
case "Point":
- rasterizePoint(geom, params, geomExtent, value);
+ rasterizePoint(geom, metadata, params, value);
break;
case "LineString":
case "MultiLineString":
@@ -182,70 +197,76 @@ public class Rasterization {
return Math.max(0, Math.min(index, size - 1));
}
+ /**
+ * Burns the single cell that contains the point under GDAL's half-open rule, whatever allTouched
+ * is: a point on a grid line or a grid corner burns exactly one cell, and a point on the raster's
+ * far edge burns none. See {@link #halfOpenCell}.
+ */
private static void rasterizePoint(
- Geometry geom, RasterizationParams params, ReferencedEnvelope geomExtent, double value) {
-
- // Traverse by integer grid index and derive each cell envelope from that index, rather than
- // walking world coordinates by repeatedly adding scaleX/scaleY. Accumulation drifts when the
- // pixel size has no exact double representation (e.g. 1/3600 degree for a 30m DEM): the running
- // coordinate can fall a fraction of an ULP short of the extent maximum and take a whole extra
- // step, and the separately incremented index it carries stops matching the cell being tested.
- int width = params.writableRaster.getWidth();
- int height = params.writableRaster.getHeight();
-
- // An extent narrower than a pixel - which clipping leaves behind where a polygon only grazes
- // the raster edge - can round to an empty range. Keep the single cell it falls in, so the
- // caller still gets the "any touch" pixel rather than silently nothing.
- int startCol =
- clampToGrid(
- (int) Math.round((geomExtent.getMinX() - params.upperLeftX) / params.scaleX), width);
- int endCol =
- Math.max(
- startCol,
- clampToGrid(
- (int) Math.round((geomExtent.getMaxX() - params.upperLeftX) / params.scaleX) - 1,
- width));
- int startRow =
- clampToGrid(
- (int) Math.round((geomExtent.getMaxY() - params.upperLeftY) / params.scaleY), height);
- int endRow =
- Math.max(
- startRow,
- clampToGrid(
- (int) Math.round((geomExtent.getMinY() - params.upperLeftY) / params.scaleY) - 1,
- height));
+ Geometry geom, double[] metadata, RasterizationParams params, double value) {
+ if (geom.isEmpty()) {
+ return;
+ }
+ int[] cell = halfOpenCell(geom.getCoordinate(), metadata);
+ if (cell == null) {
+ return;
+ }
// Where the output grid sits within the reference raster's grid: zero unless the output was
- // cropped to the geometry extent. Cell envelopes are built on the reference grid and only the
- // write index is crop-local, so a cropped output resolves boundary contacts identically to a
- // full-extent one.
+ // cropped to the geometry extent. The cell is resolved on the reference grid and only the
+ // write index is crop-local, so a cropped output burns the same cell as a full-extent one.
int colOffset = (int) Math.round((params.upperLeftX - params.rasterUpperLeftX) / params.scaleX);
int rowOffset = (int) Math.round((params.upperLeftY - params.rasterUpperLeftY) / params.scaleY);
+ int col = cell[0] - colOffset;
+ int row = cell[1] - rowOffset;
- PreparedGeometry preparedGeom = PreparedGeometryFactory.prepare(geom);
- for (int row = startRow; row <= endRow; row++) {
- // scaleY is always negative here, so row counts downwards from the geographic top
- double cellMaxY = params.rasterUpperLeftY + (row + rowOffset) * params.scaleY;
- double cellMinY = params.rasterUpperLeftY + (row + rowOffset + 1) * params.scaleY;
-
- // Adjust for bottom-up rasters
- // Reverse the y index
- int yIndex = params.bottomUp ? height - 1 - row : row;
-
- for (int col = startCol; col <= endCol; col++) {
- // Create envelope for this pixel
- double cellMinX = params.rasterUpperLeftX + (col + colOffset) * params.scaleX;
- double cellMaxX = params.rasterUpperLeftX + (col + colOffset + 1) * params.scaleX;
+ int width = params.writableRaster.getWidth();
+ int height = params.writableRaster.getHeight();
+ if (col < 0 || col >= width || row < 0 || row >= height) {
+ return;
+ }
+ // Rows count down from the geographic top here; reverse them for bottom-up rasters.
+ int yIndex = params.bottomUp ? height - 1 - row : row;
+ params.burn(col, yIndex, value);
+ }
- boolean intersects =
- preparedGeom.intersects(
- JTS.toGeometry(new Envelope(cellMinX, cellMaxX, cellMinY, cellMaxY)));
+ /**
+ * Returns the cell {col, row} containing the coordinate under GDAL's half-open rule, with the row
+ * counted down from the raster's geographic top, or null when the coordinate is off the raster.
+ *
+ * <p>A cell contains its first edge in pixel order but not its last, so a coordinate on a grid
+ * line belongs to the cell after the line, and one on the raster's right or bottom edge (in pixel
+ * order) belongs to no cell. The index is computed in the raster's own pixel order, so on a
+ * bottom-up raster a point on a horizontal grid line falls in the cell above it, as in GDAL.
+ */
+ private static int[] halfOpenCell(Coordinate coord, double[] metadata) {
+ int width = (int) metadata[2];
+ int height = (int) metadata[3];
+ int col = floorPixelIndex(coord.x, metadata[0], metadata[4]);
+ int row = floorPixelIndex(coord.y, metadata[1], metadata[5]);
+ if (col < 0 || col >= width || row < 0 || row >= height) {
+ return null;
+ }
+ return new int[] {col, metadata[5] > 0 ? height - 1 - row : row};
+ }
- if (intersects) {
- params.writableRaster.setSample(col, yIndex, 0, value);
- }
- }
+ /**
+ * Computes floor((coord - upperLeft) / scale) exactly, on the same decimal values that {@link
+ * #toPixelIndex} snaps extents with, so a coordinate on a grid line is not pushed across it by
+ * floating-point error. Saturates at the int range for coordinates far off the raster.
+ */
+ private static int floorPixelIndex(double coord, double upperLeft, double scale) {
+ BigDecimal index =
+ BigDecimal.valueOf(coord)
+ .subtract(BigDecimal.valueOf(upperLeft))
+ .divide(BigDecimal.valueOf(scale), 0, RoundingMode.FLOOR);
+ if (index.compareTo(BigDecimal.valueOf(Integer.MAX_VALUE)) > 0) {
+ return Integer.MAX_VALUE;
}
+ if (index.compareTo(BigDecimal.valueOf(Integer.MIN_VALUE)) < 0) {
+ return Integer.MIN_VALUE;
+ }
+ return index.intValue();
}
private static void rasterizeLineString(
@@ -290,6 +311,25 @@ public class Rasterization {
*/
private static void traverseSegment(
RasterizationParams params, double x0, double y0, double x1, double y1, double value) {
+ traverseSegment(params, x0, y0, x1, y1, value, false, false);
+ }
+
+ /**
+ * As {@link #traverseSegment(RasterizationParams, double, double, double, double, double)}, for a
+ * segment that may lie exactly on a grid line. A segment with no extent along an axis whose pixel
+ * coordinate is integral runs between two rows (or columns) of cells; by default it burns the
+ * half-open one after the line, and {@code flatTowardsNegativeX} / {@code flatTowardsNegativeY}
+ * select the one before it instead.
+ */
+ private static void traverseSegment(
+ RasterizationParams params,
+ double x0,
+ double y0,
+ double x1,
+ double y1,
+ double value,
+ boolean flatTowardsNegativeX,
+ boolean flatTowardsNegativeY) {
int width = params.writableRaster.getWidth();
int height = params.writableRaster.getHeight();
@@ -300,10 +340,12 @@ public class Rasterization {
int stepX = (int) Math.signum(dx);
int stepY = (int) Math.signum(dy);
- int x = interiorCell(x0, dx < 0);
- int y = interiorCell(y0, dy < 0);
- int endX = interiorCell(x1, dx > 0);
- int endY = interiorCell(y1, dy > 0);
+ boolean flatX = dx == 0 && flatTowardsNegativeX;
+ boolean flatY = dy == 0 && flatTowardsNegativeY;
+ int x = interiorCell(x0, dx < 0 || flatX);
+ int y = interiorCell(y0, dy < 0 || flatY);
+ int endX = interiorCell(x1, dx > 0 || flatX);
+ int endY = interiorCell(y1, dy > 0 || flatY);
// The endpoints are clipped to the geometry extent, so the walk covers at most the grid's
// width + height cells; the bound also guards against a floating-point overshoot never reaching
@@ -363,7 +405,7 @@ public class Rasterization {
// Reverse the y index for bottom-up rasters
int rasterY = params.bottomUp ? height - 1 - y : y;
if (x >= 0 && x < width && rasterY >= 0 && rasterY < height) {
- params.writableRaster.setSample(x, rasterY, 0, value);
+ params.burn(x, rasterY, value);
}
}
@@ -445,24 +487,27 @@ public class Rasterization {
validateRasterMetadata(metadata);
- // Always enable allTouched for MultiLineString and MultiPoint.
- //
- // Rationale:
- // - Points and lines cannot be rasterized using "pixel-center inside geometry" logic
- // because they have no area. For these geometry types, we must use "any touch"
- // semantics to mark pixels they intersect/touch.
- // - Single Point/LineString cases are already safeguarded by the zero-envelope
- // expansion logic at lines 367:373 (ensuring a non-degenerate search window).
- // - For Polygons, whether we expand the snapped extent depends on the caller’s
- // allTouched setting (center-based vs any-intersection semantics).
- //
- // Enabling allTouched here guarantees correct handling for multi-part point/line
- // geometries whose parts may sit exactly on pixel boundaries.
- if (Objects.equals(geom.getGeometryType(), "MultiLineString")) {
- allTouched = true;
+ // A point burns exactly the half-open cell it lies in, so its extent is that cell.
+ if (geom instanceof Puntal) {
+ return pointCellsExtent(geom, raster, metadata);
}
- if (Objects.equals(geom.getGeometryType(), "MultiPoint")) {
- allTouched = true;
+ // A mixed collection's window is the union of its members' windows, so each member keeps the
+ // cells it burns.
+ if (geom.getClass() == GeometryCollection.class) {
+ ReferencedEnvelope union = null;
+ for (int i = 0; i < geom.getNumGeometries(); i++) {
+ ReferencedEnvelope member =
+ rasterizeGeomExtent(geom.getGeometryN(i), raster, metadata, allTouched);
+ if (member == null) {
+ continue;
+ }
+ if (union == null) {
+ union = new ReferencedEnvelope(member);
+ } else {
+ union.expandToInclude(member);
+ }
+ }
+ return union;
}
ReferencedEnvelope geomExtent =
@@ -489,7 +534,7 @@ public class Rasterization {
toPixelIndex(geomExtent.getMaxY(), scaleY, upperLeftY, false), scaleY, upperLeftY);
// Ensure the snapped AOI window is at least one pixel wide/tall.
- // After snapping the continuous bbox to pixel edges, a point or thin line can
+ // After snapping the continuous bbox to pixel edges, a thin line can
// collapse to min == max along an axis (i.e., a degenerate 0-width/0-height window).
// That would produce an empty search region and skip rasterization entirely.
//
@@ -521,21 +566,15 @@ public class Rasterization {
return null;
}
- // Handle "allTouched" behavior when geometry edges line up exactly with pixel boundaries.
- //
- // Normally, each pixel is considered only if its *center* falls inside the geometry.
- // But if an edge of the geometry sits exactly on a pixel boundary, the geometry
- // might "touch" neighboring pixels without covering their centers — and those pixels
- // would be skipped.
- //
- // When allTouched = true, we expand the aligned bounding box outward by one pixel
- // on any side where the geometry’s edge exactly matches a pixel boundary.
- // This guarantees we include those neighboring pixels that the geometry merely touches.
+ // Widen the window of a line by one pixel on any side that lies exactly on a grid line (always
+ // for a MultiLineString, and with allTouched for a LineString).
//
- // We only expand sides that line up perfectly with grid lines (equal coordinates).
- // The scaleX / scaleY values (which already encode pixel size and direction) ensure
- // this expansion moves exactly one pixel outward in each direction.
- if (allTouched) {
+ // This only sizes the search window and the cropped output; which cells a line burns is decided
+ // by traverseSegment under GDAL's half-open rule. A line lying on a grid line burns the cells
+ // after it, which sit outside the snapped window when the line is the window's right or bottom
+ // edge. A polygon or point never burns a cell it touches only on its boundary, as in GDAL, so
+ // its window is not widened.
+ if (geom instanceof Lineal && (allTouched || geom instanceof MultiLineString)) {
alignedMinX -= (geomExtent.getMinX() == alignedMinX) ? scaleX : 0;
alignedMinY += (geomExtent.getMinY() == alignedMinY) ? scaleY : 0;
alignedMaxX += (geomExtent.getMaxX() == alignedMaxX) ? scaleX : 0;
@@ -560,6 +599,35 @@ public class Rasterization {
return alignedRasterExtent;
}
+ /**
+ * The extent of the half-open cells the points fall in, or null when none of them lies on the
+ * raster. See {@link #halfOpenCell}.
+ */
+ private static ReferencedEnvelope pointCellsExtent(
+ Geometry geom, GridCoverage2D raster, double[] metadata) {
+ double upperLeftX = metadata[0];
+ double upperLeftY = getRasterUpperLeftY(metadata);
+ double scaleX = metadata[4];
+ double scaleY = getRasterScaleY(metadata);
+
+ Envelope cells = new Envelope();
+ for (Coordinate coord : geom.getCoordinates()) {
+ int[] cell = halfOpenCell(coord, metadata);
+ if (cell == null) {
+ continue;
+ }
+ cells.expandToInclude(
+ toWorldCoordinate(cell[0], scaleX, upperLeftX),
+ toWorldCoordinate(cell[1], scaleY, upperLeftY));
+ cells.expandToInclude(
+ toWorldCoordinate(cell[0] + 1, scaleX, upperLeftX),
+ toWorldCoordinate(cell[1] + 1, scaleY, upperLeftY));
+ }
+ return cells.isNull()
+ ? null
+ : new ReferencedEnvelope(cells, raster.getCoordinateReferenceSystem2D());
+ }
+
private static double toPixelIndex(double coord, double scale, double upperLeft, boolean isMin) {
BigDecimal rel = BigDecimal.valueOf(coord).subtract(BigDecimal.valueOf(upperLeft));
@@ -658,6 +726,26 @@ public class Rasterization {
double rasterUpperLeftX;
double rasterUpperLeftY;
boolean bottomUp;
+ // Whether any cell has been burned; a cropped output with nothing burned may have nothing in
+ // it.
+ boolean anyBurned;
+
+ /** Burns one cell of the output raster. */
+ void burn(int x, int y, double value) {
+ writableRaster.setSample(x, y, 0, value);
+ anyBurned = true;
+ }
+
+ /** Burns an inclusive horizontal span, recording the burn once for the entire span. */
+ void burnSpan(int xStart, int xEnd, int y, double value) {
+ if (xStart > xEnd) {
+ return;
+ }
+ for (int x = xStart; x <= xEnd; x++) {
+ writableRaster.setSample(x, y, 0, value);
+ }
+ anyBurned = true;
+ }
RasterizationParams(
WritableRaster writableRaster,
@@ -719,16 +807,51 @@ public class Rasterization {
// Clipped geometry could be anything, such as a GeometryCollection, although such cases are
// rare. Delegate to rasterizeGeometry to handle all these cases.
//
- // Points and lines left behind by the clip - where the polygon only grazes the raster - cover
- // no pixel centre. Rasterizing them under centroid semantics would report coverage the source
- // polygon does not have, so keep only the areal parts unless the caller asked for allTouched.
- Geometry toRasterize = allTouched ? clippedGeom : arealComponents(clippedGeom);
+ // Points and lines left behind by the clip - where the polygon only touches the raster or the
+ // window - are boundary contact: they overlap no cell. As in GDAL, a polygon never burns a
+ // cell it touches only on its boundary, allTouched or not, so keep only the areal parts.
+ Geometry toRasterize = arealComponents(clippedGeom);
if (!toRasterize.isEmpty()) {
rasterizeGeometry(raster, metadata, toRasterize, params, geomExtent, value, allTouched);
}
}
}
+ /**
+ * Whether the geometry's polygonal parts overlap the raster's area, rather than only touching its
+ * boundary or lying outside it. Points and lines have no area, so they never do.
+ */
+ private static boolean overlapsRasterArea(Geometry geom, ReferencedEnvelope rasterExtent) {
+ List<?> polygons = PolygonExtracter.getPolygons(geom);
+ if (polygons.isEmpty()) {
+ return false;
+ }
+ Geometry rasterArea = null;
+ for (Object polygon : polygons) {
+ Polygon polygonal = (Polygon) polygon;
+ try {
+ // A valid polygon with positive area wholly inside the raster must overlap its area. This
+ // avoids constructing the raster polygon and relating it for unburned subpixel polygons.
+ if (rasterExtent.contains(polygonal.getEnvelopeInternal())
+ && polygonal.getArea() > 0
+ && polygonal.isValid()) {
+ return true;
+ }
+ if (rasterArea == null) {
+ rasterArea = JTS.toGeometry((BoundingBox) rasterExtent);
+ }
+ if (polygonal.relate(rasterArea, "T********")) {
+ return true;
+ }
+ } catch (TopologyException e) {
+ // An invalid polygon cannot be related exactly. Assume it overlaps, which keeps the
+ // cropped output as it was before rather than dropping it.
+ return true;
+ }
+ }
+ return false;
+ }
+
/** Keeps only the polygonal parts of a geometry, dropping any point or line components. */
private static Geometry arealComponents(Geometry geom) {
List<Geometry> polygons = new ArrayList<>();
@@ -757,12 +880,13 @@ public class Rasterization {
allRings.add(polygon.getInteriorRingN(i));
}
- for (LineString ring : allRings) {
+ for (int r = 0; r < allRings.size(); r++) {
+ LineString ring = allRings.get(r);
Coordinate[] coords = ring.getCoordinates();
int numPoints = coords.length;
if (allTouched) {
- rasterizeLineString(ring, params, value, geomExtent);
+ burnRingOutline(coords, r == 0, params, value, geomExtent);
}
for (int i = 0; i < numPoints - 1; i++) {
@@ -832,6 +956,51 @@ public class Rasterization {
return scanlineIntersections;
}
+ /**
+ * Burns every cell a polygon ring's outline passes through, for allTouched.
+ *
+ * <p>An outline edge that lies exactly on a grid line touches the cells on both sides of it but
+ * overlaps only the one on the polygon's side. Burning the half-open default instead would burn a
+ * cell outside a grid-aligned polygon along its right and bottom edges. As in GDAL, a polygon
+ * never burns a cell it touches only on its boundary, so such an edge burns the cell on the
+ * polygon's side, found from the ring's orientation.
+ */
+ private static void burnRingOutline(
+ Coordinate[] coords,
+ boolean isShell,
+ RasterizationParams params,
+ double value,
+ ReferencedEnvelope geomExtent) {
+ if (coords.length < 4) {
+ return;
+ }
+ // The polygon's interior is on the left of a counter-clockwise shell, and on the right of a
+ // counter-clockwise hole.
+ boolean interiorOnLeft = Orientation.isCCW(coords) == isShell;
+ double side = interiorOnLeft ? 1 : -1;
+
+ for (int i = 0; i < coords.length - 1; i++) {
+ LineSegment clipped = clipSegmentToRasterBounds(coords[i], coords[i + 1], geomExtent);
+ if (clipped == null) {
+ continue;
+ }
+ // The left normal of the direction of travel is (-dy, dx) in world space. Pixel x grows with
+ // world x when scaleX is positive, and pixel y grows as world y falls (scaleY < 0 here).
+ double worldDx = coords[i + 1].x - coords[i].x;
+ double worldDy = coords[i + 1].y - coords[i].y;
+ boolean interiorTowardsNegativeWorldX = -worldDy * side < 0;
+ boolean interiorTowardsPositiveWorldY = worldDx * side > 0;
+ boolean flatTowardsNegativeX = interiorTowardsNegativeWorldX == (params.scaleX > 0);
+ boolean flatTowardsNegativeY = interiorTowardsPositiveWorldY;
+
+ double x0 = (clipped.p0.x - params.upperLeftX) / params.scaleX;
+ double y0 = (clipped.p0.y - params.upperLeftY) / params.scaleY;
+ double x1 = (clipped.p1.x - params.upperLeftX) / params.scaleX;
+ double y1 = (clipped.p1.y - params.upperLeftY) / params.scaleY;
+ traverseSegment(params, x0, y0, x1, y1, value, flatTowardsNegativeX, flatTowardsNegativeY);
+ }
+ }
+
/** Computes startX and endX pairs for each scanline by leveraging sorted X-intercepts. */
private static Map<Integer, List<int[]>> computeFillRanges(
Map<Double, TreeSet<Double>> scanlineIntersections) {
@@ -895,16 +1064,14 @@ public class Rasterization {
// edge pixel: unlike the point path there is no per-cell intersection test here, so
// folding would burn a pixel the polygon does not reach.
if (range[0] >= 0 && range[0] < width) {
- params.writableRaster.setSample(range[0], y, 0, value);
+ params.burn(range[0], y, value);
}
continue;
}
int xStart = clampToGrid(range[0], width);
int xEnd = clampToGrid(range[1], width);
- for (int x = xStart; x <= xEnd; x++) {
- params.writableRaster.setSample(x, y, 0, value);
- }
+ params.burnSpan(xStart, xEnd, y, value);
}
}
}
diff --git a/common/src/test/java/org/apache/sedona/common/raster/FunctionEditorsTest.java b/common/src/test/java/org/apache/sedona/common/raster/FunctionEditorsTest.java
index ba08662e2df..1c4314cf996 100644
--- a/common/src/test/java/org/apache/sedona/common/raster/FunctionEditorsTest.java
+++ b/common/src/test/java/org/apache/sedona/common/raster/FunctionEditorsTest.java
@@ -70,9 +70,9 @@ public class FunctionEditorsTest extends RasterTestBase {
expected =
new double[] {
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0,
- 10.0, 0.0, 0.0, 0.0, 10.0, 10.0, 0.0, 0.0, 0.0, 10.0, 10.0, 0.0, 0.0, 0.0, 0.0, 0.0, 10.0,
+ 10.0, 0.0, 0.0, 0.0, 0.0, 10.0, 0.0, 0.0, 0.0, 10.0, 10.0, 0.0, 0.0, 0.0, 0.0, 0.0, 10.0,
10.0, 0.0, 10.0, 10.0, 0.0, 0.0, 0.0, 10.0, 0.0, 10.0, 10.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
- 0.0, 0.0, 0.0, 0.0, 10.0, 10.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 10.0, 10.0, 10.0, 10.0, 0.0,
+ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 10.0, 10.0, 0.0, 10.0, 0.0,
0.0, 0.0, 0.0, 10.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 10.0, 10.0, 10.0, 10.0,
10.0, 10.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0
};
@@ -217,25 +217,29 @@ public class FunctionEditorsTest extends RasterTestBase {
};
assertArrayEquals(expected, actual, 0.1d);
- // Point
+ // Point on the raster's right edge (x = 5 on a raster spanning x 1..5). Under GDAL's half-open
+ // rule a cell does not contain its right edge, so the point covers no pixel and the raster is
+ // left unchanged, as with rasterio all_touched=True.
geom = Constructors.geomFromWKT("POINT(5 -5)", 0);
raster = PixelFunctionEditors.setValues(emptyRaster, 1, geom, 35);
actual = MapAlgebra.bandAsArray(raster, 1);
expected =
new double[] {
- 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 35.0, 0.0, 0.0,
- 0.0, 35.0, 0.0, 0.0, 0.0, 0.0
+ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
+ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0
};
assertArrayEquals(expected, actual, 0.1d);
- // MultiPoint
+ // MultiPoint: each point burns the one half-open cell containing it, as in GDAL. (2 -2) and
+ // (3 -3) sit on grid corners and (2 -1) on the top edge, so each burns the cell right of and
+ // below it; (4 -7) lies on the bottom edge and burns nothing.
geom = Constructors.geomFromWKT("MULTIPOINT((2 -2), (2 -1), (3 -3), (4 -7))", 0);
raster = PixelFunctionEditors.setValues(emptyRaster, 1, geom, 400, false);
actual = MapAlgebra.bandAsArray(raster, 1);
expected =
new double[] {
- 400.0, 400.0, 0.0, 0.0, 400.0, 400.0, 400.0, 0.0, 0.0, 400.0, 400.0, 0.0, 0.0, 0.0, 0.0,
- 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 400.0, 400.0
+ 0.0, 400.0, 0.0, 0.0, 0.0, 400.0, 0.0, 0.0, 0.0, 0.0, 400.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
+ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0
};
assertArrayEquals(expected, actual, 0.1d);
diff --git a/common/src/test/java/org/apache/sedona/common/raster/RasterConstructorsTest.java b/common/src/test/java/org/apache/sedona/common/raster/RasterConstructorsTest.java
index b281d22193f..1804a7cd1cf 100644
--- a/common/src/test/java/org/apache/sedona/common/raster/RasterConstructorsTest.java
+++ b/common/src/test/java/org/apache/sedona/common/raster/RasterConstructorsTest.java
@@ -107,10 +107,9 @@ public class RasterConstructorsTest extends RasterTestBase {
// (GH-3120).
double[] expected =
new double[] {
- 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3093151.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3093151.0,
- 3093151.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3093151.0, 3093151.0, 3.0, 3.0, 3.0, 3093151.0,
- 3093151.0, 3093151.0, 3093151.0, 3.0, 3.0, 3093151.0, 3093151.0, 3093151.0, 3093151.0,
- 3093151.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0
+ 3093151.0, 3.0, 3.0, 3.0, 3.0, 3093151.0, 3093151.0, 3.0, 3.0, 3.0, 3.0, 3093151.0,
+ 3093151.0, 3.0, 3.0, 3093151.0, 3093151.0, 3093151.0, 3093151.0, 3.0, 3093151.0,
+ 3093151.0, 3093151.0, 3093151.0, 3093151.0
};
assertArrayEquals(expected, actual, 0.1d);
@@ -331,17 +330,19 @@ public class RasterConstructorsTest extends RasterTestBase {
};
assertArrayEquals(expected, actual, 0.1d);
- // MultiPoints
+ // MultiPoints. Each point burns the one half-open cell that contains it, as in GDAL: (5 -5)
+ // and (15 -15) sit on grid corners, so they burn the cell after both grid lines in pixel order
+ // (below the corner on the north-up raster, above it on the bottom-up one). The cropped output
+ // is the extent of those cells.
geom = Constructors.geomFromWKT("MULTIPOINT ((5 -5), (10 -10), (15 -15))", 0);
rasterized = RasterConstructors.asRaster(geom, raster, "d", false, 3093151, 3d);
actual = MapAlgebra.bandAsArray(rasterized, 1);
expected =
new double[] {
- 3093151.0, 3093151.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3093151.0, 3093151.0, 3.0, 3.0, 3.0, 3.0,
- 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3093151.0, 3.0, 3.0, 3.0, 3.0, 3.0,
- 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3093151.0, 3093151.0, 3.0, 3.0, 3.0,
- 3.0, 3.0, 3093151.0, 3093151.0
+ 3093151.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3093151.0,
+ 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0,
+ 3.0, 3.0, 3093151.0
};
assertArrayEquals(expected, actual, 0.1d);
@@ -350,10 +351,9 @@ public class RasterConstructorsTest extends RasterTestBase {
actual = MapAlgebra.bandAsArray(rasterized, 1);
expected =
new double[] {
- 3.0, 3.0, 3.0, 3.0, 3.0, 3093151.0, 3093151.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3093151.0,
- 3093151.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3093151.0, 3.0, 3.0, 3.0,
- 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3093151.0, 3093151.0, 3.0, 3.0, 3.0, 3.0, 3.0,
- 3093151.0, 3093151.0, 3.0, 3.0, 3.0, 3.0, 3.0
+ 3.0, 3.0, 3.0, 3.0, 3.0, 3093151.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3093151.0,
+ 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3093151.0, 3.0,
+ 3.0, 3.0, 3.0, 3.0
};
assertArrayEquals(expected, actual, 0.1d);
@@ -363,9 +363,8 @@ public class RasterConstructorsTest extends RasterTestBase {
expected =
new double[] {
- 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
- 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
- 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0
+ 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0,
+ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0
};
assertArrayEquals(expected, actual, 0.1d);
@@ -375,19 +374,20 @@ public class RasterConstructorsTest extends RasterTestBase {
actual = MapAlgebra.bandAsArray(rasterized, 1);
expected =
new double[] {
- 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0,
- 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0,
- 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0
+ 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0,
+ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0
};
assertArrayEquals(expected, actual, 0.1d);
// Point
+ // A point on a grid corner burns only the cell after both grid lines, so the cropped output is
+ // that single cell on both the north-up and the bottom-up raster.
geom = Constructors.geomFromWKT("POINT (5 -5)", 0);
rasterized = RasterConstructors.asRaster(geom, raster, "d", false, 3093151, 3d);
actual = MapAlgebra.bandAsArray(rasterized, 1);
- expected = new double[] {3093151.0, 3093151.0, 3093151.0, 3093151.0};
+ expected = new double[] {3093151.0};
assertArrayEquals(expected, actual, 0.1d);
// Test bottom-up raster case
@@ -397,7 +397,7 @@ public class RasterConstructorsTest extends RasterTestBase {
rasterized = RasterConstructors.asRaster(geom, raster, "d", false, 1d, null);
actual = MapAlgebra.bandAsArray(rasterized, 1);
- expected = new double[] {1.0, 1.0, 1.0, 1.0};
+ expected = new double[] {1.0};
assertArrayEquals(expected, actual, 0.1d);
// Test bottom-up raster case
@@ -1108,19 +1108,17 @@ public class RasterConstructorsTest extends RasterTestBase {
// GDAL burns it through a quirk of its scan order while Sedona burns only cells the boundary
// passes through (GH-3120).
double[] expected = {
- 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 612028.0, 5.0, 5.0, 5.0, 5.0, 5.0,
- 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 612028.0, 612028.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0,
- 5.0, 5.0, 612028.0, 612028.0, 612028.0, 612028.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0,
- 612028.0, 612028.0, 612028.0, 612028.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 612028.0,
- 612028.0, 612028.0, 612028.0, 612028.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 612028.0,
- 612028.0, 612028.0, 612028.0, 612028.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 612028.0,
- 612028.0, 612028.0, 612028.0, 612028.0, 612028.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 612028.0,
- 612028.0, 612028.0, 612028.0, 612028.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 612028.0,
- 612028.0, 612028.0, 612028.0, 612028.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 612028.0,
- 612028.0, 612028.0, 612028.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 612028.0, 612028.0,
- 612028.0, 612028.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 612028.0, 612028.0, 5.0,
- 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0,
- 5.0, 5.0, 5.0, 5.0, 5.0
+ 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 612028.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0,
+ 5.0, 5.0, 5.0, 5.0, 612028.0, 612028.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 612028.0,
+ 612028.0, 612028.0, 612028.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 612028.0, 612028.0, 612028.0,
+ 612028.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 612028.0, 612028.0, 612028.0, 612028.0, 612028.0,
+ 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 612028.0, 612028.0, 612028.0, 612028.0, 612028.0, 5.0, 5.0, 5.0,
+ 5.0, 5.0, 5.0, 612028.0, 612028.0, 612028.0, 612028.0, 612028.0, 612028.0, 5.0, 5.0, 5.0, 5.0,
+ 5.0, 612028.0, 612028.0, 612028.0, 612028.0, 612028.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 612028.0,
+ 612028.0, 612028.0, 612028.0, 612028.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 612028.0, 612028.0,
+ 612028.0, 612028.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 612028.0, 612028.0, 612028.0, 612028.0,
+ 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 612028.0, 612028.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0,
+ 5.0, 5.0, 5.0
};
assertArrayEquals(expected, actual, 0.1d);
diff --git a/common/src/test/java/org/apache/sedona/common/raster/RasterizationTest.java b/common/src/test/java/org/apache/sedona/common/raster/RasterizationTest.java
index ae21d855449..f4ba21d1368 100644
--- a/common/src/test/java/org/apache/sedona/common/raster/RasterizationTest.java
+++ b/common/src/test/java/org/apache/sedona/common/raster/RasterizationTest.java
@@ -22,6 +22,7 @@ import static org.apache.sedona.common.raster.RasterAccessors.metadata;
import java.awt.image.Raster;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.List;
import org.apache.sedona.common.Constructors;
import org.apache.sedona.common.FunctionsGeoTools;
@@ -34,6 +35,7 @@ import org.junit.Test;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryFactory;
+import org.locationtech.jts.geom.LineString;
import org.locationtech.jts.io.ParseException;
import org.locationtech.jts.io.WKTReader;
@@ -155,15 +157,17 @@ public class RasterizationTest extends RasterTestBase {
validateRasterizeGeomExtent(
wktLine, new double[] {5.0, 6.0, 2.0, 3.0}, testRaster, metadata, false);
- // point tests
+ // point tests: a point burns exactly the one cell that contains it under GDAL's half-open
+ // rule, so its extent is that cell. On a grid corner that is the cell after both lines
+ // in pixel order: right of it and, on this north-up raster, below it.
String wktPoint = "POINT (5.0 2.0)";
validateRasterizeGeomExtent(
- wktPoint, new double[] {4.0, 6.0, 1.0, 3.0}, testRaster, metadata, false);
+ wktPoint, new double[] {5.0, 6.0, 1.0, 2.0}, testRaster, metadata, false);
- // intersecting 2 pixels
+ // on a vertical grid line: the cell to its right
wktPoint = "POINT (5.0 2.5)";
validateRasterizeGeomExtent(
- wktPoint, new double[] {4.0, 6.0, 2.0, 3.0}, testRaster, metadata, false);
+ wktPoint, new double[] {5.0, 6.0, 2.0, 3.0}, testRaster, metadata, false);
// within pixel
wktPoint = "POINT (5.25 2.25)";
@@ -286,15 +290,17 @@ public class RasterizationTest extends RasterTestBase {
validateRasterizeGeomExtent(
wktLine, new double[] {5.0, 6.0, 2.0, 3.0}, testRaster, metadata, false);
- // point tests
+ // point tests: a point burns exactly the one cell that contains it under GDAL's half-open
+ // rule, so its extent is that cell. On a grid corner that is the cell after both lines
+ // in pixel order: right of it and, on this bottom-up raster, above it.
String wktPoint = "POINT (5.0 2.0)";
validateRasterizeGeomExtent(
- wktPoint, new double[] {4.0, 6.0, 1.0, 3.0}, testRaster, metadata, false);
+ wktPoint, new double[] {5.0, 6.0, 2.0, 3.0}, testRaster, metadata, false);
- // intersecting 2 pixels
+ // on a vertical grid line: the cell to its right
wktPoint = "POINT (5.0 2.5)";
validateRasterizeGeomExtent(
- wktPoint, new double[] {4.0, 6.0, 2.0, 3.0}, testRaster, metadata, false);
+ wktPoint, new double[] {5.0, 6.0, 2.0, 3.0}, testRaster, metadata, false);
// within pixel
wktPoint = "POINT (5.25 2.25)";
@@ -391,9 +397,10 @@ public class RasterizationTest extends RasterTestBase {
double rightEdge = upperLeftX + 256 * DEM_PIXEL_SIZE;
double bottomEdge = upperLeftY - 256 * DEM_PIXEL_SIZE;
- // A zone far larger than the tile that touches it only at the bottom-right corner. The clip
- // against the raster extent degenerates to a point, so rasterizePolygon delegates to
- // rasterizePoint - the path RS_ZonalStatsAll hits when an admin zone merely grazes a tile.
+ // A zone far larger than the tile that touches it only at the bottom-right corner - the case
+ // RS_ZonalStatsAll hits when an admin zone merely grazes a tile. It used to overrun the grid.
+ // The zone covers no cell of the tile, so, as in GDAL (rasterio all_touched=True), it burns
+ // nothing even with allTouched.
Geometry zone =
new GeometryFactory()
.createPolygon(
@@ -405,8 +412,9 @@ public class RasterizationTest extends RasterTestBase {
new Coordinate(rightEdge, bottomEdge)
});
- assertSingleBurnedPixel(
- Rasterization.rasterize(zone, testRaster, "D", 150, false, true), 255, 255);
+ assertBurnedPixels(Rasterization.rasterize(zone, testRaster, "D", 150, false, true), "[]");
+ Assert.assertEquals(
+ Double.valueOf(0), RasterBandAccessors.getZonalStatsAll(testRaster, zone, 1, true)[0]);
}
@Test
@@ -439,9 +447,11 @@ public class RasterizationTest extends RasterTestBase {
@Test
public void testCroppedOutputResolvesBoundaryContactLikeFullExtent() throws FactoryException {
- // Cell envelopes must be built on the reference raster's grid, not the cropped output's origin.
- // The second point sits exactly on a row boundary and so touches two rows; deriving envelopes
- // from the crop origin put those edges an ULP off and dropped one of them.
+ // A point's cell must be resolved on the reference raster's grid, not the cropped output's
+ // origin, so a cropped output burns the same cell as a full-extent one. The second point sits
+ // on
+ // a row boundary; under GDAL's half-open rule it burns exactly one cell, (20,19) here, which is
+ // also what GDAL (rasterio all_touched=True) burns for these coordinates.
double p = DEM_PIXEL_SIZE;
double ulx = -180.0;
double uly = 60.0;
@@ -455,12 +465,11 @@ public class RasterizationTest extends RasterTestBase {
});
assertBurnedPixels(
- RasterConstructors.asRaster(points, testRaster, "D", true, 150, null),
- "[(0,0), (10,9), (10,10)]");
- // the same contacts, at full-raster offsets
+ RasterConstructors.asRaster(points, testRaster, "D", true, 150, null), "[(0,0), (10,9)]");
+ // the same cells, at full-raster offsets
assertBurnedPixels(
RasterConstructors.asRasterWithRasterExtent(points, testRaster, "D", true, 150, null),
- "[(10,10), (20,19), (20,20)]");
+ "[(10,10), (20,19)]");
}
@Test
@@ -691,6 +700,100 @@ public class RasterizationTest extends RasterTestBase {
Assert.assertArrayEquals(expected, band, 0d);
}
+ @Test
+ public void testLineClippedAtFarRasterEdgeKeepsEdgePixels() throws FactoryException {
+ // 1/3600 degree pixels have no exact double representation. On this tile origin the right edge
+ // converts to pixel x = 256.00000000004, one rounding error past the grid, so a segment that
+ // ends on or crosses it makes the traversal visit a column outside the raster, which burnCell
+ // skips; the bottom edge lands just inside, at y = 255.99999999998886. Either way the edge cell
+ // is visited before the walk leaves the grid, so no pixel inside the raster may be lost. The
+ // reference is the same geometry rasterized on a larger raster with the same origin (so every
+ // unclipped pixel coordinate is bit-for-bit identical), cropped back to the tile.
+ double p = 1.0 / 3600.0;
+ double ulx = -180.0 + 822 * p;
+ double uly = 60.0 - 546 * p;
+ GridCoverage2D tile =
+ RasterConstructors.makeEmptyRaster(1, "d", 256, 256, ulx, uly, p, -p, 0, 0, 4326);
+ GridCoverage2D larger =
+ RasterConstructors.makeEmptyRaster(1, "d", 272, 272, ulx, uly, p, -p, 0, 0, 4326);
+ double right = ulx + 256 * p;
+ double bottom = uly - 256 * p;
+ GeometryFactory factory = new GeometryFactory();
+
+ // Leaves through the right edge along row 100: columns 200..255.
+ LineString acrossRight =
+ line(factory, ulx + 200.5 * p, uly - 100.5 * p, right + 10 * p, uly - 100.5 * p);
+ assertBurnedCount(tile, acrossRight, 56, 255, 100);
+ // Leaves through the bottom edge along column 100: rows 200..255.
+ LineString acrossBottom =
+ line(factory, ulx + 100.5 * p, uly - 200.5 * p, ulx + 100.5 * p, bottom - 10 * p);
+ assertBurnedCount(tile, acrossBottom, 56, 100, 255);
+ // Ends exactly on the extent maximum: columns / rows 250..255.
+ LineString toRight = line(factory, ulx + 250.5 * p, uly - 100.5 * p, right, uly - 100.5 * p);
+ assertBurnedCount(tile, toRight, 6, 255, 100);
+ LineString toBottom = line(factory, ulx + 100.5 * p, uly - 250.5 * p, ulx + 100.5 * p, bottom);
+ assertBurnedCount(tile, toBottom, 6, 100, 255);
+
+ Geometry[] geometries = {
+ acrossRight,
+ acrossBottom,
+ toRight,
+ toBottom,
+ // oblique segments leaving through the right edge, the bottom edge and the corner
+ line(factory, ulx + 240.3 * p, uly - 180.6 * p, right + 7.1 * p, uly - 190.2 * p),
+ line(factory, ulx + 180.6 * p, uly - 240.3 * p, ulx + 190.2 * p, bottom - 7.1 * p),
+ line(factory, ulx + 240.3 * p, uly - 247.7 * p, right + 7.1 * p, bottom - 3.3 * p),
+ line(factory, ulx + 250.5 * p, uly - 252.5 * p, right, bottom),
+ // a polygon crossing both far edges; allTouched burns its ring through the same traversal
+ factory.createPolygon(
+ new Coordinate[] {
+ new Coordinate(ulx + 230.3 * p, uly - 240.6 * p),
+ new Coordinate(right + 9.2 * p, uly - 235.1 * p),
+ new Coordinate(ulx + 245.7 * p, bottom - 8.4 * p),
+ new Coordinate(ulx + 230.3 * p, uly - 240.6 * p)
+ })
+ };
+ for (Geometry geom : geometries) {
+ for (Geometry g : new Geometry[] {geom, geom.reverse()}) {
+ double[] expected = crop(burn(g, larger, true), 272, 256, 256);
+ Assert.assertArrayEquals(g.toText(), expected, burn(g, tile, true), 0d);
+ }
+ }
+ }
+
+ private static LineString line(
+ GeometryFactory factory, double x0, double y0, double x1, double y1) {
+ return factory.createLineString(
+ new Coordinate[] {new Coordinate(x0, y0), new Coordinate(x1, y1)});
+ }
+
+ private static double[] burn(Geometry geom, GridCoverage2D raster, boolean allTouched)
+ throws FactoryException {
+ return MapAlgebra.bandAsArray(
+ RasterConstructors.asRaster(geom, raster, "d", allTouched, 1d, 0d, false), 1);
+ }
+
+ private static double[] crop(double[] band, int bandWidth, int width, int height) {
+ double[] cropped = new double[width * height];
+ for (int y = 0; y < height; y++) {
+ System.arraycopy(band, y * bandWidth, cropped, y * width, width);
+ }
+ return cropped;
+ }
+
+ /** Asserts the burned pixel count of both directions of a line, and that an edge cell is set. */
+ private static void assertBurnedCount(
+ GridCoverage2D raster, LineString line, int expectedCount, int edgeX, int edgeY)
+ throws FactoryException {
+ int width = RasterAccessors.getWidth(raster);
+ for (Geometry g : new Geometry[] {line, line.reverse()}) {
+ double[] band = burn(g, raster, false);
+ Assert.assertEquals(
+ g.toText(), expectedCount, Arrays.stream(band).filter(v -> v != 0).count());
+ Assert.assertEquals(g.toText(), 1d, band[edgeY * width + edgeX], 0d);
+ }
+ }
+
private GridCoverage2D unitGrid6x6() throws FactoryException {
return RasterConstructors.makeEmptyRaster(1, "d", 6, 6, 0, 6, 1, -1, 0, 0, 0);
}
@@ -736,4 +839,225 @@ public class RasterizationTest extends RasterTestBase {
Assert.assertEquals(expectedEnvelope[3], envelope.getMaxY(), FP_TOLERANCE);
}
}
+
+ // GDAL's half-open boundary rule (GH-3425). A cell contains its first edge in pixel order but not
+ // its last, so a geometry never burns a cell it touches only on its boundary. The expected cells
+ // are what GDAL 3.12 (rasterio.features.rasterize) burns on the same grids, identically with
+ // all_touched on and off.
+
+ /** An 8x8 grid of unit pixels over [0, 8] x [0, 8], north-up or bottom-up. */
+ private static GridCoverage2D unitGrid8x8(boolean bottomUp) throws FactoryException {
+ return bottomUp
+ ? RasterConstructors.makeEmptyRaster(1, "D", 8, 8, 0, 0, 1, 1, 0, 0, 0)
+ : RasterConstructors.makeEmptyRaster(1, "D", 8, 8, 0, 8, 1, -1, 0, 0, 0);
+ }
+
+ /** Asserts the burned pixels at full extent, with allTouched both off and on. */
+ private void assertBurnedLikeGdal(GridCoverage2D raster, String wkt, String expected)
+ throws ParseException, FactoryException {
+ Geometry geom = wktReader.read(wkt);
+ for (boolean allTouched : new boolean[] {false, true}) {
+ assertBurnedPixels(
+ RasterConstructors.asRasterWithRasterExtent(geom, raster, "D", allTouched, 150, null),
+ expected);
+ }
+ }
+
+ @Test
+ public void testPointBurnsTheHalfOpenCellContainingIt() throws ParseException, FactoryException {
+ GridCoverage2D northUp = unitGrid8x8(false);
+ // On a row line, a column line or a grid corner, only the cell after the line(s) in pixel
+ // order.
+ assertBurnedLikeGdal(northUp, "POINT (3.5 5)", "[(3,3)]");
+ assertBurnedLikeGdal(northUp, "POINT (3 4.5)", "[(3,3)]");
+ assertBurnedLikeGdal(northUp, "POINT (3 5)", "[(3,3)]");
+ // The raster's left and top edges belong to its cells; its right and bottom edges do not.
+ assertBurnedLikeGdal(northUp, "POINT (0 4.5)", "[(0,3)]");
+ assertBurnedLikeGdal(northUp, "POINT (3.5 8)", "[(3,0)]");
+ assertBurnedLikeGdal(northUp, "POINT (8 4.5)", "[]");
+ assertBurnedLikeGdal(northUp, "POINT (3.5 0)", "[]");
+ assertBurnedLikeGdal(northUp, "POINT (8 0)", "[]");
+
+ // Bottom-up, pixel order runs up the raster: a point on a horizontal grid line falls in the
+ // cell above it, and the top edge is the far edge.
+ GridCoverage2D bottomUp = unitGrid8x8(true);
+ assertBurnedLikeGdal(bottomUp, "POINT (3.5 3)", "[(3,3)]");
+ assertBurnedLikeGdal(bottomUp, "POINT (3 3)", "[(3,3)]");
+ assertBurnedLikeGdal(bottomUp, "POINT (3.5 0)", "[(3,0)]");
+ assertBurnedLikeGdal(bottomUp, "POINT (3.5 8)", "[]");
+ assertBurnedLikeGdal(bottomUp, "POINT (8 8)", "[]");
+
+ // Cropped to the geometry, the output is that single cell, or nothing on the far edge.
+ GridCoverage2D cropped =
+ RasterConstructors.asRaster(
+ wktReader.read("POINT (3 5)"), northUp, "D", true, 150, null, true);
+ Assert.assertEquals(1, RasterAccessors.getWidth(cropped));
+ Assert.assertEquals(1, RasterAccessors.getHeight(cropped));
+ Assert.assertEquals(3.0, RasterAccessors.getUpperLeftX(cropped), FP_TOLERANCE);
+ Assert.assertEquals(5.0, RasterAccessors.getUpperLeftY(cropped), FP_TOLERANCE);
+ Assert.assertNull(
+ RasterConstructors.asRaster(
+ wktReader.read("POINT (8 4.5)"), northUp, "D", true, 150, null, true));
+ }
+
+ @Test
+ public void testGridAlignedPolygonBurnsOnlyItsInterior() throws ParseException, FactoryException {
+ // Edges on grid lines touch the cells beyond them but overlap only the interior, so allTouched
+ // burns exactly the interior, along an inner corner and around a hole as well.
+ for (boolean bottomUp : new boolean[] {false, true}) {
+ GridCoverage2D raster = unitGrid8x8(bottomUp);
+ String box =
+ bottomUp ? "POLYGON ((2 2, 4 2, 4 4, 2 4, 2 2))" : "POLYGON ((2 6, 4 6, 4 4, 2 4, 2 6))";
+ String lShape =
+ bottomUp
+ ? "POLYGON ((2 2, 6 2, 6 4, 4 4, 4 6, 2 6, 2 2))"
+ : "POLYGON ((2 6, 6 6, 6 4, 4 4, 4 2, 2 2, 2 6))";
+ String boxWithHole =
+ bottomUp
+ ? "POLYGON ((1 1, 7 1, 7 7, 1 7, 1 1), (3 3, 5 3, 5 5, 3 5, 3 3))"
+ : "POLYGON ((1 7, 7 7, 7 1, 1 1, 1 7), (3 5, 5 5, 5 3, 3 3, 3 5))";
+ assertBurnedLikeGdal(raster, box, "[(2,2), (3,2), (2,3), (3,3)]");
+ assertBurnedLikeGdal(
+ raster,
+ lShape,
+ "[(2,2), (3,2), (4,2), (5,2), (2,3), (3,3), (4,3), (5,3), (2,4), (3,4), (2,5), (3,5)]");
+ assertBurnedLikeGdal(
+ raster,
+ boxWithHole,
+ "[(1,1), (2,1), (3,1), (4,1), (5,1), (6,1), (1,2), (2,2), (3,2), (4,2), (5,2), (6,2),"
+ + " (1,3), (2,3), (5,3), (6,3), (1,4), (2,4), (5,4), (6,4), (1,5), (2,5), (3,5),"
+ + " (4,5), (5,5), (6,5), (1,6), (2,6), (3,6), (4,6), (5,6), (6,6)]");
+ }
+ }
+
+ @Test
+ public void testPolygonTouchingRasterOnlyOnItsBoundaryCoversNothing()
+ throws ParseException, FactoryException, TransformException {
+ GridCoverage2D raster = unitGrid8x8(false);
+ String[] touching = {
+ "POLYGON ((-2 6, 0 6, 0 4, -2 4, -2 6))", // left edge
+ "POLYGON ((8 6, 10 6, 10 4, 8 4, 8 6))", // right edge
+ "POLYGON ((2 10, 4 10, 4 8, 2 8, 2 10))", // top edge
+ "POLYGON ((2 0, 4 0, 4 -2, 2 -2, 2 0))", // bottom edge
+ "POLYGON ((8 0, 10 0, 10 -2, 8 -2, 8 0))" // bottom-right corner
+ };
+ for (String wkt : touching) {
+ assertBurnedLikeGdal(raster, wkt, "[]");
+ Geometry zone = wktReader.read(wkt);
+ for (boolean allTouched : new boolean[] {false, true}) {
+ // No pixel is covered, so there is no extent to crop the output to.
+ Assert.assertNull(
+ RasterConstructors.asRaster(zone, raster, "D", allTouched, 150, null, true));
+ Assert.assertEquals(
+ Double.valueOf(0),
+ RasterBandAccessors.getZonalStatsAll(raster, zone, 1, allTouched)[0]);
+ }
+ }
+
+ Geometry rightEdge = wktReader.read(touching[1]);
+ // RS_SetValues leaves the raster unchanged.
+ GridCoverage2D updated = PixelFunctionEditors.setValues(raster, 1, rightEdge, 7, true);
+ Assert.assertArrayEquals(new double[64], MapAlgebra.bandAsArray(updated, 1), 0);
+ // RS_Clip keeps no pixel; cropping has nothing to crop to.
+ GridCoverage2D clipped = RasterBandEditors.clip(raster, 1, rightEdge, true, -1, false, false);
+ double[] allNoData = new double[64];
+ Arrays.fill(allNoData, -1);
+ Assert.assertArrayEquals(allNoData, MapAlgebra.bandAsArray(clipped, 1), 0);
+ Assert.assertNull(RasterBandEditors.clip(raster, 1, rightEdge, true, -1, true, true));
+ Assert.assertThrows(
+ IllegalArgumentException.class,
+ () -> RasterBandEditors.clip(raster, 1, rightEdge, true, -1, true, false));
+ }
+
+ @Test
+ public void testZoneOnTileBoundaryIsCountedOnceAcrossTiles()
+ throws ParseException, FactoryException {
+ // Two adjacent 8x8 unit tiles, A over x in [0, 8] and B over x in [8, 16], and one raster
+ // covering both. Every grid line belongs to exactly one cell, so per-tile counts of a zone that
+ // ends or starts on the A|B boundary add up to its count on the single raster.
+ GridCoverage2D tileA = RasterConstructors.makeEmptyRaster(1, "D", 8, 8, 0, 8, 1, -1, 0, 0, 0);
+ GridCoverage2D tileB = RasterConstructors.makeEmptyRaster(1, "D", 8, 8, 8, 8, 1, -1, 0, 0, 0);
+ GridCoverage2D mosaic = RasterConstructors.makeEmptyRaster(1, "D", 16, 8, 0, 8, 1, -1, 0, 0, 0);
+ for (String wkt :
+ new String[] {
+ "POLYGON ((5 2, 8 2, 8 5, 5 5, 5 2))", "POLYGON ((8 2, 11 2, 11 5, 8 5, 8 2))"
+ }) {
+ Geometry zone = wktReader.read(wkt);
+ for (boolean allTouched : new boolean[] {false, true}) {
+ double inA = RasterBandAccessors.getZonalStatsAll(tileA, zone, 1, allTouched)[0];
+ double inB = RasterBandAccessors.getZonalStatsAll(tileB, zone, 1, allTouched)[0];
+ double inMosaic = RasterBandAccessors.getZonalStatsAll(mosaic, zone, 1, allTouched)[0];
+ Assert.assertEquals(9, inMosaic, 0);
+ Assert.assertEquals(inMosaic, inA + inB, 0);
+ }
+ }
+ }
+
+ @Test
+ public void testCroppedMixedCollectionKeepsEveryMembersCells()
+ throws ParseException, FactoryException {
+ // The point lies on the collection envelope's last column line, so its half-open cell is past
+ // that envelope. The cropped window is the union of the members' windows, so the cropped
+ // output still burns the same cells as the full-extent one, which are GDAL's.
+ GridCoverage2D raster = unitGrid8x8(false);
+ String wkt = "GEOMETRYCOLLECTION (POLYGON ((1 7, 3 7, 3 5, 1 5, 1 7)), POINT (6 4.5))";
+ assertBurnedLikeGdal(raster, wkt, "[(1,1), (2,1), (1,2), (2,2), (6,3)]");
+ for (boolean allTouched : new boolean[] {false, true}) {
+ GridCoverage2D cropped =
+ RasterConstructors.asRaster(
+ wktReader.read(wkt), raster, "D", allTouched, 150, null, true);
+ Assert.assertEquals(1.0, RasterAccessors.getUpperLeftX(cropped), FP_TOLERANCE);
+ Assert.assertEquals(7.0, RasterAccessors.getUpperLeftY(cropped), FP_TOLERANCE);
+ assertBurnedPixels(cropped, "[(0,0), (1,0), (0,1), (1,1), (5,2)]");
+ }
+ }
+
+ @Test
+ public void testCroppedOutputIsNullOnlyWhenNothingIsBurnedOrOverlapped()
+ throws ParseException, FactoryException, TransformException {
+ GridCoverage2D raster = unitGrid8x8(false);
+ // Each of these only touches the raster: a polygon meeting it diagonally at its top-right
+ // corner (its window still holds that corner cell), and lines along its right and bottom
+ // edges. GDAL burns nothing for them, and with nothing burned and no pixel area overlapped
+ // there is nothing to crop to.
+ String[] touchingOnly = {
+ "POLYGON ((9 7, 7 9, 10 10, 9 7))", "LINESTRING (8 1, 8 6)", "LINESTRING (1 0, 6 0)"
+ };
+ for (String wkt : touchingOnly) {
+ assertBurnedLikeGdal(raster, wkt, "[]");
+ for (boolean allTouched : new boolean[] {false, true}) {
+ Assert.assertNull(
+ RasterConstructors.asRaster(
+ wktReader.read(wkt), raster, "D", allTouched, 150, null, true));
+ }
+ }
+ Geometry corner = wktReader.read(touchingOnly[0]);
+ Assert.assertNull(RasterBandEditors.clip(raster, 1, corner, true, -1, true, true));
+ double[] allNoData = new double[64];
+ Arrays.fill(allNoData, -1);
+ Assert.assertArrayEquals(
+ allNoData,
+ MapAlgebra.bandAsArray(
+ RasterBandEditors.clip(raster, 1, corner, true, -1, false, false), 1),
+ 0);
+ Assert.assertArrayEquals(
+ new double[64],
+ MapAlgebra.bandAsArray(PixelFunctionEditors.setValues(raster, 1, corner, 7, true), 1),
+ 0);
+
+ // A polygon that overlaps a pixel without covering its centre burns nothing without allTouched,
+ // as in GDAL, but it does overlap the pixel, so its cropped output is that pixel, unburned.
+ Geometry small = wktReader.read("POLYGON ((3.1 4.1, 3.4 4.1, 3.4 4.4, 3.1 4.4, 3.1 4.1))");
+ assertBurnedPixels(
+ RasterConstructors.asRasterWithRasterExtent(small, raster, "D", false, 150, null), "[]");
+ GridCoverage2D cropped =
+ RasterConstructors.asRaster(small, raster, "D", false, 150, null, true);
+ Assert.assertEquals(1, RasterAccessors.getWidth(cropped));
+ Assert.assertEquals(1, RasterAccessors.getHeight(cropped));
+ Assert.assertEquals(3.0, RasterAccessors.getUpperLeftX(cropped), FP_TOLERANCE);
+ Assert.assertEquals(5.0, RasterAccessors.getUpperLeftY(cropped), FP_TOLERANCE);
+ assertBurnedPixels(cropped, "[]");
+ assertBurnedPixels(
+ RasterConstructors.asRaster(small, raster, "D", true, 150, null, true), "[(0,0)]");
+ }
}
diff --git a/docs/api/sql/Raster-Band-Accessors/RS_ZonalStats.md b/docs/api/sql/Raster-Band-Accessors/RS_ZonalStats.md
index 828865843db..42eee22a388 100644
--- a/docs/api/sql/Raster-Band-Accessors/RS_ZonalStats.md
+++ b/docs/api/sql/Raster-Band-Accessors/RS_ZonalStats.md
@@ -23,7 +23,7 @@ Introduction: This returns a statistic value specified by `statType` over the re
The `allTouched` parameter (Since `v1.7.1`) determines how pixels are selected:
-- When true, any pixel touched by the geometry will be included.
+- When true, any pixel touched by the geometry will be included. As in GDAL, a pixel the geometry touches only on its boundary, along an edge or at a corner, is not included, so a geometry that ends exactly on a pixel boundary does not pull in the pixels beyond it.
- When false (default), only pixels whose centroid intersects with the geometry will be included.

diff --git a/docs/api/sql/Raster-Band-Accessors/RS_ZonalStatsAll.md b/docs/api/sql/Raster-Band-Accessors/RS_ZonalStatsAll.md
index f577684f502..c1e614329b9 100644
--- a/docs/api/sql/Raster-Band-Accessors/RS_ZonalStatsAll.md
+++ b/docs/api/sql/Raster-Band-Accessors/RS_ZonalStatsAll.md
@@ -23,7 +23,7 @@ Introduction: Returns a struct of statistic values, where each statistic is comp
The `allTouched` parameter (Since `v1.7.1`) determines how pixels are selected:
-- When true, any pixel touched by the geometry will be included.
+- When true, any pixel touched by the geometry will be included. As in GDAL, a pixel the geometry touches only on its boundary, along an edge or at a corner, is not included, so a geometry that ends exactly on a pixel boundary does not pull in the pixels beyond it.
- When false (default), only pixels whose centroid intersects with the geometry will be included.

diff --git a/docs/api/sql/Raster-Operators/RS_AsRaster.md b/docs/api/sql/Raster-Operators/RS_AsRaster.md
index facd0650108..11a81d3f0ee 100644
--- a/docs/api/sql/Raster-Operators/RS_AsRaster.md
+++ b/docs/api/sql/Raster-Operators/RS_AsRaster.md
@@ -24,10 +24,10 @@ Introduction: `RS_AsRaster` converts a vector geometry into a raster dataset by
* `geom`: The geometry to be rasterized.
* `raster`: The reference raster to be used for overlaying the `geom` on.
* `pixelType`: Defines data type of the output raster. This can be one of the following, D (double), F (float), I (integer), S (short), US (unsigned short) or B (byte).
-* `allTouched` (Since: `v1.7.1`): Decides the pixel selection criteria. If set to `true`, the function selects all pixels touched by the geometry, else, selects only pixels whose centroids intersect the geometry. Defaults to `false`. For lines and polygon boundaries, when a vertex maps exactly to a pixel grid line, a neighboring pixel contacted only at that endpoint is not selected unless the segment enters it. `POINT` geometries instead burn every pixel whose extent contains the point, [...]
+* `allTouched` (Since: `v1.7.1`): Decides the pixel selection criteria. If set to `true`, the function selects all pixels touched by the geometry, else, selects only pixels whose centroids intersect the geometry. Defaults to `false`. As in GDAL, pixels are half-open: a pixel contains its first edges in pixel order (the left and top edges on a north-up raster) but not its last, so a pixel the geometry touches only on its boundary is not selected, and a polygon whose edges lie on pixel gri [...]
* `value`: The value to be used for assigning pixels covered by the geometry. Defaults to using `1.0` if not provided.
* `noDataValue`: The no data value of the resultant raster. Every pixel the geometry does not cover (including interior holes) is filled with the resolved no data value, which is also recorded as the output band's no data metadata. The value must be representable in `pixelType`: an out-of-range or fractional value for an integer `pixelType`, or a value that is not exactly representable in a floating-point `pixelType` (for example `0.1` in a 32-bit float band), is rejected with an error r [...]
-* `useGeometryExtent`: Defines the extent of the resultant raster. When set to `true`, it corresponds to the extent of `geom`, and when set to false, it corresponds to the extent of `raster`. Default value is `true` if not set.
+* `useGeometryExtent`: Defines the extent of the resultant raster. When set to `true`, it corresponds to the extent of `geom`, and when set to false, it corresponds to the extent of `raster`. Default value is `true` if not set. When set to `true` and `geom` neither burns nor overlaps any pixel of `raster`, for example a polygon that only touches its boundary or a line along its right or bottom edge, there is nothing to crop to and `RS_AsRaster` returns `null`. A polygon that overlaps a p [...]
Format:
diff --git a/docs/api/sql/Raster-Operators/RS_Clip.md b/docs/api/sql/Raster-Operators/RS_Clip.md
index 7433f5e4850..61875207a43 100644
--- a/docs/api/sql/Raster-Operators/RS_Clip.md
+++ b/docs/api/sql/Raster-Operators/RS_Clip.md
@@ -25,7 +25,7 @@ If `crop` is not specified then it will default to `true`, meaning it will make
The `allTouched` parameter (Since `v1.7.1`) determines how pixels are selected:
-- When true, any pixel touched by the geometry will be included.
+- When true, any pixel touched by the geometry will be included. As in GDAL, a pixel the geometry touches only on its boundary, along an edge or at a corner, is not included, so a geometry that ends exactly on a pixel boundary does not pull in the pixels beyond it.
- When false (default), only pixels whose centroid intersects with the geometry will be included.
!!!Note
diff --git a/docs/api/sql/Raster-Operators/RS_SetValues.md b/docs/api/sql/Raster-Operators/RS_SetValues.md
index 4a06d164853..dc5ca542ebb 100644
--- a/docs/api/sql/Raster-Operators/RS_SetValues.md
+++ b/docs/api/sql/Raster-Operators/RS_SetValues.md
@@ -48,7 +48,7 @@ The geometry variant of this function accepts all types of Geometries, and it se
The `allTouched` parameter (Since `v1.7.1`) determines how pixels are selected:
-- When true, any pixel touched by the geometry will be included.
+- When true, any pixel touched by the geometry will be included. As in GDAL, a pixel the geometry touches only on its boundary, along an edge or at a corner, is not included, so a geometry that ends exactly on a pixel boundary does not pull in the pixels beyond it.
- When false (default), only pixels whose centroid intersects with the geometry will be included.
!!!note
diff --git a/python/tests/sql/test_rasterize_parity.py b/python/tests/sql/test_rasterize_parity.py
index 826ccd30311..5513b395c5c 100644
--- a/python/tests/sql/test_rasterize_parity.py
+++ b/python/tests/sql/test_rasterize_parity.py
@@ -20,6 +20,7 @@ import random
import numpy as np
import rasterio.features
from affine import Affine
+from shapely.affinity import affine_transform
from shapely.geometry import Polygon
from shapely.wkt import loads as wkt_loads
@@ -218,3 +219,74 @@ class TestRasterizeParity(TestBase):
dtype="uint8",
)
assert np.array_equal(actual, expected)
+
+ def test_as_raster_half_open_cell_boundaries_match_gdal(self):
+ """Geometries lying exactly on grid lines (GH-3425). GDAL treats every
+ cell as half-open, with or without all_touched: a cell contains its
+ first edge in pixel order but not its last. A point on a grid line or
+ a grid corner burns exactly one cell, a point on the raster's far edge
+ burns none, a grid-aligned polygon burns only its interior, and a
+ polygon that only touches the raster burns nothing."""
+ grids = [
+ # width, height, ulx, uly, sx, sy
+ (8, 8, 0.0, 8.0, 1.0, -1.0), # north-up
+ (8, 8, 0.0, 0.0, 1.0, 1.0), # bottom-up
+ (8, 8, 100.25, 50.5, 0.25, -0.25), # decimal pixel size
+ ]
+ # Geometries in pixel coordinates (column, row), mapped onto each grid.
+ pixel_wkts = [
+ "POINT (3.5 3)", # on a row line
+ "POINT (3 3.5)", # on a column line
+ "POINT (3 3)", # on a grid corner
+ "POINT (0 3.5)", # on the first column edge
+ "POINT (8 3.5)", # on the last column edge
+ "POINT (3.5 0)", # on the first row edge
+ "POINT (3.5 8)", # on the last row edge
+ "POINT (8 8)", # on the far corner
+ "MULTIPOINT ((3 3.5), (5.5 5.5))",
+ "POLYGON ((2 2, 4 2, 4 4, 2 4, 2 2))",
+ "POLYGON ((2 2, 6 2, 6 4, 4 4, 4 6, 2 6, 2 2))",
+ "POLYGON ((1 1, 7 1, 7 7, 1 7, 1 1), (3 3, 5 3, 5 5, 3 5, 3 3))",
+ "POLYGON ((-3 2, 2 2, 2 4, -3 4, -3 2))", # past the first column edge
+ "POLYGON ((6 2, 11 2, 11 4, 6 4, 6 2))", # past the last column edge
+ "POLYGON ((2 -3, 4 -3, 4 2, 2 2, 2 -3))", # past the first row edge
+ "POLYGON ((2 6, 4 6, 4 11, 2 11, 2 6))", # past the last row edge
+ "POLYGON ((-2 2, 0 2, 0 4, -2 4, -2 2))", # touching the first column edge
+ "POLYGON ((8 2, 10 2, 10 4, 8 4, 8 2))", # touching the last column edge
+ "POLYGON ((2 -2, 4 -2, 4 0, 2 0, 2 -2))", # touching the first row edge
+ "POLYGON ((2 8, 4 8, 4 10, 2 10, 2 8))", # touching the last row edge
+ "POLYGON ((8 8, 10 8, 10 10, 8 10, 8 8))", # touching the far corner
+ ]
+ cases = []
+ for width, height, ulx, uly, sx, sy in grids:
+ for pixel_wkt in pixel_wkts:
+ geom = affine_transform(wkt_loads(pixel_wkt), [sx, 0, 0, sy, ulx, uly])
+ cases.append((len(cases), width, height, ulx, uly, sx, sy, geom.wkt))
+ df = self.spark.createDataFrame(
+ cases,
+ "id INT, width INT, height INT, ulx DOUBLE, uly DOUBLE, "
+ "sx DOUBLE, sy DOUBLE, wkt STRING",
+ )
+ for all_touched in (False, True):
+ rows = df.selectExpr(
+ "id",
+ "RS_BandAsArray(RS_AsRaster(ST_GeomFromWKT(wkt), "
+ "RS_MakeEmptyRaster(1, 'd', width, height, ulx, uly, sx, sy, 0, 0, 0), "
+ f"'d', {str(all_touched).lower()}, 1.0, 0.0, false), 1) as band",
+ ).collect()
+ bands = {row["id"]: row["band"] for row in rows}
+
+ for case_id, width, height, ulx, uly, sx, sy, wkt in cases:
+ actual = np.array(bands[case_id], dtype=float).reshape(height, width)
+ expected = rasterio.features.rasterize(
+ [(wkt_loads(wkt), 1)],
+ out_shape=(height, width),
+ fill=0,
+ transform=Affine(sx, 0, ulx, 0, sy, uly),
+ all_touched=all_touched,
+ dtype="uint8",
+ )
+ assert np.array_equal(actual, expected), (
+ f"case {case_id} all_touched={all_touched}: grid {width}x{height}, "
+ f"scale ({sx}, {sy}), origin ({ulx}, {uly}), {wkt}"
+ )
diff --git a/spark/common/src/test/scala/org/apache/sedona/sql/rasteralgebraTest.scala b/spark/common/src/test/scala/org/apache/sedona/sql/rasteralgebraTest.scala
index eb2a9f676a8..d3944ce50f0 100644
--- a/spark/common/src/test/scala/org/apache/sedona/sql/rasteralgebraTest.scala
+++ b/spark/common/src/test/scala/org/apache/sedona/sql/rasteralgebraTest.scala
@@ -816,8 +816,10 @@ class rasteralgebraTest extends TestBaseScala with BeforeAndAfter with GivenWhen
"RS_BandAsArray(RS_SetValues(raster, 1, ST_GeomFromWKT('POINT(2 -2)'), 25), 1)")
.first()
.getSeq(0)
- expected = Seq(25.0, 25.0, 0.0, 0.0, 0.0, 25.0, 25.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
- 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
+ // A point on a grid corner burns only the half-open cell after both grid lines, as in GDAL
+ // (rasterio), not the four cells that meet at the corner.
+ expected = Seq(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 25.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
+ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
assert(expected.equals(actual))
actual = inputDf
@@ -825,8 +827,9 @@ class rasteralgebraTest extends TestBaseScala with BeforeAndAfter with GivenWhen
"RS_BandAsArray(RS_SetValues(raster, 1, ST_GeomFromWKT('MULTIPOINT((2 -2), (2 -1), (3 -3))'), 400), 1)")
.first()
.getSeq(0)
- expected = Seq(400.0, 400.0, 0.0, 0.0, 0.0, 400.0, 400.0, 400.0, 0.0, 0.0, 0.0, 400.0,
- 400.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
+ // One cell per point: (2 -2) and (3 -3) sit on grid corners and (2 -1) on the top edge.
+ expected = Seq(0.0, 400.0, 0.0, 0.0, 0.0, 0.0, 400.0, 0.0, 0.0, 0.0, 0.0, 0.0, 400.0, 0.0,
+ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
assert(expected.equals(actual))
actual = inputDf
@@ -1922,8 +1925,14 @@ class rasteralgebraTest extends TestBaseScala with BeforeAndAfter with GivenWhen
// polygon vertex also sits exactly on a pixel corner (coordinates are multiples of the
// 0.25-degree pixel size), and cells the boundary merely touches at such a corner point are
// not burned (GH-3120), which trims twelve pixels against the pre-GH-3120 count. The count is
- // direction-independent: rasterizing the ring in reverse order yields the same 14655.
- assertEquals(14655.0, actual)
+ // direction-independent: rasterizing the ring in reverse order yields the same count.
+ //
+ // The right edge (x = -155.25) and the bottom edge (y = 40.25) lie exactly on grid lines. They
+ // touch the column and row beyond them but overlap none of their area, so, as in GDAL, those
+ // 289 cells (190 + 100 - 1 shared corner) are not burned (GH-3425). GDAL (rasterio,
+ // all_touched=True) counts 14357 here; the remaining nine cells are near-corner cells along
+ // the steep left edge, a separate difference.
+ assertEquals(14366.0, actual)
actual =
df.selectExpr("RS_ZonalStats(raster, geom, 1, 'mean', false, false)").first().get(0)