[R-sig-Geo] Reproducible results with overlay and clusterR

Bede-Fazekas Ákos b|@|ev||@t @end|ng |rom gm@||@com
Tue May 28 07:15:03 CEST 2019


Dear Hugo,
please find below a solution. It might be too complicated and shorter 
solutions might exist, but it works.

library(raster)
r1 <- r2 <- raster()
r1[]<-runif(ncell(r1), 1, 100)
r2[]<-1
r2[1:30000]<-2
r2[30001:35000]<-NA
plot(stack(r1,r2))


## Function
prob<-data.frame(value=1:100, r1=log(1:100), r2=max(log(1:100))-log(1:100))
f <- function(x,y,seed,...){
   ifelse(is.na(y),NA,rbinom(n=1, size=1, prob=prob[[y]][x]))
}
f <- Vectorize(f)

## Wrapper function
wrapper <- function(raster,seed,...){
     set.seed(seed)
     overlay(raster,fun=f)
}

## Overlay (reproducible)
result1<-wrapper(stack(r1,r2),seed=0)
result2<-wrapper(stack(r1,r2),seed=0)
compareRaster(result1,result2,values=TRUE)

## Cluster overlay (Not reproducible)
beginCluster(2)
result3<-clusterR(stack(r1,r2),wrapper,args=list(seed=0), 
export=c("prob", "f"))
endCluster()

beginCluster(2)
result4<-clusterR(stack(r1,r2),wrapper,args=list(seed=0), 
export=c("prob", "f"))
endCluster()

compareRaster(result3,result4,values=TRUE)

HTH,
Ákos Bede-Fazekas
Hungarian Academy of Sciences

2019.05.27. 22:59 keltezéssel, Hugo Costa írta:
> Dear all
> I need to implement a raster::overlay operation with clusterR (which
> works), but don't figure out how to do it reproducible. How to set seeds in
> the cluster? Please find a example below.
> Thank you
> Hugo
>
> ## Rasters
> library(raster)
> r1 <- r2 <- raster()
> r1[]<-runif(ncell(r1), 1, 100)
> r2[]<-1
> r2[1:30000]<-2
> r2[30001:35000]<-NA
> plot(stack(r1,r2))
>
>
> ## Function
> prob<-data.frame(value=1:100, r1=log(1:100), r2=max(log(1:100))-log(1:100))
> f <- function(x,y,...){
>    ifelse(is.na(y),NA,rbinom(n=1, size=1, prob=prob[[y]][x]))
> }
> f <- Vectorize(f)
>
> ## Overlay (reproducible)
> set.seed(0)
> result1<-overlay(stack(r1,r2), fun=f)
> set.seed(0)
> result2<-overlay(stack(r1,r2), fun=f)
> compareRaster(result1,result2,values=TRUE)
>
> ## Cluster overlay (Not reproducible)
> set.seed((0))
> beginCluster(2)
> result3<-clusterR(stack(r1,r2),overlay,args=list(fun=f), export="prob")
> endCluster()
>
> set.seed((0))
> beginCluster(2)
> result4<-clusterR(stack(r1,r2),overlay,args=list(fun=f), export="prob")
> endCluster()
>
> compareRaster(result3,result4,values=TRUE)
>
> 	[[alternative HTML version deleted]]
>
> _______________________________________________
> R-sig-Geo mailing list
> R-sig-Geo using r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
>



More information about the R-sig-Geo mailing list