Skip to content

Use GEOSGridIntersectionFractions_r() directly in st_interpolate_aw - #2624

Open
edzer wants to merge 21 commits into
mainfrom
aw
Open

edzer wants to merge 21 commits into
mainfrom
aw

Conversation

@edzer

@edzer edzer commented Sep 16, 2026

Copy link
Copy Markdown
Member

st_interpolate_aw() is for area-weighted interpolation, estimating attribute values from geometry set A to an arbitrary geometry set B, by using averaging (intensive variables) or summing/redistributing (extensive variables). The naive implementation computes all A-B intersections, and uses their areas for weighting. Since GEOS 3.14, GEOSGridIntersectionFractions_r (migrated from @dbaston's exactextracter) computes such weights much more efficiently in case A or B is (regularly) gridded; and tbh that is probably a very common, if not dominant, use case. The current PR implements this both for x (source geoms) being a regularly gridded stars object, as well as to (target geoms).

The st_interpolated_aw.stars() has been added to sf in the current CRAN release for that reason, and needs to be removed from stars (which happened in r-spatial/stars@50ad7e8).

@edzer

edzer commented Sep 16, 2026

Copy link
Copy Markdown
Member Author

@dbaston when doing so, I discovered that when calling GEOSGridIntersectionFractions_r repeatedly (once for every geometry), I had to set the float output buffer values all to zero before every call; cells not intersecting seem to keep their old value. it would be good if this went into the docs, or got fixed.

Comment thread src/geos.cpp
Rcpp::NumericVector ret(ncell * g.size());
for (int i = 0; i < (int) g.size(); i++) {
for (int j = 0; j < ncell; j++)
buf[j] = 0.0; // initialize, needed for i > 0!

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@dbaston found out the hard way

@dbaston

dbaston commented Sep 16, 2026

Copy link
Copy Markdown
Contributor

cells not intersecting seem to keep their old value

It's actually cells outside the geometry's bounding box that keep their old value. This behavior is wrong, and a fix is in libgeos/geos#1532

Still, you may want to adjust your usage to crop the raster down to each bbox before the call. Otherwise, a lot of effort is spent copying zeros around.

Comment thread src/geos.cpp Outdated
edzer and others added 3 commits September 16, 2026 13:44
Co-authored-by: Dan Baston <dbaston@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants