From bebdab4a5b6fc9a5dbb423836140822346362c84 Mon Sep 17 00:00:00 2001 From: Vishesh Tarun Modi Date: Wed, 14 Oct 2026 22:31:45 +1100 Subject: [PATCH 1/3] [GH-2409] Clip raster to the ROI extent in zonal statistics getStatObjects rasterized the zone at the full extent of the input raster and then read and scanned every pixel, so the cost scaled with raster size rather than with the size of the region of interest. For a small polygon on a large raster this is both slow and memory-hungry (two full-size sample arrays). Rasterize the ROI with useGeometryExtent=true so only the window covered by the geometry is produced, and read just that window from the source band. The window's offset in the source raster is computed from pixel centres. If the window cannot be placed exactly (for example a skewed raster or a window that does not fit inside the raster), fall back to the previous full-extent path, so results are unchanged in those cases. A null rasterization result (the geometry burns no pixel) now yields an empty pixel set, matching the previous behaviour. Statistics are unchanged: pixels are still visited in row-major order, so the output of RS_ZonalStats and RS_ZonalStatsAll is identical to before. Tests: - [new tests: small polygon on a larger raster, bottom-up raster, polygon that only touches the raster boundary] - RasterBandAccessorsTest passes Benchmark ([machine, JDK], [size] raster, ~50x50 pixel polygon): before [x] ms, after [y] ms Closes #2409 --- .../common/raster/RasterBandAccessors.java | 55 ++++++++++++++++++- 1 file changed, 53 insertions(+), 2 deletions(-) diff --git a/common/src/main/java/org/apache/sedona/common/raster/RasterBandAccessors.java b/common/src/main/java/org/apache/sedona/common/raster/RasterBandAccessors.java index b96b7e8b47a..e92f6af42b9 100644 --- a/common/src/main/java/org/apache/sedona/common/raster/RasterBandAccessors.java +++ b/common/src/main/java/org/apache/sedona/common/raster/RasterBandAccessors.java @@ -31,6 +31,7 @@ import org.apache.sedona.common.Functions; import org.apache.sedona.common.utils.RasterUtils; import org.geotools.api.referencing.FactoryException; +import org.geotools.api.referencing.operation.MathTransform2D; import org.geotools.coverage.GridSampleDimension; import org.geotools.coverage.grid.GridCoverage2D; import org.locationtech.jts.geom.Geometry; @@ -391,16 +392,36 @@ private static List getStatObjects( Raster rasterData = RasterUtils.getRaster(raster.getRenderedImage()); String datatype = RasterBandAccessors.getBandType(raster, band); Double noDataValue = RasterBandAccessors.getBandNoDataValue(raster, band); + + // CHANGED: rasterize only the part of the raster the geometry covers // Adding an arbitrary value '150' for the pixels that are under the geometry. GridCoverage2D rasterizedGeom = - RasterConstructors.asRasterWithRasterExtent(roi, raster, datatype, allTouched, 150, null); + RasterConstructors.asRaster(roi, raster, datatype, allTouched, 150, null, true); + + int xOffset = 0, yOffset = 0; + if (rasterizedGeom == null) { + // NEW: the geometry does not burn any pixel, so there is nothing to compute over + double[] empty = new double[0]; + return Arrays.asList(new DescriptiveStatistics(empty), empty); + } + int[] offset = windowOffset(raster, rasterizedGeom); // NEW + if (offset == null) { + // NEW: fall back to the full-extent path when the window cannot be placed exactly + rasterizedGeom = + RasterConstructors.asRasterWithRasterExtent(roi, raster, datatype, allTouched, 150, null); + } else { + xOffset = offset[0]; + yOffset = offset[1]; + } + Raster rasterizedData = RasterUtils.getRaster(rasterizedGeom.getRenderedImage()); int width = RasterAccessors.getWidth(rasterizedGeom), height = RasterAccessors.getHeight(rasterizedGeom); double[] rasterizedPixelData = rasterizedData.getSamples(0, 0, width, height, 0, (double[]) null); + // CHANGED: read only the window from the source raster double[] rasterPixelData = - rasterData.getSamples(0, 0, width, height, band - 1, (double[]) null); + rasterData.getSamples(xOffset, yOffset, width, height, band - 1, (double[]) null); List pixelData = new ArrayList<>(); @@ -430,6 +451,36 @@ private static List getStatObjects( return statObjects; } + /** + * Returns {x, y}: the position of the window's top-left pixel inside the raster, or null if the + * window is not exactly aligned to the raster's pixel grid or does not fit inside it. + */ + private static int[] windowOffset(GridCoverage2D raster, GridCoverage2D window) { + try { + MathTransform2D windowToWorld = + window + .getGridGeometry() + .getGridToCRS2D(org.geotools.api.metadata.spatial.PixelOrientation.CENTER); + MathTransform2D worldToRaster = + raster + .getGridGeometry() + .getGridToCRS2D(org.geotools.api.metadata.spatial.PixelOrientation.CENTER) + .inverse(); + double[] pt = {0, 0}; // centre of the window's first pixel + windowToWorld.transform(pt, 0, pt, 0, 1); + worldToRaster.transform(pt, 0, pt, 0, 1); + int x = (int) Math.round(pt[0]), y = (int) Math.round(pt[1]); + if (Math.abs(pt[0] - x) > 1e-6 || Math.abs(pt[1] - y) > 1e-6) return null; + if (x < 0 + || y < 0 + || x + RasterAccessors.getWidth(window) > RasterAccessors.getWidth(raster) + || y + RasterAccessors.getHeight(window) > RasterAccessors.getHeight(raster)) return null; + return new int[] {x, y}; + } catch (Exception e) { // TransformException, NoninvertibleTransformException + return null; + } + } + public static double getSummaryStats( GridCoverage2D rasterGeom, String statType, int band, boolean excludeNoDataValue) { double[] stats = getSummaryStatsAll(rasterGeom, band, excludeNoDataValue); From 52a71478a9076dc4f594732105f312709b6fec13 Mon Sep 17 00:00:00 2001 From: Vishesh Tarun Modi Date: Mon, 19 Oct 2026 15:20:00 +1100 Subject: [PATCH 2/3] [GH-2409] Fall back to full-extent path for degenerate ROI windows --- .../common/raster/RasterBandAccessors.java | 75 +++++++++---------- 1 file changed, 35 insertions(+), 40 deletions(-) diff --git a/common/src/main/java/org/apache/sedona/common/raster/RasterBandAccessors.java b/common/src/main/java/org/apache/sedona/common/raster/RasterBandAccessors.java index e92f6af42b9..8266f4b34d0 100644 --- a/common/src/main/java/org/apache/sedona/common/raster/RasterBandAccessors.java +++ b/common/src/main/java/org/apache/sedona/common/raster/RasterBandAccessors.java @@ -31,9 +31,9 @@ import org.apache.sedona.common.Functions; import org.apache.sedona.common.utils.RasterUtils; import org.geotools.api.referencing.FactoryException; -import org.geotools.api.referencing.operation.MathTransform2D; import org.geotools.coverage.GridSampleDimension; import org.geotools.coverage.grid.GridCoverage2D; +import org.geotools.geometry.jts.ReferencedEnvelope; import org.locationtech.jts.geom.Geometry; public class RasterBandAccessors { @@ -393,27 +393,32 @@ private static List getStatObjects( String datatype = RasterBandAccessors.getBandType(raster, band); Double noDataValue = RasterBandAccessors.getBandNoDataValue(raster, band); - // CHANGED: rasterize only the part of the raster the geometry covers - // Adding an arbitrary value '150' for the pixels that are under the geometry. - GridCoverage2D rasterizedGeom = - RasterConstructors.asRaster(roi, raster, datatype, allTouched, 150, null, true); + double[] md = RasterAccessors.metadata(raster); + ReferencedEnvelope window = Rasterization.rasterizeGeomExtent(roi, raster, md, allTouched); + int[] offset = null; + if (window != null + && Math.round(window.getWidth() / Math.abs(md[4])) >= 1 + && Math.round(window.getHeight() / Math.abs(md[5])) >= 1) { + offset = windowOffset(raster, md, window); + } + GridCoverage2D rasterizedGeom; int xOffset = 0, yOffset = 0; - if (rasterizedGeom == null) { - // NEW: the geometry does not burn any pixel, so there is nothing to compute over - double[] empty = new double[0]; - return Arrays.asList(new DescriptiveStatistics(empty), empty); - } - int[] offset = windowOffset(raster, rasterizedGeom); // NEW - if (offset == null) { - // NEW: fall back to the full-extent path when the window cannot be placed exactly + if (offset != null) { + // Adding an arbitrary value '150' for the pixels that are under the geometry. rasterizedGeom = - RasterConstructors.asRasterWithRasterExtent(roi, raster, datatype, allTouched, 150, null); - } else { + RasterConstructors.asRaster(roi, raster, datatype, allTouched, 150, null, true); + if (rasterizedGeom == null) { + // the geometry burns no pixel: same result as an all-zero full-extent raster + double[] empty = new double[0]; + return Arrays.asList(new DescriptiveStatistics(empty), empty); + } xOffset = offset[0]; yOffset = offset[1]; + } else { + rasterizedGeom = + RasterConstructors.asRasterWithRasterExtent(roi, raster, datatype, allTouched, 150, null); } - Raster rasterizedData = RasterUtils.getRaster(rasterizedGeom.getRenderedImage()); int width = RasterAccessors.getWidth(rasterizedGeom), height = RasterAccessors.getHeight(rasterizedGeom); @@ -455,30 +460,20 @@ private static List getStatObjects( * Returns {x, y}: the position of the window's top-left pixel inside the raster, or null if the * window is not exactly aligned to the raster's pixel grid or does not fit inside it. */ - private static int[] windowOffset(GridCoverage2D raster, GridCoverage2D window) { - try { - MathTransform2D windowToWorld = - window - .getGridGeometry() - .getGridToCRS2D(org.geotools.api.metadata.spatial.PixelOrientation.CENTER); - MathTransform2D worldToRaster = - raster - .getGridGeometry() - .getGridToCRS2D(org.geotools.api.metadata.spatial.PixelOrientation.CENTER) - .inverse(); - double[] pt = {0, 0}; // centre of the window's first pixel - windowToWorld.transform(pt, 0, pt, 0, 1); - worldToRaster.transform(pt, 0, pt, 0, 1); - int x = (int) Math.round(pt[0]), y = (int) Math.round(pt[1]); - if (Math.abs(pt[0] - x) > 1e-6 || Math.abs(pt[1] - y) > 1e-6) return null; - if (x < 0 - || y < 0 - || x + RasterAccessors.getWidth(window) > RasterAccessors.getWidth(raster) - || y + RasterAccessors.getHeight(window) > RasterAccessors.getHeight(raster)) return null; - return new int[] {x, y}; - } catch (Exception e) { // TransformException, NoninvertibleTransformException - return null; - } + private static int[] windowOffset(GridCoverage2D raster, double[] md, ReferencedEnvelope window) { + // md: 4 = scaleX, 5 = scaleY, 6/7 = skew, 2/3 = raster width/height + if (md[6] != 0 || md[7] != 0) return null; // skewed: use the full-extent path + double sx = Math.abs(md[4]), sy = Math.abs(md[5]); + ReferencedEnvelope re = raster.getEnvelope2D(); + double fx = (window.getMinX() - re.getMinX()) / sx; + // bottom-up rasters (scaleY > 0) put row 0 at the minimum Y + double fy = + md[5] > 0 ? (window.getMinY() - re.getMinY()) / sy : (re.getMaxY() - window.getMaxY()) / sy; + int x = (int) Math.round(fx), y = (int) Math.round(fy); + int w = (int) Math.round(window.getWidth() / sx), h = (int) Math.round(window.getHeight() / sy); + if (Math.abs(fx - x) > 1e-6 || Math.abs(fy - y) > 1e-6) return null; + if (x < 0 || y < 0 || x + w > (int) md[2] || y + h > (int) md[3]) return null; + return new int[] {x, y}; } public static double getSummaryStats( From 8e879100c7c99b82af6cc2b026a85d921bac4b17 Mon Sep 17 00:00:00 2001 From: Vishesh Tarun Modi Date: Wed, 21 Oct 2026 18:53:08 +1100 Subject: [PATCH 3/3] [GH-2409] Add tests for zonal stats over a clipped window Cover a small polygon on a larger raster (top-down and bottom-up), a polygon partly outside the raster, nodata exclusion inside the window, and a polygon that only touches the raster boundary. --- .../raster/RasterBandAccessorsTest.java | 71 +++++++++++++++++++ 1 file changed, 71 insertions(+) diff --git a/common/src/test/java/org/apache/sedona/common/raster/RasterBandAccessorsTest.java b/common/src/test/java/org/apache/sedona/common/raster/RasterBandAccessorsTest.java index 4ad00cc80a6..8c99c620deb 100644 --- a/common/src/test/java/org/apache/sedona/common/raster/RasterBandAccessorsTest.java +++ b/common/src/test/java/org/apache/sedona/common/raster/RasterBandAccessorsTest.java @@ -868,4 +868,75 @@ public void testCountWithSignedZeroNoData() throws FactoryException { assertEquals(2, RasterBandAccessors.getCount(raster, 1, true)); assertEquals(4, RasterBandAccessors.getCount(raster, 1, false)); } + + // 10x10 raster over [0,10] x [0,10]; the pixel at row r, column c holds r * 10 + c + 1. + private static GridCoverage2D rowMajorRaster() throws FactoryException { + double[] values = new double[100]; + for (int i = 0; i < values.length; i++) { + values[i] = i + 1; + } + return RasterConstructors.makeNonEmptyRaster( + 1, "d", 10, 10, 0, 10, 1, -1, 0, 0, 0, new double[][] {values}); + } + + private static void assertZonalWindow( + Double[] stats, + double count, + double sum, + double mean, + double median, + double min, + double max) { + assertEquals(count, stats[0].doubleValue(), 0d); + assertEquals(sum, stats[1].doubleValue(), FP_TOLERANCE); + assertEquals(mean, stats[2].doubleValue(), FP_TOLERANCE); + assertEquals(median, stats[3].doubleValue(), FP_TOLERANCE); + assertEquals(min, stats[7].doubleValue(), 0d); + assertEquals(max, stats[8].doubleValue(), 0d); + } + + @Test + public void testZonalStatsSmallPolygonOnLargerRaster() throws Exception { + GridCoverage2D raster = rowMajorRaster(); + // covers rows 2-4 and columns 2-4: values 23-25, 33-35, 43-45 + Geometry geom = Constructors.geomFromWKT("POLYGON ((2 8, 5 8, 5 5, 2 5, 2 8))", 0); + // the same result for a top-down and a bottom-up raster, with and without allTouched + for (GridCoverage2D r : new GridCoverage2D[] {raster, flipVerticallyPixelSpace(raster)}) { + for (boolean allTouched : new boolean[] {false, true}) { + assertZonalWindow( + RasterBandAccessors.getZonalStatsAll(r, geom, 1, allTouched), 9, 306, 34, 34, 23, 45); + } + } + } + + @Test + public void testZonalStatsPolygonPartlyOutsideRaster() throws Exception { + GridCoverage2D raster = rowMajorRaster(); + // only x in [8, 10] is inside the raster: columns 8-9, rows 2-4 (29, 30, 39, 40, 49, 50) + Geometry geom = Constructors.geomFromWKT("POLYGON ((8 8, 13 8, 13 5, 8 5, 8 8))", 0); + for (GridCoverage2D r : new GridCoverage2D[] {raster, flipVerticallyPixelSpace(raster)}) { + assertZonalWindow( + RasterBandAccessors.getZonalStatsAll(r, geom, 1, false), 6, 237, 39.5, 39.5, 29, 50); + } + } + + @Test + public void testZonalStatsNoDataInsideClippedWindow() throws Exception { + // the centre pixel of the 3x3 block (34) is nodata + GridCoverage2D raster = RasterBandEditors.setBandNoDataValue(rowMajorRaster(), 1, 34d); + Geometry geom = Constructors.geomFromWKT("POLYGON ((2 8, 5 8, 5 5, 2 5, 2 8))", 0); + assertZonalWindow( + RasterBandAccessors.getZonalStatsAll(raster, geom, 1, false, true), 8, 272, 34, 34, 23, 45); + assertEquals(9d, RasterBandAccessors.getZonalStatsAll(raster, geom, 1, false, false)[0], 0d); + } + + @Test + public void testZonalStatsPolygonOnlyTouchingRasterBoundary() throws Exception { + GridCoverage2D raster = rowMajorRaster(); + // shares only the raster's right edge, so it covers no pixel + Geometry geom = Constructors.geomFromWKT("POLYGON ((10 8, 12 8, 12 5, 10 5, 10 8))", 0); + for (boolean allTouched : new boolean[] {false, true}) { + assertEquals(0d, RasterBandAccessors.getZonalStatsAll(raster, geom, 1, allTouched)[0], 0d); + } + } }