在大型数据集上加速 st_crop(sf 包)的方法

Erv*_*van 2 r spatial data.table r-sf

我需要从不同的 shapefile 中提取大约 4 个 1 公顷的 mio 网格单元的信息。目前,我在所有单元格的 for 循环中的每一层上使用 st_crop,但这将永远运行。我想加快使用“data.table”(DT)排序方式按坐标裁剪 shapefile 的过程。让我们考虑下面的示例,我正在寻找感兴趣区域中多边形边缘的范围:

require(sf)
require(data.table)
require(ggplot2)
require(tidyverse)

# load shapefile
nc = st_read(system.file("shape/nc.shp", package="sf"))


# Define a bounding-box that mimic a mowing-window or area of interest
bb <- st_bbox(c(xmin= -79, xmax=-78,ymin= 34.5, ymax= 35.5))


# Commute 'nc' into some sort of data.table object for fast subsetting, in preserving object's integrity (i.e. same id to all points of a given polygon)
nobs <- mapview::npts(nc,by_feature=T)
NC <- data.table::data.table(id=rep(1:nrow(nc),nobs),st_coordinates(nc)[,1:2])
head(NC)

# Compare cropping methods amon
library(microbenchmark)
x = runif(100)
test <- microbenchmark(
  crop_nc <- st_crop(nc,bb),
  crop_NC <- NC[X >= bb[1] & X < bb[3] & Y>= bb[2] & Y < bb[4]]
)  

print(test)
Unit: microseconds
  expr      min       lq      mean   median        uq       max neval cld
 crop_nc  5205.051 5675.807 6837.9472 5903.219 6829.0865 16046.654   100   b
 crop_NC   405.334  528.356  624.8398  576.996  656.9245  1295.361   100  a 
There were 50 or more warnings (use warnings() to see the first 50)
Run Code Online (Sandbox Code Playgroud)

正如预期的那样,子集的 DT 方式更快。现在让我们从我们的 DT 对象回到 sf 对象,如下所示:

crop_NC_sf <- st_as_sf(crop_NC,coords=c("X","Y"),crs=st_crs(nc))  %>% group_by(id)  %>%  summarise(i=mean(id)) %>% st_cast("POLYGON")
Run Code Online (Sandbox Code Playgroud)

现在比较我们研究区域中包含的多边形的周长:

sum(st_length(crop_nc),na.rm=T)
1307555 [m]

sum(st_length(crop_NC_sf),na.rm=T)
2610959 [m]
Run Code Online (Sandbox Code Playgroud)

显然工作得不是很好......

结果

问题:

  • 还有另一种方法可以加速 st_crop()

  • 有没有办法从点重新创建多边形以保留“原始”顺序点相互连接?

Tim*_*bim 5

通过st_intersects(或st_crop)获得正确的交叉点不仅仅是对一堆坐标进行子集化。您将在下面找到一个适用于您的示例的工作解决方案,该解决方案试图回答您的两个问题。

对于问题 1,我建议在裁剪之前识别与 bbox 相交的多边形在许多情况下可以大大加快速度,特别是如果您有很多多边形并且 bbox 的面积与多边形的范围相比较小区域。

关于问题 2,您可以使用包sfheaders,它提供了从 data.frames/data.tables 等创建 sf 对象的方法。

最后,我稍微修改了时序代码,以更好地反映每个步骤需要做什么才能提供类似的输出,从而使比较更加公平。

data.table事情的最终结果是不同的,st_crop因为这种方法只是将坐标子集到bbox内部的坐标,而不是在适当的位置插入bbox的坐标。此操作可能代价高昂,因为我们需要确定这些正确的位置。因此,您将在结果中获得任意形状,甚至可能会破坏,因为您可能会产生无效的几何形状。

一般来说,我会坚持这种st_crop方法,这可能会在以后为您省去麻烦。如果您感兴趣的区域很大,有很多多边形,并且您使用的 bbox 相对于整个区域很小,我希望在进行实际交叉之前识别与 bbox 相交的多边形会加快速度。

library(sf)
#> Linking to GEOS 3.6.1, GDAL 2.2.3, PROJ 4.9.3
library(mapview)
library(data.table)
library(ggplot2)
library(tidyverse)
library(sfheaders)
library(microbenchmark)

# load shapefile
nc = st_geometry(st_read(system.file("shape/nc.shp", package="sf")))
#> Reading layer `nc' from data source `C:\Users\Tim\R\win-library\3.5\sf\shape\nc.shp' using driver `ESRI Shapefile'
#> Simple feature collection with 100 features and 14 fields
#> geometry type:  MULTIPOLYGON
#> dimension:      XY
#> bbox:           xmin: -84.32385 ymin: 33.88199 xmax: -75.45698 ymax: 36.58965
#> epsg (SRID):    4267
#> proj4string:    +proj=longlat +datum=NAD27 +no_defs

# Define a bounding-box that mimic a mowing-window or area of interest
bb <- st_bbox(c(xmin= -79, xmax=-78,ymin= 34.5, ymax= 35.5))
bb_sfc = st_as_sfc(bb)
st_crs(bb_sfc) <- st_crs(nc)


# Commute 'nc' into some sort of data.table object for fast subsetting, in preserving object's integrity (i.e. same id to all points of a given polygon)
nobs <- mapview::npts(nc,by_feature=T)
NC <- data.table::data.table(id=rep(1:length(nc),nobs),st_coordinates(nc)[,1:2])
head(NC)
#>    id         X        Y
#> 1:  1 -81.47276 36.23436
#> 2:  1 -81.54084 36.27251
#> 3:  1 -81.56198 36.27359
#> 4:  1 -81.63306 36.34069
#> 5:  1 -81.74107 36.39178
#> 6:  1 -81.69828 36.47178

# Compare cropping methods amon
test <- microbenchmark(
    sf_way = {
        # identify subset of nc that intersects with bbox
        isec = unlist(st_intersects(bb_sfc, nc))
        crop_nc <- st_crop(nc[isec], bb_sfc)
    }, 
    dt_way = {
        crop_NC <- NC[X >= bb[1] & X < bb[3] & Y>= bb[2] & Y < bb[4]]
        crop_NC_sf <- sfheaders::sf_polygon(crop_NC, "X", "Y", polygon_id = "id")
        st_crs(crop_NC_sf) = st_crs(nc)
    }
)  

print(test)
#> Unit: milliseconds
#>    expr      min       lq     mean   median       uq      max neval cld
#>  sf_way 4.270801 4.492551 4.945424 4.828702 5.051951 8.666301   100   b
#>  dt_way 3.101400 3.442551 3.705610 3.593301 3.887202 8.270801   100  a

sum(st_length(crop_nc),na.rm=T)
#> 1307555 [m]
sum(st_length(crop_NC_sf),na.rm=T)
#> 975793 [m]

mapview(st_bbox(crop_nc)) + crop_NC_sf
Run Code Online (Sandbox Code Playgroud)

reprex 包(v0.3.0)于 2019 年 11 月 29 日创建

  • 根据您想要实现的具体目标,您可能需要开始“跳出框框”思考。例如,我可以使用基于光栅的方法吗?或者您可能想开始考虑建立一个空间数据库并使用 postgis 进行查询。或者尝试直接从控制台使用 GDAL...R 似乎确实不是适合您任务的正确工具。 (2认同)