The code executing the simulation is given below. It simulates two types of voter preferences encoded as 1 and -1. In this way average preference equal to 0 indicates 50/50 split. Voters are arranged on square grid with vertical and horizontal wrapping.
nei8 <- function(x, y, size) {
base.x <- c(-1, -1, -1, 0, 0, 1, 1, 1)
base.y <- c(-1, 0, 1, -1, 1, -1, 0, 1)
1 + ((cbind(x + base.x, y + base.y) - 1) %% size)
}
step.syn <- function(space) {
size <- nrow(space)
new.space <- space
for (x in 1:size) {
for (y in 1:size) {
nei.pref <- sum(space[nei8(x, y, size)])
if (nei.pref > 0) { new.space[x, y] <- 1 }
if (nei.pref < 0) { new.space[x, y] <- -1 }
}
}
return(new.space)
}
step.asyn <- function(space) {
size <- nrow(space)
old.space <- space
all.x <- rep(1:size, size)
all.y <- rep(1:size, each = size)
dec.seq <- sample.int(length(all.x))
for (i in dec.seq) {
x <- all.x[i]
y <- all.y[i]
nei.pref <- sum(space[nei8(x, y, size)])
if (nei.pref > 0) { space[x, y] <- 1 }
if (nei.pref < 0) { space[x, y] <- -1 }
}
return(space)
}
simulate <- function (size, is.syn, do.plot) {
x <- rep(1:size, size)
y <- rep(1:size, each = size)
space <- 2 * matrix(rbinom(size ^ 2, 1, 0.5), nrow = size) - 1
rep <- 0
while (TRUE) {
rep <- rep + 1
old.space <- space
if (is.syn) {
space <- step.syn(space)
} else {
space <- step.asyn(space)
}
if (do.plot) {
par(pin=c(3,3))
plot(x , y, axes = FALSE, xlab="", ylab="",
col = space + 2, pch = 15, cex = 40 / size)
}
if (all(old.space == space)) {
return(c(rep, mean(space)))
}
if (rep > 100) {
return(c(NA, mean(space)))
}
}
}
It uses either step.syn function which assumes that all voters make decision at the same time in each time step and step.asyn where all voters are activated in random order.
To reproduce graph similar to NetLogo original the do.plot option should be set to TRUE. For example simulate(32, FALSE, TRUE) generates the following picture:
In order to compare synchronous and asynchronous voter activation regimes I have run the following code:
s.r <- replicate (1024, simulate(32, TRUE, FALSE))
as.r <- replicate (1024, simulate(32, FALSE, FALSE))
par(mfrow = c(1, 2))
boxplot(cbind("synchronous"=s.r[1,],"asynchronous"=as.r[1,]),
main = "time")
boxplot(cbind("synchronous"=s.r[2,],"asynchronous"=as.r[2,]),
main = "mean preference")
As shown on the picture below the distribution of mean voter preferences is very similar. However convergence speed of both methods varies greatly. Moreover under synchronous activation around 0.5% of simulations do not reach stable state.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.