Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
36 commits
Select commit Hold shift + click to select a range
12bc8a1
update
edzer Sep 10, 2026
88f91d8
Merge branch 'main' into aw
edzer Sep 10, 2026
7105094
use GEOSGridIntersectionFractions_r in st_interpolate_aw()
edzer Sep 11, 2026
f0f431d
fix
edzer Sep 11, 2026
55745e6
omit create_dimension()
edzer Sep 11, 2026
63abe32
fix dimensions
edzer Sep 11, 2026
4a42b5b
fix raster
edzer Sep 11, 2026
6305d3d
add interpolate_aw(sf, stars)
edzer Sep 14, 2026
ba59b67
add interpolate_aw for sf, stars
edzer Sep 14, 2026
dcc4eea
typo
edzer Sep 14, 2026
fb0a866
set NAs, scale
edzer Sep 14, 2026
7b95ee0
name
edzer Sep 14, 2026
5778626
extensive
edzer Sep 15, 2026
535f3b7
extensive
edzer Sep 15, 2026
a263ddc
use cell area
edzer Sep 15, 2026
6ff58c7
fix dimensions
edzer Sep 15, 2026
0c3d686
fix dimension
edzer Sep 15, 2026
68598c0
set dimensions
edzer Sep 15, 2026
6bf471d
Update src/geos.cpp
edzer Sep 16, 2026
7fe6b3e
drop units
edzer Sep 16, 2026
5025851
tidy; add warnings;
edzer Sep 16, 2026
7094fc0
move warning
edzer Sep 17, 2026
1787388
Merge branch 'main' into aw
edzer Sep 17, 2026
f106150
update aw interpolation
edzer Sep 28, 2026
a77c43b
Merge branch 'main' into aw
edzer Oct 9, 2026
340bcc7
Merge branch 'main' into aw
edzer Oct 18, 2026
54147fe
add last 4; #2632
edzer Oct 19, 2026
ea7e6f2
Merge branch 'main' into aw
edzer Oct 19, 2026
2337a05
add fast raster-raster (stars) st_interpolate_aw path
edzer Oct 19, 2026
a1df089
tidy
edzer Oct 19, 2026
264a1e8
Merge branch 'main' into aw
edzer Oct 21, 2026
6289e13
Merge branch 'main' into aw
edzer Oct 26, 2026
ef2d630
Merge branch 'main' into aw
edzer Oct 28, 2026
66b12b0
changes due to new autoconf version
edzer Nov 10, 2026
500cfa3
Merge branch 'main' into aw
edzer Nov 10, 2026
44b2841
add tests and several fixes
edzer Nov 19, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion NEWS.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
# version 1.1-4

* add `TIN`, `POLYHEDRALSURFACE` and `TRIANGLE` to vctrs methods; #2632
* `st_intersection()` becomes sensitive to setting `dimensions = "polygon"` (`"lines"`) to only have polygons (lines) returned, also for the planar case.

* optimize `st_interpolate_aw()` for regular gridded source or target geometries (using `GEOS::GEOSGridIntersectionFractions()` which requires GEOS >= 3.14); #2624, and also for the case where both `x` and `to` are regular or rectilinear (`stars`) rasters

* add `TIN`, `POLYHEDRALSURFACE`, `TRIANGLE`, `CIRCULARSTRING`, `COMPOUNDCURVE`, `CURVE`, and `MULTICURVE` to vctrs methods; #2632

* `st_combine()` preserves the precision of input object; #2618

Expand Down
8 changes: 6 additions & 2 deletions R/RcppExports.R
Original file line number Diff line number Diff line change
Expand Up @@ -233,8 +233,8 @@ CPL_geos_voronoi <- function(sfc, env, dTolerance = 0.0, bOnlyEdges = 1L) {
.Call(`_sf_CPL_geos_voronoi`, sfc, env, dTolerance, bOnlyEdges)
}

