使用mc2d进行基于网格的蒙特卡罗模拟

时间:2018-01-17 17:37:55

标签: r montecarlo

我有一个简单的公式来计算四个不同网格之和的“CL”:

CL = A + B + C + D

我试图使用mc2d包根据每个输入网格的不确定性来表示CL结果的不确定性。

每个输入网格的不确定性基于均匀分布表示,其不确定性范围为:

光栅A

+/- 6

光栅B

+/- 10

光栅C

+/- 12

+/- 5用于栅格D

我想运行蒙特卡罗模拟,根据从这些不确定范围内随机选择的每个网格单元的值,对输入网格进行多次求和(例如n = 1000)

以下代码失败:

Error in .calcTest(x[1:5], fun, na.rm, forcefun, forceapply) : 
    cannot use this function

我不确定如何解决此错误。任何建议都会非常感激。

library(raster) 
library(rgdal) 
library(mc2d) #load package

# Input grid files
A <- raster(matrix(c(20, 35, 40, 60), nrow=2))
B <- raster(matrix(c(6, 10, 13, 14), nrow=2))
C <- raster(matrix(c(6, 8, 12, 14), nrow=2))
D <- raster(matrix(c(35, 40, 50, 60), nrow=2))

# combine the RasterLayer objects into a RasterStack 
s <- stack(A, B, C, D)

# Uncertainty distance for each raster used to establish the 
# min/max for the uniform distributions in the function just below
uA <- 6
uB <- 10
uC <- 12
uD <- 5

# Function for generating CL
ndunc(1000)
fun <- function(x) {
  # Convert each raster to mcnode object
  dA <- mcdata(x[1], type="0")
  dB <- mcdata(x[2], type="0")
  dC <- mcdata(x[3], type="0")
  dD <- mcdata(x[4], type="0")

  # Define uniform distirbutions for each raster
  stA <- mcstoc(runif, type="U", min=dA-uA, max=dA+uA, rtrunc=TRUE, linf=0)
  stB <- mcstoc(runif, type="U", min=dA-uB, max=dA+uB, rtrunc=TRUE, linf=0)
  stC <- mcstoc(runif, type="U", min=dA-uC, max=dA+uC, rtrunc=TRUE, linf=0)
  stD <- mcstoc(runif, type="U", min=dA-uD, max=dA+uD, rtrunc=TRUE, linf=0)

  # Apply Monte Carlo to this equation
  CL <- stA + stB + stC + stD
  # Extract the min, mean, and max CL from the 1000 iterations
  c(min(CL), mean(CL), max(CL))
}

# Need to create rasters for min(CL), mean(CL), and max(CL)
x <- calc(s, fun) 
names(x) = c('min', 'mean', 'max') 
plot(x)

1 个答案:

答案 0 :(得分:0)

函数中的错误是由rtrunc = TRUE中的拼写错误(缺少等号)引起的

相关问题