Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Agent-Based Models

Open in Colab

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.

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:

Now 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.

Here is a function that simulates all the conversations in one day, and one that counts how many people are enlightened:

Now let’s see how the number of enlightened people changes over 100 days.

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.

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 EtE_t enlightened people on day tt has kpkp successful conversations, and a fraction 1−Et/N1 - E_t/N of these reach someone new, so

Et+1≈Et+kp Et(1−EtN).E_{t+1} \approx E_t + kp\, E_t \left(1 - \frac{E_t}{N}\right).

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.

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.

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 1+kp1 + kp per day, so the idea reaches everyone in 20 days when (1+kp)20≈N(1 + kp)^{20} \approx N.

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:

  1. Any live cell with 0 or 1 live neighbors dies (under-population).

  2. Any live cell with 2 or 3 live neighbors survives until the next time step.

  3. Any live cell with more than 3 live neighbors dies (overpopulation).

  4. 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.

Counting 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.

The rules then become one line of NumPy:

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:

The cell below produces an animated GIF of the Game of Life. See the matplotlib animation guide for more on animations.

Here’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:

  1. steer away from neighbors that are too close (separation)

  2. steer towards the average heading of the neighbors (alignment)

  3. steer towards their average position (cohesion).

The Vicsek model (1995) keeps only alignment and adds noise:

  • NN agents move in a square box of side LL with periodic boundary conditions: an agent that leaves through one side comes back through the opposite side.

  • All agents move at the same speed vv. Agent ii has a position xi\mathbf x_i and a heading, the angle θi\theta_i.

  • At every time step, each agent turns to the average heading of all the agents within distance rr of it, including itself, plus a random angle drawn uniformly from [−η/2,η/2][-\eta/2, \eta/2]. Then it moves a distance vv in its new direction.

The average heading is the direction of the sum of the unit vectors (cos⁡θj,sin⁡θj)(\cos\theta_j, \sin\theta_j). Averaging the angles themselves would be wrong: the average of 179°179° and −179°-179° is 0°0°, but the two agents are both heading in the direction 180°180°.

The order parameter

φ=∣1N∑j=1N(cos⁡θj,sin⁡θj)∣\varphi = \left| \frac{1}{N} \sum_{j=1}^N (\cos\theta_j, \sin\theta_j) \right|

measures how well the flock is aligned. It is 1 when all agents move in the same direction, and about 1/N1/\sqrt N when they move in random directions.

We simulate N=300N = 300 agents in a box of side L=10L = 10, with interaction radius r=1r = 1 and speed v=0.1v = 0.1, starting from random positions and headings. We run the model with a low noise level, η=0.5\eta = 0.5, and a high one, η=5\eta = 5.

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:

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.

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 N/L2N/L^2. 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 N2N^2 pairs of agents, which is fine for hundreds of agents but not for a million. Since each agent only interacts with agents within distance rr, 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?

Exercise 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 1−q/(kp)1 - q/(kp) of the population is enlightened when q<kpq < kp.

Exercise 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.