使用过多内存提取 {raster} 包中的数据

3

我一直在使用raster软件包中的extract函数,使用由shapefile定义的区域从栅格文件中提取数据。但是,我现在遇到了这个过程所需的内存量问题。我有很多shapefile文件(~1000),而栅格文件很大(~1.6gb)。

我的处理方式是:

shp <- mclapply(list.files(pattern="*.shp",full.names=TRUE), readShapePoly,mc.cores=6)
ndvi <- raster("NDVI.dat")
mc<- function(y) {
temp <- gUnionCascaded(y)
extract <- extract(ndvi,temp)
mean <- range(extract, na.rm=T )[1:2]
leng <- length(output)
}
output <- lapply(shp, mc)

我能采取哪些措施来减少内存负载?我尝试加载更少的shapefile,在大约5分钟后它起了作用,但内存再次飙升了。我的电脑是四核2.4GHz,带8GB内存。


不要一次性加载所有文件,而是逐个循环处理shapefile文件。(唉)。-1因为您没有展示相对内存使用情况,尽管您声称extract()有问题。 - mdsumner
顺便说一下,使用mclapply是完全错误的,因为所有文件都在同一磁盘上。 - mdsumner
mc()函数的输出是什么? - mdsumner
1个回答

4
我会这样做(未经测试):
## Clearly we need these packages, and their dependencies
library(raster)
library(rgeos)
shpfiles <- list.files(pattern="*.shp",full.names=TRUE)
ndvi <- raster("NDVI.dat")
## initialize an object to store the results for each shpfile
res <- vector("list", length(shpfiles))
names(res) <- shpfiles
## loop over files
for (i in seq_along(shpfiles)) {
  ## do the union
  temp <- gUnionCascaded(shpfiles[i])
  ## extract for this shape data (and don't call it "extract")
  extracted <- extract(ndvi,temp)
  ## further processing, save result
  mean <- range(extracted, na.rm = TRUE )[1:2]
  res[[i]] <- mean  ## plus whatever else you need
}

上面的mc()函数返回值的含义并不明确,因此我会忽略它。这种方法比你最初尝试的方法更加节省内存且速度更快。我怀疑在这里使用并行处理并没有多大意义。


1
extract 函数在使用多边形时其实是内部多核的。你不需要做任何事情来利用这个特点,除了 require( parallel ); beginCluster( detectCores()-1 )。当在 1000 个多边形之间提取时,通过这样做你可能会发现明显的速度优势(但这个问题涉及内存,而非速度)。 - Simon O'Hanlon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接