# Parallelizing Voting simulation

March 1, 2012
By

(This article was first published on R snippets, and kindly contributed to R-bloggers)

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.
The two versions of the Voting synchronous code are given here:

step.syn.slow <- function(space) {
base.x <- c(-1, 1, 10, 01, 1, 1)
base.y <- c(-101, 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🙁size1))

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 on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

## Sponsors

Contact us if you wish to help support R-bloggers, and place your banner here.

# Never miss an update! Subscribe to R-bloggers to receive e-mails with the latest R posts.(You will not see this message again.)

Click here to close (This popup will not appear again)