【问题标题】:Optimise code to split large vector into smaller files?优化代码以将大向量拆分为较小的文件?
【发布时间】:2023-01-17 08:37:04
【问题描述】:

在我下面的玩具/示例代码中,我制作了一个覆盖世界的网格,然后使用此网格将一个大型复杂的全球数据集拆分为每个网格单元格的一个文件。在我的实际工作中,这是一个瓶颈,需要很长时间。我会很感激一些关于优化它的想法和想法。我通过利用并行处理取得了一些成功,但我也认为它可以做得“更聪明”。

library("sf")
library("terra")
library("glue")
library("rnaturalearth")
library("tidyverse")

dir.create("tmp")

ogr2ogr_path <- "C://Program Files//QGIS 3.26.1//bin//ogr2ogr.exe"

## Make some grid cells
world_grid <-  rast(nrows=1, ncols=1, xmin=-180, xmax=180, ymin=-90, ymax=90, crs="epsg:4326") %>%
                st_bbox() %>%
                st_as_sfc() %>%
                st_make_grid(cellsize = 10) %>%
                st_as_sf()

make_grid_cells <- function(grid_id, world_grid) {
    output_name <- glue("tmp/polygon_{grid_id}.gpkg")
    st_write(world_grid[grid_id,],
            output_name,
            append = FALSE,
            quiet = TRUE)
    return(output_name)
}

grid_cell <- lapply(1:nrow(world_grid), make_grid_cells, world_grid = world_grid)

## Get some sample data
ne_countries(type = "countries", scale = "large", returnclass = "sf") %>% 
            select(iso_a2) %>%
            st_write("tmp/world_polygons.gpkg")

## Split the worldwide data into tiles
split_world_to_tiles <- function(tile_template_area, worldwide_data) {
    output_name <- gsub("polygon", "worldwide_poly", tile_template_area)
    grid_poly <- st_read(tile_template_area, quiet=T)
    box <- grid_poly %>% st_bbox()
    command <- glue('{double_quote("C://Program Files//QGIS 3.26.1//bin//ogr2ogr.exe")} -spat {box$xmin} {box$ymin} {box$xmax} {box$ymax} -clipsrc spat_extent -f GPKG {output_name} {worldwide_data} -nlt GEOMETRYCOLLECTION')
    system(command)
}

split_worldwide_data <- lapply(grid_cell, split_world_to_tiles, worldwide_data = "tmp/world_polygons.gpkg")

【问题讨论】:

    标签: r gis sf terra


    【解决方案1】:

    如果您使用不同的文件格式,您似乎可以获得更多的里程。

    library(terra)
    dir.create("tmp", FALSE, FALSE)
    d <- file.remove(list.files("tmp", full=TRUE))
    
    wrldgrid <- as.polygons(rast(res=10))
    
    write_cells <- function(wgrid, format=".gpkg") {
        nr <- nrow(wgrid)
        outf <- paste0("tmp/polygon_", 1:nr, format)
        for (i in 1:nr) {
            writeVector(wgrid[i,], outf[i])
        }
        invisible(outf)
    }
    
    system.time(f <- write_cells(wrldgrid))
    #   user  system elapsed 
    #   5.03   13.89   24.70 
    
    system.time(f <- write_cells(wrldgrid, ".shp"))
    #   user  system elapsed 
    #   1.97    3.15    9.86 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      相关资源
      最近更新 更多