An agent-based model simulates a system as a collection of individual agents, such as people, animals, cells, or cars, which follow simple rules and interact with each other. ODE models only track the total population, and the Gillespie algorithm of Stochastic Simulation assumes that everybody is equally likely to meet everybody else. In an agent-based model, every agent can have its own state, position, and contacts. Even when the rules are simple, the agents together can show complicated emergent behavior that no single rule describes.
We’ll look at three examples: an idea spreading through a population, Conway’s Game of Life, and a flock of birds.
import time
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
from scipy.signal import convolve2d
rng = np.random.default_rng(37830)Example: spreading an idea¶
Let’s say someone has a new idea, and that it is a really good idea. So good, in fact, that once someone hears it they can’t stop talking about it. We can model a person, or agent, as a Python class with a single attribute:
class Person():
"""
An agent representing a person.
By default, a person is not enlightened. They can become enlightened using the enlighten method.
"""
def __init__(self):
self.enlightened = False # if enlightened = True, the person has heard the idea
def is_enlightened(self):
"""
returns True if the person has heard the idea
"""
return self.enlightened
def enlighten(self):
"""
once the person has heard the idea, they become enlightened
"""
self.enlightened = True
a = Person()
print(a.is_enlightened()) # the person is not enlightened by default
a.enlighten() # the person becomes enlightened
print(a.is_enlightened()) # the person is now enlightenedNow we simulate how the idea spreads through a population. Say that there are N people in the population, and each day every enlightened person talks to k random other people. Each person they talk to becomes enlightened with probability p. We start with one enlightened person.
N = 1_000 # population size
k = 5 # number of people each person talks to
p = 0.1 # probability that a conversation enlightens the listener
pop = [Person() for i in range(N)] # our population
pop[0].enlighten()Here is a function that simulates all the conversations in one day, and one that counts how many people are enlightened:
def one_day(pop, k, p, rng):
"""
every enlightened person talks to k random people, who each become enlightened with probability p
"""
N = len(pop)
for i in range(N):
if pop[i].is_enlightened():
contacts = rng.integers(N, size=k)
for j in contacts:
if rng.random() < p:
pop[j].enlighten()
def count_enlightened(pop):
return sum(person.is_enlightened() for person in pop)
one_day(pop, k, p, rng)
count_enlightened(pop)Now let’s see how the number of enlightened people changes over 100 days.
T = 100 # number of days to simulate
start = time.perf_counter()
counts = [count_enlightened(pop)]
for t in range(T):
one_day(pop, k, p, rng)
counts.append(count_enlightened(pop))
object_time = time.perf_counter() - start
plt.plot(counts)
plt.xlabel('day')
plt.ylabel('number enlightened')
plt.show()Agents as arrays¶
You don’t have to use Python objects to represent agents. When every agent has the same few attributes, it is simpler and much faster to store each attribute of the whole population in a NumPy array, here a boolean array enlightened, and to update all the agents at once.
def spread_idea(N, k, p, T, rng):
"""
simulate the spread of an idea for T days, starting from one enlightened person
returns the number of enlightened people on days 0, 1, ..., T
"""
enlightened = np.zeros(N, dtype=bool)
enlightened[0] = True
counts = [1]
for t in range(T):
talkers = np.count_nonzero(enlightened)
contacts = rng.integers(N, size=(talkers, k)) # everyone the talkers talk to
convinced = contacts[rng.random((talkers, k)) < p] # the conversations that succeed
enlightened[convinced] = True
counts.append(np.count_nonzero(enlightened))
return np.array(counts)
start = time.perf_counter()
counts = spread_idea(N, k, p, T, rng)
array_time = time.perf_counter() - start
print(f"objects: {object_time:.3f} s, arrays: {array_time:.4f} s, {object_time / array_time:.0f} times faster")The two versions differ in one detail. In the loop over Person objects, someone enlightened earlier in the same day may already talk to others later in that day, while in the array version everyone talks based on the state at the start of the day. The order in which agents are updated, all at once (synchronously) or one at a time (asynchronously), is a modeling choice that can change the results.
Different runs differ mostly in how long the idea takes to get going. On average, each of the enlightened people on day has successful conversations, and a fraction of these reach someone new, so
This is a discrete version of the logistic equation. Such a “mean-field” approximation, which replaces random interactions by their average, describes the typical behavior but not the randomness.
mean_field = [1.0]
for t in range(T):
E = mean_field[-1]
mean_field.append(E + k * p * E * (1 - E / N))
plt.figure(figsize=(7, 4))
for _ in range(10):
plt.plot(spread_idea(N, k, p, 40, rng), color='C0', lw=0.8, alpha=0.7)
plt.plot(mean_field[:41], 'k--', lw=2, label='mean-field approximation')
plt.xlabel('day')
plt.ylabel('number enlightened')
plt.legend()
plt.title('10 runs of the agent-based model')
plt.show()Phase diagrams¶
In our example, there are a couple of parameters we can tweak. We’ll focus on p and k, and ask how the outcome changes as we change them, by counting the number of people who are enlightened on day 20.
ks = np.arange(1, 11)
ps = np.logspace(-2, 0, 10)
cts = np.zeros((len(ks), len(ps)))
for i, k_ in enumerate(ks):
for j, p_ in enumerate(ps):
cts[i, j] = spread_idea(N, k_, p_, 20, rng)[-1]
plt.figure(figsize=(8, 5))
plt.pcolormesh(ps, ks, cts, shading='nearest')
plt.colorbar(label='number enlightened on day 20')
plt.plot(ps, (N**(1 / 20) - 1) / ps, 'w--', label=r'$(1 + kp)^{20} = N$')
plt.xscale('log')
plt.ylim(0.5, 10.5)
plt.xlabel('$p$')
plt.ylabel('$k$')
plt.legend()
plt.show()If k and p are large enough, the whole population is enlightened by day 20, and if they are too small, very few people are. The change between the two regions is abrupt, which is a kind of phase transition: a small change in the parameters causes a large change in the behavior of the system. The dashed curve is a mean-field estimate of where it happens. While few people are enlightened, their number grows by a factor of about per day, so the idea reaches everyone in 20 days when .
The Game of Life¶
Conway’s Game of Life takes place on an m by n grid of cells, each of which is either alive or dead. The cells are updated at each time step using the following rules:
Any live cell with 0 or 1 live neighbors dies (under-population).
Any live cell with 2 or 3 live neighbors survives until the next time step.
Any live cell with more than 3 live neighbors dies (overpopulation).
Any dead cell with exactly 3 live neighbors becomes alive (reproduction).
Neighbors are horizontally, vertically, or diagonally adjacent. We store the grid in a boolean NumPy array, with True for alive and False for dead. The first step is to count the live neighbors of every cell. The neighbors generator (see Iterators and Generators) yields the neighbors of a cell; cells on the edge of the grid have fewer of them.
def neighbors(i, j, m, n):
"""
yields the indices of the neighbors of cell (i, j) in an m by n grid
"""
inbrs = [-1, 0, 1]
if i == 0:
inbrs = [0, 1]
if i == m - 1:
inbrs = [-1, 0]
jnbrs = [-1, 0, 1]
if j == 0:
jnbrs = [0, 1]
if j == n - 1:
jnbrs = [-1, 0]
for delta_i in inbrs:
for delta_j in jnbrs:
if delta_i == delta_j == 0:
continue
yield i + delta_i, j + delta_j
def count_alive_neighbors(S):
m, n = S.shape
cts = np.zeros(S.shape, dtype=np.int64)
for i in range(m):
for j in range(n):
for i2, j2 in neighbors(i, j, m, n):
cts[i, j] = cts[i, j] + S[i2, j2]
return ctsCounting the neighbors of every cell is a convolution of the grid with the kernel below. convolve2d with mode='same' treats the cells outside the grid as dead, which gives the same counts as the loops above, much faster.
kernel = np.array([[1, 1, 1],
[1, 0, 1],
[1, 1, 1]])
def count_alive_neighbors_fast(S):
return convolve2d(S.astype(int), kernel, mode='same')
S = rng.random((100, 100)) < 0.3
start = time.perf_counter()
slow = count_alive_neighbors(S)
loop_time = time.perf_counter() - start
start = time.perf_counter()
fast = count_alive_neighbors_fast(S)
conv_time = time.perf_counter() - start
print(f"same counts: {np.array_equal(slow, fast)}, loops {loop_time:.3f} s, convolution {conv_time:.5f} s")The rules then become one line of NumPy:
def life_step(S):
"""
one step of the Game of Life
"""
cts = count_alive_neighbors_fast(S)
return (cts == 3) | (S & (cts == 2))What makes the Game of Life interesting is that simple rules produce patterns that persist, oscillate, or travel across the grid. We start from a random grid:
m, n = 50, 50
S = rng.random((m, n)) < 0.3
plt.figure(figsize=(5, 5))
plt.imshow(S)
plt.axis('off')
plt.show()The cell below produces an animated GIF of the Game of Life. See the matplotlib animation guide for more on animations.
fig = plt.figure(figsize=(5, 5))
im = plt.imshow(S, animated=True)
plt.axis('off') # turn off ticks
def update(frame):
global S
S = life_step(S)
im.set_array(S)
return im,
anim = animation.FuncAnimation(fig, update, frames=100, interval=200, blit=True)
anim.save('life.gif', dpi=80, writer='pillow')
plt.close(fig) # don't also show the last frame as a static figureHere’s what the GIF looks like:

