Skip to content

Instantly share code, notes, and snippets.

@timriffe
Created February 25, 2012 19:32
Show Gist options
  • Save timriffe/1910220 to your computer and use it in GitHub Desktop.
Save timriffe/1910220 to your computer and use it in GitHub Desktop.
Model Thinking- Schelling Process- Segregation Indices and Neighborhood size
# the point of this script is to demonstrate the SchellingSegregation() function,
# which takes the output from SchellingProcess() and calculates the segregation index given a certain neighborhood size, by default 4x4 cells blocks in the larger matrix.
# we first source two git gists containing the functions we'll use:
# source Schelling Process functions:
# get Schelling Process functions:
source("http://raw.github.com/gist/1910183/785efd5809a05df73de23c4fa9d897e3789444ba/SchellingProcessFunctions.r")
# get Segregation Index functions for Schelling Process output:
source("http://raw.github.com/gist/1910173/248483abb658f73acb03e897d3374b5b709c3c21/SegregationIndex.r")
# set random number seed:
set.seed(1)
# get starting population:
A <- PopulateMatrix(nrow=20,ncol=20, propvacant = .3)
# iterate through Schelling moves until convergence (if possible)
SchellingOutput <- SchellingProcess(A,threshold = .35, maxit = 500)
# take a look at output:
plot(SchellingOutput)
# calculate segregation index for each iteration with 4x4 neighborhoods:
segtime16 <- SchellingSegregation(SchellingOutput,16)
# and again for 3x3 neighborhoods:
segtime9 <- SchellingSegregation(SchellingOutput,9)
# how do they compare?:
plot(0:(length(segtime16)-1),segtime16,type='l',ylim=c(0,1),ylab="Segreagation Index",xlab="iteration",col="blue",
main = "Segregation indices vary depending on neighborhood size\nbut usually show the same overall trend")
lines(0:(length(segtime9)-1),segtime9,col="green")
legend("topleft",lty=1,col=c("blue","green"),legend=c("16-cell neighborhoods (4x4)","9-cell neighborhoods (3x3)"))
text(1,.75,"*Schelling process\n*randomly generated 20x20 board 20% vacant\n*remaining cells divided 70% A, 30% B\n*equal preferences of .35 same",pos=4)
arrows(7.5,.25,9,.38)
text(7.5,.25,"convergence after 9 iterations",pos=2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment