Site icon R-bloggers

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

step.syn.slow <- function(space) {< o:p>
    base.x <- c(-1, 1, 10, 01, 1, 1)< o:p>
    base.y <- c(-101, 1, 1, 1, 0, 1)< o:p>
    size <- nrow(space)< o:p>
    new.space <- space< o:p>
    for (x in 1:size) {< o:p>
        for (y in 1:size) {< o:p>
            nei8 <- 1 + ((cbind(x + base.x, y + base.y) 1) %% size)< o:p>
            nei.pref <- sum(space[nei8])< o:p>
            if (nei.pref > 0) { new.space[x, y] <- 1 }< o:p>
            if (nei.pref < 0) { new.space[x, y] <- 1 }< o:p>
        }< o:p>
    }< o:p>
    return(new.space)< o:p>
}< o:p>

step.syn.fast <- function(space) {< o:p>
    size <- nrow(space)< o:p>
    shift.back    <- c(2:size, 1)< o:p>
    shift.forward <- c(size, 1🙁size1))< o:p>
    < o:p>
    shift.space <- space[, shift.back] +< o:p>
                   space[shift.back, shift.back] +< o:p>
                   space[shift.forward, shift.back] +< o:p>
                   space[, shift.forward] +< o:p>
                   space[shift.back, shift.forward] +< o:p>
                   space[shift.forward, shift.forward] +< o:p>
                   space[shift.back,] +< o:p>
                   space[shift.forward,]< o:p>
    space[shift.space > 0] <- 1< o:p>
    space[shift.space < 0] <- 1< o:p>
    return(space)< o:p>
}< o:p>

To compare their execution speed I run the following test:

run <- function(size, reps) {< o:p>
    space <- 2 * matrix(rbinom(size^2, 1, 0.5), nrow = size) 1< o:p>
    slow <- system.time(replicate(reps, step.syn.slow(space)))< o:p>
    fast <- system.time(replicate(reps, step.syn.fast(space)))< o:p>
    cbind(“slow” = slow[3], “fast” = fast[3])< o:p>
}< o:p>

run(32, 512)< o:p>
# Result< o:p>
#         slow fast< o:p>
# elapsed 6.02 0.06< o:p>

run(512, 32)< o:p>
# Result< o:p>
#          slow fast< o:p>
# elapsed 95.77 1.98< o:p>

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.