rr-rasterterrasnow

bias correct raster cells using edcf


I have a gridded map that i want to bias correct the cell values using ECDF. I tried using clusterR from the snow package in R. But I keep getting this error.

[1] "cannot use this function"
attr(,"class")
[1] "snow-try-error" "try-error"     
Error in clusterR(snodas_max_4km_2014, calc, args = list(fun = bias_correct_on_grid),  : 
  cluster error

function to apply to each cell. in_ecdf_snodas is an inverse cdf and ecdf_ua is a cdf function

#define the function to apply to each cell

bias_correct_on_grid = function(x, snodas_overlap, ua_overlap){
 if (x <= max_ua_overlap) {
    x_biased_correct <- in_ecdf_snodas(ecdf_ua(x))
  } else if (x > max_ua_overlap) {
    x_biased_correct <- max_snodas_overlap + (x - max_ua_overlap) * (sd_snodas_overlap / sd_ua_overlap)
  } else  if (is.na(x)){
    x_biased_correct <- x
  }
  return(x_biased_correct)
}

The rest of code is as follows:

load("data-raw/RObject/snodas_max_4km_2014.RData") #raster layer


# create a cluster with 6 workers
cl <- makeCluster(4)

# load required packages on each worker node
clusterEvalQ(cl, {
  library(raster)
  library(snow)
library(GoFKernel)
})


clusterExport(cl, list(
  "bias_correct_on_grid", "max_ua_overlap", "min_snodas_overlap",
  "max_snodas_overlap", "sd_snodas_overlap",
  "sd_ua_overlap" , "in_ecdf_snodas", "ecdf_ua"
))

# apply the function to the raster using clusterR
raster_out <- clusterR(snodas_max_4km_2014, calc,
                       args = list(fun = bias_correct_on_grid), cl = cl)

# stop the cluster
stopCluster(cl)



Solution

  • Here is how you might stats::ecdf to a raster.

    library(terra)
    s <- rast(system.file("ex/logo.tif", package="terra")) 
    a <- app(s, \(i) ecdf(i)(i))