Parallelizing Voting simulation
[This article was first published on R snippets, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Last week I have compared synchronous and asynchronous implementation of NetLogo Voting model. An interesting afterthought is that synchronous model implementation can be easily made much faster using vectorization.Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
The two versions of the Voting synchronous code are given here:
step.syn.slow <- function(space) {
base.x <- c(-1, –1, –1, 0, 0, 1, 1, 1)
base.y <- c(-1, 0, 1, –1, 1, –1, 0, 1)
size <- nrow(space)
new.space <- space
for (x in 1:size) {
for (y in 1:size) {
nei8 <- 1 + ((cbind(x + base.x, y + base.y) – 1) %% size)
nei.pref <- sum(space[nei8])
if (nei.pref > 0) { new.space[x, y] <- 1 }
if (nei.pref < 0) { new.space[x, y] <- –1 }
}
}
return(new.space)
}
step.syn.fast <- function(space) {
size <- nrow(space)
shift.back <- c(2:size, 1)
shift.forward <- c(size, 1🙁size–1))
shift.space <- space[, shift.back] +
space[shift.back, shift.back] +
space[shift.forward, shift.back] +
space[, shift.forward] +
space[shift.back, shift.forward] +
space[shift.forward, shift.forward] +
space[shift.back,] +
space[shift.forward,]
space[shift.space > 0] <- 1
space[shift.space < 0] <- –1
return(space)
}
To compare their execution speed I run the following test:
run <- function(size, reps) {
space <- 2 * matrix(rbinom(size^2, 1, 0.5), nrow = size) – 1
slow <- system.time(replicate(reps, step.syn.slow(space)))
fast <- system.time(replicate(reps, step.syn.fast(space)))
cbind(“slow” = slow[3], “fast” = fast[3])
}
run(32, 512)
# Result
# slow fast
# elapsed 6.02 0.06
run(512, 32)
# Result
# slow fast
# elapsed 95.77 1.98
As it could be predicted vectorized version of the code is much faster for small and large problem sizes.
Unfortunately such a vectorization is probably impossible to implement in R for asynchronous model.
To leave a comment for the author, please follow the link and comment on their blog: R snippets.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.