# The Boids!

## Contents

# The Boids!¶

## Flocking¶

The aggregate motion of a flock of birds, a herd of land animals, or a school of fish is a beautiful and familiar part of the natural world… The aggregate motion of the simulated flock is created by a distributed behavioral model much like that at work in a natural flock; the birds choose their own course. Each simulated bird is implemented as an independent actor that navigates according to its local perception of the dynamic environment, the laws of simulated physics that rule its motion, and a set of behaviors programmed into it… The aggregate motion of the simulated flock is the result of the dense interaction of the relatively simple behaviors of the individual simulated birds.

– Craig W. Reynolds, “Flocks, Herds, and Schools: A Distributed Behavioral Model”, *Computer Graphics* **21** *4* 1987, pp 25-34
See the original paper

Collision Avoidance: avoid collisions with nearby flockmates

Velocity Matching: attempt to match velocity with nearby flockmates

Flock Centering: attempt to stay close to nearby flockmates

## Setting up the Boids¶

Our boids will each have an x velocity and a y velocity, and an x position and a y position.

We’ll build this up in NumPy notation, and eventually, have an animated simulation of our flying boids.

```
import numpy as np
```

Let’s start with simple flying in a straight line.

Our positions, for each of our N boids, will be an array, shape \(2 \times N\), with the x positions in the first row, and y positions in the second row.

```
boid_count = 10
```

We’ll want to be able to seed our Boids in a random position.

We’d better define the edges of our simulation area:

```
limits = np.array([2000, 2000])
```

```
positions = np.random.rand(2, boid_count) * limits[:, np.newaxis]
positions
```

```
array([[1126.12768092, 664.42430135, 657.21500702, 1226.01412659,
1758.54803614, 1816.5657489 , 280.51817017, 472.20737301,
1039.77448917, 607.39689312],
[ 862.81201383, 1362.66295229, 817.83544097, 1665.1245057 ,
484.69309657, 651.41320921, 1537.75014883, 1500.12681106,
69.06270909, 541.89314273]])
```

```
positions.shape
```

```
(2, 10)
```

We used **broadcasting** with np.newaxis to apply our upper limit to each boid.
`rand`

gives us a random number between 0 and 1. We multiply by our limits to get a number up to that limit.

```
limits[:, np.newaxis]
```

```
array([[2000],
[2000]])
```

```
limits[:, np.newaxis].shape
```

```
(2, 1)
```

```
np.random.rand(2, boid_count).shape
```

```
(2, 10)
```

So we multiply a \(2\times1\) array by a \(2 \times 10\) array – and get a \(2\times 10\) array.

Let’s put that in a function:

```
def new_flock(count, lower_limits, upper_limits):
width = upper_limits - lower_limits
return lower_limits[:, np.newaxis] + np.random.rand(2, count) * width[:, np.newaxis]
```

For example, let’s assume that we want our initial positions to vary between 100 and 200 in the x axis, and 900 and 1100 in the y axis. We can generate random positions within these constraints with:

```
positions = new_flock(boid_count, np.array([100, 900]), np.array([200, 1100]))
```

But each bird will also need a starting velocity. Let’s make these random too:

We can reuse the `new_flock`

function defined above, since we’re again essentially just generating random numbers from given limits. This saves us some code, but keep in mind that using a function for something other than what its name indicates can become confusing!

Here, we will let the initial x velocities range over \([0, 10]\) and the y velocities over \([-20, 20]\).

```
velocities = new_flock(boid_count, np.array([0, -20]), np.array([10, 20]))
velocities
```

```
array([[ 6.22755732, 9.61191044, 1.41729182, 4.9540166 ,
7.93370176, 9.48849701, 7.87734517, 1.38124485,
6.19263826, 9.59009789],
[-17.33479479, -1.05910359, -11.95349696, -11.22976279,
-3.89335765, -13.81542151, -7.89352162, -0.96176008,
2.59189342, -1.86048686]])
```

## Flying in a Straight Line¶

