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..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 @@ -33,6 +33,7 @@ import org.geotools.api.referencing.FactoryException; 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 { @@ -391,16 +392,41 @@ private static List getStatObjects( Raster rasterData = RasterUtils.getRaster(raster.getRenderedImage()); String datatype = RasterBandAccessors.getBandType(raster, band); Double noDataValue = RasterBandAccessors.getBandNoDataValue(raster, band); - // Adding an arbitrary value '150' for the pixels that are under the geometry. - GridCoverage2D rasterizedGeom = - RasterConstructors.asRasterWithRasterExtent(roi, raster, datatype, allTouched, 150, null); + + 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 (offset != null) { + // Adding an arbitrary value '150' for the pixels that are under the geometry. + rasterizedGeom = + 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); 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 +456,26 @@ 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, 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( GridCoverage2D rasterGeom, String statType, int band, boolean excludeNoDataValue) { double[] stats = getSummaryStatsAll(rasterGeom, band, excludeNoDataValue); 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); + } + } }