Over the weekend I implemented a version of the agent-based model from Thomas Schelling's 1971 paper in Python. Schelling's story about segregation is simple: there are two colors of agents, happiness is based on whether two or more of your neighbors are the same color as you, and you move if you are unhappy.

The model has been studied thoroughly by smarter people than me, and is included as one of the early discussions in Scott Page's Model Thinking course. My instantiation comes from an exercise in chapter 10 of Allen Downey's Think Complexity, which is accompanied by the following comments:

You might not be surprised to hear that this model leads to some segregation, but you might be surprised by the degree. Fairly quickly, clusters of similar agents appear. The clusters grow and coalesce over time until there are a small number of large clusters and most agents live in homogeneous neighborhoods.
If you did not know the process and only saw the result, you might assume that the agents were racist, but in fact all of them would be perfectly happy in a mixed neighborhood. Since they prefer not to be greatly outnumbered, they might be considered xenophobic at worst. Of course, these agents are a wild simplification of real people, so it may not be appropriate to apply these descriptions at all.

Here is a screenshot from the running of my model:

[caption id="attachment_991" align="aligncenter" width="404"] Screenshot from my implementation of Schelling's model in Python[/caption]

Unhappy agents are represented by X's, happy ones by O's. The only substantial departure from the exercise here is that I base happiness on four neighbors (up, down, left, right), rather than eight (including the diagonals) because I misread the instructions the first time. This departure makes the agents less tolerant than in Schelling's original. The neighborhood shown above is 10x10, but the code should be generalizable. Ninety percent of the houses are filled, which leaves some empty ones for moving around.

My code is here, including some comments indicating planned improvements. For the pointer to Downey's book, I thank Josh Cutler.