Now we see the real amazingness of NumPy: if we want to move our *whole flock* according to

\(\delta_x = \delta_t \cdot \frac{dv}{dt}\)

we just do:

```
positions += velocities
```

## Matplotlib Animations¶

So now we can animate our Boids using the matplotlib animation tools. All we have to do is import the relevant libraries:

```
from matplotlib import animation
from matplotlib import pyplot as plt
%matplotlib inline
```

Then, we make a static plot, showing our first frame:

```
# create a simple plot
# initial x position in [100, 200], initial y position in [900, 1100]
# initial x velocity in [0, 10], initial y velocity in [-20, 20]
positions = new_flock(100, np.array([100, 900]), np.array([200, 1100]))
velocities = new_flock(100, np.array([0, -20]), np.array([10, 20]))
figure = plt.figure()
axes = plt.axes(xlim=(0, limits[0]), ylim=(0, limits[1]))
scatter = axes.scatter(
positions[0, :], positions[1, :], marker="o", edgecolor="k", lw=0.5
)
scatter
```

```
<matplotlib.collections.PathCollection at 0x7f714c20a160>
```

Then, we define a function which **updates** the figure for each timestep

```
def update_boids(positions, velocities):
positions += velocities
def animate(frame):
update_boids(positions, velocities)
scatter.set_offsets(positions.transpose())
```

Call `FuncAnimation`

, and specify how many frames we want:

```
anim = animation.FuncAnimation(figure, animate, frames=50, interval=50)
```

Save out the figure:

```
positions = new_flock(100, np.array([100, 900]), np.array([200, 1100]))
velocities = new_flock(100, np.array([0, -20]), np.array([10, 20]))
anim.save("boids_1.mp4")
```

And download the saved animation.

You can even view the results directly in the notebook.

```
from IPython.display import HTML
positions = new_flock(100, np.array([100, 900]), np.array([200, 1100]))
velocities = new_flock(100, np.array([0, -20]), np.array([10, 20]))
HTML(anim.to_jshtml())
```

## Fly towards the middle¶

Boids try to fly towards the middle:

```
positions = new_flock(4, np.array([100, 900]), np.array([200, 1100]))
velocities = new_flock(4, np.array([0, -20]), np.array([10, 20]))
```

```
positions
```

```
array([[ 116.53528191, 125.46597499, 132.75048647, 193.98801265],
[ 951.32882889, 1017.04255013, 907.57662575, 1051.81326509]])
```

```
velocities
```

```
array([[ 5.24343853, 4.00235372, 0.49888984, 7.87987737],
[17.63027086, 7.19885691, 2.6621786 , 18.62066984]])
```

```
middle = np.mean(positions, 1)
middle
```

```
array([142.184939 , 981.94031747])
```

```
direction_to_middle = positions - middle[:, np.newaxis]
direction_to_middle
```

```
array([[-25.64965709, -16.71896401, -9.43445254, 51.80307364],
[-30.61148857, 35.10223266, -74.36369172, 69.87294763]])
```

This is easier and faster than:

```
for bird in birds:
for dimension in [0, 1]:
direction_to_middle[dimension][bird] = positions[dimension][bird] - middle[dimension]
```

```
move_to_middle_strength = 0.01
velocities = velocities - direction_to_middle * move_to_middle_strength
```

Let’s update our function, and animate that:

```
def update_boids(positions, velocities):
move_to_middle_strength = 0.01
middle = np.mean(positions, 1)
direction_to_middle = positions - middle[:, np.newaxis]
velocities -= direction_to_middle * move_to_middle_strength
positions += velocities
```

```
def animate(frame):
update_boids(positions, velocities)
scatter.set_offsets(positions.transpose())
```

```
anim = animation.FuncAnimation(figure, animate, frames=50, interval=50)
```

```
positions = new_flock(100, np.array([100, 900]), np.array([200, 1100]))
velocities = new_flock(100, np.array([0, -20]), np.array([10, 20]))
HTML(anim.to_jshtml())
```