How to make maps in R with parallel processing?

Question:

I have been trying to make multiple maps at the same time in R using plot and parallel processing using the snowfall package. I made the following mapas function:

mapas <- function (tx,
                  limite)
    {
    # Open o png
    png(filename=paste0("mapas_mpc/",tx,".png"),width = 1365, height = 1024)
    plot.new()
    par(mar=c(0,0,0,0),oma=c(0,0,0,0))

    # Plot South America border
    #map(regions = SA, fill = TRUE, col="gray", border="black")
    plot(limite, col="gray", border="black")

    # Load species shapefile
    tx_shp <- shapefile (paste0("MPC/",tx,".shp"))

    # Plot species shapefile
    plot(tx_shp,col=rgb(0/255,139/255,0/255,alpha=0.5), border="darkgreen" ,lwd=3,add=T)

    # Species name
    nome_sp <- gsub(pattern="_",replacement=" ",tx)

    # Plot species name
    text(x=-97,y=-27, nome_sp,font=4,cex=1.5)

    # Close PNG
    dev.off()
    cat(paste("Mapa de ",tx),"\n")
}

After that I start parallel processing:

library(snowfall)

# Strat parallel processing
sfInit(parallel=T,cpus=3)

And then I run the mapas function in parallel:

sfLapply(x = lista_sp,fun = mapas,limite = am_sul )

"sp_list": is a vector the characters which contain the names of species. "am_south": is the shapefile of South America boundaries.

Then I have the following error:

Error in checkForRemoteErrors(val) : 3 nodes produced errors; first error: cannot coerce type 'S4' to vector of type 'double'

I don't want my maps to be on the same plot page, because there are thousands. And I need to make maps as quickly as possible, so I chose parallel processing. How can I solve this problem?

Answer:

There is probably a map that is having problems running. But then you end up losing what you've already done. I recommend you use a function that doesn't stop execution when you get an error.

When I use codes in parallel, I use the following workflow:

On Windows:

library(doSNOW)
library(foreach)
cl <- makeCluster(2)
registerDoSNOW(cl)

No Linux:

library(doMC)
registerDoMC(2)

Then:

plyr::l_ply(lista_sp, plyr::failwith(NULL, function(i, limite){
  mapas(i, limite = am_sul)
}), .parallel = T, limite = am_sul)

The failwith function modifies the function so that it returns a pre-defined value (in the case NULL ) in case any error occurs.

That way, at the end of the loop execution you can see in detail why some cases didn't run.

However, seeing that your three nodes are lista_sp , it's worth checking that the maps function is working for the first element of lista_sp .

Scroll to Top
AllEscort