I would like to do parallel coding in R. So far I have found some examples like the following, which works fine:
library(parallelly)
library(parallel)
library(future)
# define function to test whether an number is prime
is_prime <- function(num)
{
if(num == 2 | num == 3)
return(TRUE)
if(num == 1)
return(FALSE)
if(num %% 2 == 0)
return(FALSE)
root <- floor(sqrt(num))
for(elt in seq(5,root))
{
if (num %% elt == 0)
return(FALSE)
}
return(TRUE)
}
# get random sample of 1 million integers from integers between 1 and
# 10 million
# set seed so the random sample will be the same every time
set.seed(2)
sample_numbers <- sample(10000000, 1000000)
start <- proc.time()
cl <- makeCluster(4)
results <- parSapply(cl , sample_numbers , is_prime)
stopCluster(cl)
end <- proc.time()
print(end - start)
Now I would like to build a script to run in parallel the function that generates mandelbrot sets. In the following script, two Mandelbrot sets are generated and plotted, sequentially. I want to convert that process to parallel processing, in which both xlim, ylim and colors can be passed to the function, but I don't know how to do that. Below is the code that is intended to be parallel.
library(mandelbrot)
xlim <- c(-0.8438146, -0.8226294)
ylim <- c(0.1963144, 0.2174996)
view <- mandelbrot(xlim, ylim,iterations = 1000, resolution = 1000)
cols <- mandelbrot_palette(RColorBrewer::brewer.pal(11, "Spectral"), fold = FALSE)
plot(view, col = cols)
xlim <- c(-2, 2)
ylim <- c(-2, 2)
view <- mandelbrot(xlim, ylim, resolution = 1000, iterations = 1000)
blues <- RColorBrewer::brewer.pal(9, "Blues")
cols <- mandelbrot_palette(blues, in_set = "white",
fold = TRUE, reps = 2)
plot(view, col = cols, transform = "log")
I would be very grateful if someone could help me to correctly build the following script, which allows generating and graphing mandelbrot sets in parallel.
library(parallelly)
library(parallel)
library(future)
library(mandelbrot)
#The following is the function that allows you to call the mandelbrot set generator
get_mandelbrot_set <-function(xlim,ylim,color) {
view <- mandelbrot(xlim, ylim,iterations = 1000, resolution = 1000)
cols <- mandelbrot_palette(RColorBrewer::brewer.pal(11, color), fold = FALSE)
plot(view, col = cols) #I don't know if it can be graphed here, inside the function that is executed in parallel or has to be executed at the end, but I don't know how?
}
repetitions <- 1:100
color <-"Blues"
#Generate 100 values for x1, x2, y1, y2, but I don't know how?
xlim <- c(x1, x2)
ylim <- c(y1, y2)
start <- proc.time()
cl <- makeCluster(4)
results <- parSapply(cl , repetitions , get_mandelbrot_set,xlim,ylim,color) #I don't know how to pass the parameters to the get_mandelbrot_set function
stopCluster(cl)
end <- proc.time()
print(end - start)