在 R terra 中将单波段栅格并行乘以向量

问题描述 投票:0回答:1

我想并行执行以下向量*光栅乘法,因为我的向量很长:

library(terra)

# Create a raster example

set.seed(123)

raster_example <- rast(nrow = 10, ncol = 10, vals = rnorm(100))

# Create a vector example
vector_ejemplo <- c(2, 3, 4, 5, 6, 7, 8, 9, 10, 11)

# Perform multiplication 
result_no_parallel <- vector_ejemplo * raster_example


print(result_no_parallel)

我尝试使用

terra::app
,但只收到错误。

有办法做到这一点吗?

r parallel-processing raster terra
1个回答
0
投票

Rast
对象无法序列化(请查看here和相关链接)。但是您可以将名称或路径发送到节点,或者您可以
wrap
将栅格发送到节点。这是一个包含您的数据的玩具示例。请注意,此示例没有时间增益,因为拥有多个节点的开销比速度增益更重要。由于乘法是
terra
中的一个 C++ 函数,针对速度和内存使用进行了优化,我想如果您需要并行化这样一个简单的操作,您的栅格将是巨大的。

library(terra)
library(foreach)
library(doParallel)
# Create a raster example

set.seed(123)

raster_example <- rast(nrow = 10, ncol = 10, vals = rnorm(100))
path <-file.path(tempdir(),"ejemplo.tif")
writeRaster(raster_example,path)

# Create a vector example
vector_ejemplo <- c(2, 3, 4, 5, 6, 7, 8, 9, 10, 11)



f <- function(path,n) {
  x <- rast(path)
  y <- x*n
  wrap(y)
}

cl <- makeCluster(10)
registerDoParallel(cl)

result <- foreach(n=vector_ejemplo,.packages="terra")%dopar%{
  f(path,n)
}

stopCluster(cl)
x <- do.call(c,lapply(result, unwrap))

有关这个漂亮函数的更多详细信息,请参阅

?wrap
,该函数使与
rast
对象的并行化成为可能。

© www.soinside.com 2019 - 2024. All rights reserved.