Flocking (Optional)¶
Flocks of birds, schools of fish, and swarms of bacteria move together without a leader. Each animal reacts only to its neighbors, yet the whole group can line up and travel in one direction. Reynolds’ boids (1987) produced realistic flocks with three rules:
steer away from neighbors that are too close (separation)
steer towards the average heading of the neighbors (alignment)
steer towards their average position (cohesion).
The Vicsek model (1995) keeps only alignment and adds noise:
agents move in a square box of side with periodic boundary conditions: an agent that leaves through one side comes back through the opposite side.
All agents move at the same speed . Agent has a position and a heading, the angle .
At every time step, each agent turns to the average heading of all the agents within distance of it, including itself, plus a random angle drawn uniformly from . Then it moves a distance in its new direction.
The average heading is the direction of the sum of the unit vectors . Averaging the angles themselves would be wrong: the average of and is , but the two agents are both heading in the direction .
The order parameter
measures how well the flock is aligned. It is 1 when all agents move in the same direction, and about when they move in random directions.
def vicsek_step(x, theta, L, r, v, eta, rng):
"""
one time step of the Vicsek model
x - positions, shape (N, 2), in the periodic box [0, L) x [0, L)
theta - headings, shape (N,)
returns the new positions and headings
"""
d = x[:, None, :] - x[None, :, :] # displacements between all pairs, shape (N, N, 2)
d -= L * np.round(d / L) # use the nearest periodic copy of each agent
near = np.sum(d**2, axis=2) < r**2 # near[i, j] is True if j is within distance r of i
theta = np.arctan2(near @ np.sin(theta), near @ np.cos(theta)) # average heading
theta = theta + eta * (rng.random(theta.size) - 0.5)
x = (x + v * np.column_stack([np.cos(theta), np.sin(theta)])) % L
return x, theta
def order_parameter(theta):
"""
length of the average heading vector, 1 if all agents move in the same direction
"""
return np.abs(np.mean(np.exp(1j * theta)))
def plot_agents(ax, x, theta, L):
"""
draw each agent as an arrow, colored by its heading
"""
arrows = ax.quiver(x[:, 0], x[:, 1], np.cos(theta), np.sin(theta), theta,
cmap='hsv', clim=(-np.pi, np.pi), scale=30, width=0.006)
ax.set_xlim(0, L)
ax.set_ylim(0, L)
ax.set_aspect('equal')
ax.set_xticks([])
ax.set_yticks([])
return arrowsWe simulate agents in a box of side , with interaction radius and speed , starting from random positions and headings. We run the model with a low noise level, , and a high one, .
N, L, r, v = 300, 10.0, 1.0, 0.1
x0 = rng.uniform(0, L, size=(N, 2))
theta0 = rng.uniform(-np.pi, np.pi, size=N)
fig, ax = plt.subplots(1, 3, figsize=(13, 4.5))
plot_agents(ax[0], x0, theta0, L)
ax[0].set_title(f'random start, order {order_parameter(theta0):.2f}')
order = {}
for a, eta in zip(ax[1:], [0.5, 5.0]):
x, theta = x0, theta0
order[eta] = [order_parameter(theta)]
for step in range(500):
x, theta = vicsek_step(x, theta, L, r, v, eta, rng)
order[eta].append(order_parameter(theta))
plot_agents(a, x, theta, L)
a.set_title(rf'$\eta = {eta}$ after 500 steps, order {order[eta][-1]:.2f}')
plt.show()
plt.figure(figsize=(7, 3))
for eta, values in order.items():
plt.plot(values, label=rf'$\eta = {eta}$')
plt.xlabel('step')
plt.ylabel(r'order parameter $\varphi$')
plt.ylim(0, 1.05)
plt.legend()
plt.show()With low noise, neighbors align, aligned groups merge, and the whole flock soon moves in one direction. With high noise, small groups form and break up, and there is no common direction. Animating the low-noise flock shows how the order emerges:
x, theta = x0, theta0
fig, ax = plt.subplots(figsize=(4, 4), dpi=60)
arrows = plot_agents(ax, x, theta, L)
def update(frame):
global x, theta
for _ in range(3): # three time steps per frame
x, theta = vicsek_step(x, theta, L, r, v, 0.5, rng)
arrows.set_offsets(x)
arrows.set_UVC(np.cos(theta), np.sin(theta), theta)
return arrows,
anim = animation.FuncAnimation(fig, update, frames=100, interval=60)
anim.save('flocking.gif', writer='pillow')
plt.close(fig)
How does the order depend on the noise? We run the model for each of several noise levels, discard the first 200 steps, and average the order parameter over the next 200.
etas = np.linspace(0, 5, 11)
nburn, navg = 200, 200
mean_order = []
for eta in etas:
x, theta = x0, theta0
values = []
for step in range(nburn + navg):
x, theta = vicsek_step(x, theta, L, r, v, eta, rng)
values.append(order_parameter(theta))
mean_order.append(np.mean(values[nburn:]))
plt.figure(figsize=(6, 4))
plt.plot(etas, mean_order, 'o-')
plt.axhline(1 / np.sqrt(N), color='k', ls='--', label=r'random headings, $1/\sqrt{N}$')
plt.xlabel(r'noise $\eta$')
plt.ylabel(r'average order parameter $\varphi$')
plt.legend()
plt.show()The flock goes from ordered motion at low noise to disordered motion at high noise. Vicsek and his coauthors found that this change gets sharper as the number of agents grows at a fixed density . It is a phase transition, like the one in the idea-spreading model, but in the collective motion of the agents.
Each step of vicsek_step compares all pairs of agents, which is fine for hundreds of agents but not for a million. Since each agent only interacts with agents within distance , a KD-tree finds the pairs of neighbors much faster (see Nearest Neighbors), and scipy.spatial.cKDTree(x, boxsize=L) handles the periodic box.
Exercises¶
Exercise 1¶
How does changing N, p, and k affect the spread of the idea?
# Your code hereExercise 2¶
Change spread_idea so that each enlightened person forgets the idea and becomes un-enlightened with probability q every day. What happens to the number of enlightened people in the long run? Compare with the mean-field prediction that a fraction of the population is enlightened when .
# Your code hereExercise 3¶
Run the Game of Life on a torus, where the top edge of the grid is glued to the bottom and the left edge to the right, using the boundary='wrap' argument of convolve2d. Start from a glider and check that it moves one cell diagonally every four steps and comes back to where it started.
# Your code here