CPL_geos_op2 <- function(op, sfcx, sfcy) {
.Call(`_sf_CPL_geos_op2`, op, sfcx, sfcy)
CPL_geos_op2 <- function(op, sfcx, sfcy, min_dimension = 0L) {
.Call(`_sf_CPL_geos_op2`, op, sfcx, sfcy, min_dimension)
}

CPL_geos_dist_by_element <- function(sfc0, sfc1, which, par) {
Expand Down Expand Up @@ -281,6 +281,10 @@ CPL_line_interpolate <- function(lines, dists, normalized) {
.Call(`_sf_CPL_line_interpolate`, lines, dists, normalized)
}

CPL_grid_intersection_fractions <- function(p, geoms) {
.Call(`_sf_CPL_grid_intersection_fractions`, p, geoms)
}

CPL_hex_to_raw <- function(cx) {
.Call(`_sf_CPL_hex_to_raw`, cx)
}
Expand Down
194 changes: 166 additions & 28 deletions R/aggregate.R
Original file line number Diff line number Diff line change
Expand Up @@ -90,20 +90,22 @@ aggregate.sf = function(x, by, FUN, ..., do_union = TRUE, simplify = TRUE,
}
}

#' Area-weighted interpolation or dasymetric mapping of polygon data
#' Area-weighted interpolation (conservative regridding) or dasymetric mapping
#'
#' Area-weighted interpolation or dasymetric mapping of polygon data
#' Area-weighted interpolation (conservative regridding) or dasymetric mapping
#' @name interpolate_aw
#' @param x object of class \code{sf}, for which we want to aggregate attributes
#' @param to object of class \code{sf} or \code{sfc}, with the target geometries
#' @param extensive logical; if TRUE, the attribute variables are assumed to be spatially extensive (like population) and the sum is preserved, otherwise, spatially intensive (like population density) and the mean is preserved.
#' @param x object of class \code{sf} or \code{stars}, for which we want to aggregate attributes
#' @param to object of class \code{sf}, \code{sfc} or \code{stars}, with the target geometries
#' @param extensive logical; if TRUE, the attribute variables are assumed to be spatially extensive (like population) and their sum is preserved, otherwise, spatially intensive (like population density) and their mean is preserved.
#' @param na.rm logical; if `TRUE` remove features with `NA` attributes from `x` before interpolating
#' @param ... ignored
#' @param keep_NA logical; if \code{TRUE}, return all features in \code{to}, if \code{FALSE} return only those with non-NA values (but with \code{row.names} the index corresponding to the feature in \code{to})
#' @param include_non_intersected logical; for the case when `extensive=FALSE`, when set to `TRUE` divide by the target areas (including non-intersected areas),
#' when `FALSE` divide by the sum of the source areas.
#' @param weights character; name of column in `to` that indicates (extensive) weights, to be used instead of areas, for redistributing attributes in `x`; currently only works for `extensive=TRUE`.
#' @details if `extensive` is `TRUE` and `na.rm` is set to `TRUE`, geometries with `NA` are effectively treated as having zero attribute values. Dasymetric mapping is obtained when `weights` are specified.
#'
#' Handling of gridded data (\code{stars} objects) is efficient when GEOS >= 3.14
#' @examples
#' # example Area-weighted interpolation:
#' nc = st_read(system.file("shape/nc.shp", package="sf"))
Expand Down Expand Up @@ -152,7 +154,20 @@ st_interpolate_aw = function(x, to, extensive, ...) UseMethod("st_interpolate_aw
st_interpolate_aw.sf = function(x, to, extensive, ..., keep_NA = FALSE, na.rm = FALSE,
include_non_intersected = FALSE, weights = character(0)) {

if (!inherits(to, "sf") && !inherits(to, "sfc")) {
if (inherits(to, "stars") && length(weights) == 0) { # use S7 multiple dispatch instead?
if (! requireNamespace("stars", quietly = TRUE))
stop("package stars required, please install it first")
if (stars::st_raster_type(to) == "regular" &&
compareVersion(gsub("[a-zA-Z].+$", "", sf_extSoftVersion()[["GEOS"]]), "3.14.0") > -1) {
return(interpolate_aw_sf_stars(x, to, extensive, ..., keep_NA = keep_NA, na.rm = na.rm,
include_non_intersected = include_non_intersected))
}
}

if (! all_constant(x))
warning("st_interpolate_aw assumes attributes are constant or uniform over areas of x")

if (!inherits(to, c("sf", "sfc"))) {
to <- try(st_as_sf(to))
if (inherits(to, "try-error"))
stop("st_interpolate_aw requires geometries in argument to")
Expand All @@ -161,12 +176,10 @@ st_interpolate_aw.sf = function(x, to, extensive, ..., keep_NA = FALSE, na.rm =
x = x[! apply(is.na(x), 1, any),]

if (length(weights)) {
stopifnot(length(weights) == 1, is.character(weights), inherits(to, "sf"), weights %in% names(to))
stopifnot(length(weights) == 1, is.character(weights), inherits(to, c("sf", "stars")), weights %in% names(to))
return(dasymetric(x, to[weights], extensive, keep_NA, include_non_intersected))
}

if (! all_constant(x))
warning("st_interpolate_aw assumes attributes are constant or uniform over areas of x")
i = st_intersection(st_geometry(x), st_geometry(to), dimensions = "polygon")
idx = attr(i, "idx")

Expand Down Expand Up @@ -199,38 +212,158 @@ st_interpolate_aw.sf = function(x, to, extensive, ..., keep_NA = FALSE, na.rm =
x_st$...area_t = merge(data.frame(idx = idx[,2]), df)$area
lapply(x_st, function(v) v * x_st$...area_st / x_st$...area_t)
}
x_st = aggregate(x_st, list(idx[,2]), sum)
df = if (keep_NA) {
ix = rep(NA_integer_, length(to))
ix[x_st$Group.1] = seq_along(x_st$Group.1)
st_sf(x_st[ix,], geometry = st_geometry(to))
} else
st_sf(x_st, geometry = st_geometry(to)[x_st$Group.1], row.names = x_st$Group.1)
to.g = st_geometry(to)
if (length(x_st[[1]])) {
x_st = aggregate(x_st, list(idx[,2]), sum) # converts x_st into a data.frame
df = if (keep_NA) {
ix = rep(NA_integer_, length(to.g))
ix[x_st$Group.1] = seq_along(x_st$Group.1)
st_sf(x_st[ix,], geometry = to.g)
} else
st_sf(x_st, geometry = to.g[x_st$Group.1], row.names = x_st$Group.1)
} else {
ix = rep(NA_integer_, length(to.g))
df = st_sf(data.frame(x_st)[ix,], geometry = to.g)
}
# clean up:
df$...area_t = df$...area_st = df$...area_s = df$Group.1 = NULL
st_set_agr(df, "aggregate")
}

# compute the intersection fraction (of a) of pairs of stars raster cells
intersection_fraction = function(st_a, st_b) {
ord = function(d) {
xo = if (d[[1]]$delta < 0) c(3,1) else c(1,3) # x-order small-large
yo = if (d[[2]]$delta < 0) c(4,2) else c(2,4) # y-order small-large
c(xo, yo)
}
a = st_coordinates(st_a, add_max = TRUE)[, ord(da <- stars::st_dimensions(st_a))]
b = st_coordinates(st_b, add_max = TRUE)[, ord(stars::st_dimensions(st_b))]
i = rep(seq_len(nrow(a)), nrow(b))
j = rep(seq_len(nrow(b)), each = nrow(a))
ovx = ifelse(a[i,1] > b[j,2] | a[i,2] < b[j,1], 0, pmin(a[i,2], b[j,2])- pmax(a[i,1],b[j,1]))
ovy = ifelse(a[i,3] > b[j,4] | a[i,4] < b[j,3], 0, pmin(a[i,4], b[j,4])- pmax(a[i,3],b[j,3]))
matrix(ovx * ovy, nrow(a), nrow(b)) / abs(da[[1]]$delta * da[[2]]$delta) # / cellsize(st_a)
}

#' @name interpolate_aw
#' @export
st_interpolate_aw.stars = function(x, to, extensive, ...) {
if (! requireNamespace("stars", quietly = TRUE))
stop("package stars required, please install it first")
ret = st_interpolate_aw(st_as_sf(x), to, extensive, ...)
geom = attr(ret, "sf_column")
dx = dim(x)
if (length(dx) > 2 && length(x) == 1 && length(ret) > 2) {
ret = merge(stars::st_as_stars(ret))
nd = names(stars::st_dimensions(x))
ret = stars::st_set_dimensions(ret, seq_along(dx),
names = c(geom, paste0(nd[-(1:2)], collapse = ".")))
setNames(ret, names(x))
} else

stopifnot(st_crs(x) == st_crs(to))

weigh = function(a, w, extensive) {
d = dim(a)
dim(a) = c(prod(d[1:2]), prod(d[-(1:2)]))
ret = structure(t(w) %*% a, dim = c(ncol(w), ifelse(length(d) <= 2, 1, d[-(1:2)])))
cs = colSums(w)
ret[cs == 0.,] = NA
if (! extensive)
ret = ret / cs
ret
}

if (inherits(to, "stars") && stars::st_raster_type(to) %in% c("regular", "rectilinear") &&
stars::st_raster_type(x) %in% c("regular", "rectilinear")) {
w = intersection_fraction(x, to)
ret = lapply(x, weigh, w, extensive)
ret = lapply(ret, structure, dim = dim(to))
stars::st_as_stars(ret, dimensions = stars::st_dimensions(to))
} else if (stars::st_raster_type(x) == "regular" &&
compareVersion(gsub("[a-zA-Z].+$", "", sf_extSoftVersion()[["GEOS"]]), "3.14.0") > -1) {
if (isTRUE(st_is_longlat(x)))
warning("for longitude/latitude data and gridded geometry, st_interpolate_aw computes intersections assuming Cartesian coordinates; use st_as_sf(x) if this is not wanted")
# check x and y are first two dimensions:
if (!identical(match(attr(stars::st_dimensions(x), "raster")$dimensions, names(dim(x))), 1:2))
stop("raster dimensions need to be at position 1 and 2; use aperm to rearrange")
# we HAVE_GEOS_3_14_0
if (!inherits(to, c("sf", "sfc"))) {
to <- try(st_as_sf(to))
if (inherits(to, "try-error"))
stop("st_interpolate_aw requires geometries in argument to")
}
if (stars::st_dimensions(x)[[2]]$delta > 0)
stop("only implemented for negative N-S cellsize")
w = CPL_grid_intersection_fractions(c(st_bbox(x), dim(x)[1:2]), st_geometry(to))
ret = lapply(x, weigh, w, extensive)
if (length(dim(x)) == 2) { # return sf object
sf = st_sf(a = as.vector(ret), geom = st_geometry(to))
names(sf)[1] = names(x)[1]
sf
} else {
dm = stars::st_dimensions(x)
dm[[1]] = NULL
attr(dm, "raster")$dimensions = c(NA_character_, NA_character_)
g = st_geometry(to)
# this is ugly, but stars does not export stars:::create_dimension():
dm[[1]] = structure(list(from = 1L, to = length(g), offset = NA_real_, delta = NA_real_,
refsys = st_crs(g), point = any(st_dimension(g) > 0), values = g), class = "dimension")
names(dm)[1] = "geometry"
if (length(dm) == 1L)
ret = lapply(ret, function(v) structure(as.vector(v), dim = nrow(v)))
stars::st_as_stars(ret, dimensions = dm)
}
} else { # convert stars to sf...
ret = st_interpolate_aw(st_as_sf(x), to, extensive, ...)
geom = attr(ret, "sf_column")
dx = dim(x)
if (length(dx) > 2 && length(x) == 1 && length(ret) > 2) {
ret = merge(stars::st_as_stars(ret))
nd = names(stars::st_dimensions(x))
ret = stars::st_set_dimensions(ret, seq_along(dx),
names = c(geom, paste0(nd[-(1:2)], collapse = ".")))
setNames(ret, names(x))
} else
ret
}
}

interpolate_aw_sf_stars = function(x, to, extensive, ..., keep_NA = keep_NA, na.rm = na.rm,
include_non_intersected = include_non_intersected) {

# todo: deal with include_non_intersected...
stopifnot(inherits(to, "stars"), inherits(x, "sf"), st_crs(x) == st_crs(to))
if (isTRUE(st_is_longlat(x)))
warning("for longitude/latitude data and gridded geometry, st_interpolate_aw computes intersections assuming Cartesian coordinates; use st_as_sf(to) if this is unwanted")

# check x and y are first two dimensions:
if (!identical(match(attr(stars::st_dimensions(to), "raster")$dimensions, names(dim(to))), 1:2))
stop("raster dimensions of to need to be at position 1 and 2; use aperm to rearrange")
if (stars::st_dimensions(to)[[2]]$delta > 0)
stop("only implemented for negative N-S cellsize")
w = CPL_grid_intersection_fractions(c(st_bbox(to), dim(to)), st_geometry(x)) # n_cells x n_geoms
g = st_geometry(x)
x = as.matrix(st_set_geometry(x, NULL)) # n_geoms x n_attributes
rs = rowSums(w)
ret = if (extensive) {
cellsize = as.vector(st_area(to)[[1]])
if (inherits(cellsize, "units"))
cellsize = units::drop_units(cellsize)
w %*% (x / st_area(g)) * cellsize # n_cells x n_attributes
} else
w %*% x # n_cells x n_attributes
dim(ret) = c(nrow(w), ncol(x)) # needed for the case of ncol(x) == 1
ret[rs == 0.0, ] = NA
if (!extensive)
ret = ret / rs

# redimension:
dm = stars::st_dimensions(to)[1:2]
if (ncol(x) > 1) {
dim(ret) = c(dim(to)[1:2], ncol(x))
dm[["attribute"]] = structure(list(from = 1L, to = ncol(x), offset = NA_real_, delta = NA_real_,
refsys = NA_character_, point = any(st_dimension(g) > 0),
values = dimnames(x)[[2]]), class = "dimension")
} else
dim(ret) = dim(to)[1:2]
stars::st_as_stars(list(attributes = ret), dimensions = dm)
}

dasymetric = function(x, to, extensive, keep_NA, include_non_intersected) {
stopifnot(isTRUE(extensive), !keep_NA, !include_non_intersected) # later...
# stopifnot(isTRUE(extensive), !keep_NA, !include_non_intersected) # later...
stopifnot(isTRUE(extensive), !include_non_intersected) # later...
stopifnot(length(to) == 2)
if (!inherits(to[[2]], "sfc"))
to = to[2:1] # swap: geom last
Expand Down Expand Up @@ -275,7 +408,12 @@ dasymetric = function(x, to, extensive, keep_NA, include_non_intersected) {
x = do.call(rbind, spl)
# sum over the target regions:
# x = aggregate(x, list(idx[,2]), sum)
x = aggregate(x, list(idx2), sum)
if (length(x[[1]]))
x = aggregate(x, list(idx2), sum)
else {
x = data.frame(x)
x$Group.1 = integer(0)
}
df = if (keep_NA) {
ix = rep(NA_integer_, length(to))
ix[x$Group.1] = seq_along(x$Group.1)
Expand Down
20 changes: 14 additions & 6 deletions R/geom-transformers.R
Original file line number Diff line number Diff line change
Expand Up @@ -862,7 +862,7 @@ geos_op2_df = function(x, y, geoms) {
# after checking identical crs,
# call geos_op2 function op on x and y:
# DE-9IM compliant should use model = "closed", more robust seems:
geos_op2_geom = function(op, x, y, ..., by_element = FALSE, model = "semi-open") {
geos_op2_geom = function(op, x, y, ..., by_element = FALSE, model = "semi-open", min_dimensions = 0L) {
stopifnot(st_crs(x) == st_crs(y))
x = st_geometry(x)
y = st_geometry(y)
Expand All @@ -887,7 +887,7 @@ geos_op2_geom = function(op, x, y, ..., by_element = FALSE, model = "semi-open")
sym_difference = s2::s2_sym_difference,
union = s2::s2_union, stop("invalid operator"))
# to be optimized -- this doesn't index on y:
lst = structure(unlist(lapply(y, function(yy) fn(x, yy, s2::s2_options(model = model, ...))),
lst = structure(unlist(lapply(y, function(yy) fn(x, yy, s2::s2_options(model = model, ...))), # absorbs the dimensions="polygon"
recursive = FALSE), class = "s2_geography")
e = s2::s2_is_empty(lst)
idx = cbind(rep(seq_along(x), length(y)), rep(seq_along(y), each = length(x)))
Expand All @@ -896,7 +896,7 @@ geos_op2_geom = function(op, x, y, ..., by_element = FALSE, model = "semi-open")
} else {
if (longlat)
message_longlat(paste0("st_", op))
st_sfc(CPL_geos_op2(op, x, y), crs = st_crs(x))
st_sfc(CPL_geos_op2(op, x, y, min_dimensions), crs = st_crs(x))
}
}
}
Expand Down Expand Up @@ -967,8 +967,16 @@ st_intersection.sfc = function(x, y, ...) {
message_longlat("st_intersection")
ret = CPL_nary_intersection(x)
structure(st_sfc(ret), idx = attr(ret, "idx"))
} else
geos_op2_geom("intersection", x, y, ...)
} else {
dots = list(...)
min_dimensions = if (!is.null(dots$dimensions) && dots$dimensions == "polygon")
2L
else if (!is.null(dots$dimensions) && dots$dimensions %in% c("line", "lines", "polyline"))
1L
else
0L
geos_op2_geom("intersection", x, y, ..., min_dimensions = min_dimensions)
}
}

#' @name geos_binary_ops
Expand All @@ -987,7 +995,7 @@ st_intersection.sf = function(x, y, ...) {
x[[ sf_column ]] = structure(geom, idx = NULL)
st_sf(x)
} else
geos_op2_df(x, y, geos_op2_geom("intersection", x, y, ...))
geos_op2_df(x, y, st_intersection(st_geometry(x), st_geometry(y), ...))
}

#' @name geos_binary_ops
Expand Down
Loading
Loading