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

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([[1139.12118857, 834.75692667, 431.59553909, 1933.69068 ,

535.19893364, 1671.26016195, 1016.90369993, 205.89704533,

802.30121762, 1614.25453631],

[ 975.74670056, 1014.50516629, 1622.5720159 , 1687.81955266,

355.28066874, 1795.56221913, 1390.05491204, 1965.18470341,

990.87375482, 1739.27324094]])

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 array by a array – and get a 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 and the y velocities over .

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

array([[ 0.81167039, 6.56034383, 5.93374497, 1.70865358,

1.44797375, 7.97679971, 9.9658176 , 7.70999084,

7.47443724, 1.07073215],

[-19.04407841, 14.52219186, -4.53789567, 10.42665951,

9.1768477 , -12.13402252, -16.42034841, -6.04480051,

-11.94098305, -16.26647181]])

Flying in a straight lines

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

we just do:

position += 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 0x7f480beaf470>

add in plot file

Then, we define a function which updates the figure for each time step.

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
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([[ 168.71212355, 198.27130197, 128.31692158, 155.71554998],

[ 939.3189024 , 1021.58008427, 1004.90060243, 945.43225348]])

velocities

array([[ 7.48284669, 0.02336254, 5.57540396, 8.26395788],

[ 12.90869553, -16.0128998 , 9.90418773, 12.29887078]]

middle = np.mean(positions, 1)
middle

array([162.75397427, 977.80796065])

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

array([[ 5.95814928, 35.5173277 , -34.43705269, -7.03842429],

[-38.48905824, 43.77212362, 27.09264179, -32.37570717]])

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())

Avoiding collisions

We’ll want to add our other flocking rules to the behaviour of the Boids.

We’ll need a matrix giving the distances between each bird. This should be $N \times N$

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

We might think that we need to do the X-distances and Y-distances separately:

xpos = positions[0, :]
xsep_matrix = xpos[:, np.newaxis] - xpos[np.newaxis, :]
xsep_matrix.shape

(4, 4)

xsep_matrix

array([[ 0. , 13.12557316, 16.73339323, 31.99310107],

[-13.12557316, 0. , 3.60782008, 18.86752792],

[-16.73339323, -3.60782008, 0. , 15.25970784],

[-31.99310107, -18.86752792, -15.25970784, 0. ]])

But in NumPy we can be cleverer than that, and make a $2 \times N \times N$ matrix of separations:

separations = positions[:, np.newaxis, :] - positions[:, :, np.newaxis]
separations.shape

(2, 4, 4)

And then we can get the sum-of-squares like this:

squared_displacements = separations * separations
square_distances = np.sum(squared_displacements, 0)
square_distances

array([[ 0. , 4958.52769981, 11949.17097576, 14578.08095394],

[ 4958.52769981, 0. , 1521.65515301, 2587.71303698],

[11949.17097576, 1521.65515301, 0. , 303.41841419],

[14578.08095394, 2587.71303698, 303.41841419, 0. ]])

Now we need to find birds that are too close:

alert_distance = 2000
close_birds = square_distances < alert_distance
close_birds

array([[ True, False, False, False],

[False, True, True, False],

[False, True, True, True],

[False, False, True, True]])

Find the direction distances only to those birds which are too close:

separations_if_close = np.copy(separations)
far_away = np.logical_not(close_birds)

Set x and y values in separations_if_close to zero if they are far away:

separations_if_close[0, :, :][far_away] = 0
separations_if_close[1, :, :][far_away] = 0
separations_if_close

array([[[ 0. , 0. , 0. , 0. ],

[ 0. , 0. , -3.60782008, 0. ],

[ 0. , 3.60782008, 0. , -15.25970784],

[ 0. , 0. , 15.25970784, 0. ]],

[[ 0. , 0. , 0. , 0. ],

[ 0. , 0. , 38.84119961, 0. ],

[ 0. , -38.84119961, 0. , 8.39998398],

[ 0. , 0. , -8.39998398, 0. ]]])

And fly away from them:

np.sum(separations_if_close, 2)

array([[ 0. , -3.60782008, -11.65188776, 15.25970784],

[ 0. , 38.84119961, -30.44121563, -8.39998398]])

velocities = velocities + np.sum(separations_if_close, 2)

Now we can update our animation:

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

    separations = positions[:, np.newaxis, :] - positions[:, :, np.newaxis]
    squared_displacements = separations * separations
    square_distances = np.sum(squared_displacements, 0)
    alert_distance = 100
    far_away = square_distances > alert_distance
    separations_if_close = np.copy(separations)
    separations_if_close[0, :, :][far_away] = 0
    separations_if_close[1, :, :][far_away] = 0
    velocities += np.sum(separations_if_close, 1)

    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())

Match speed with nearby close_birds

This is pretty similar:

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

    separations = positions[:, np.newaxis, :] - positions[:, :, np.newaxis]
    squared_displacements = separations * separations
    square_distances = np.sum(squared_displacements, 0)
    alert_distance = 100
    far_away = square_distances > alert_distance
    separations_if_close = np.copy(separations)
    separations_if_close[0, :, :][far_away] = 0
    separations_if_close[1, :, :][far_away] = 0
    velocities += np.sum(separations_if_close, 1)

    velocity_differences = velocities[:, np.newaxis, :] - velocities[:, :, np.newaxis]
    formation_flying_distance = 10000
    formation_flying_strength = 0.125
    very_far = square_distances > formation_flying_distance
    velocity_differences_if_close = np.copy(velocity_differences)
    velocity_differences_if_close[0, :, :][very_far] = 0
    velocity_differences_if_close[1, :, :][very_far] = 0
    velocities -= np.mean(velocity_differences_if_close, 1) * formation_flying_strength

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


anim = animation.FuncAnimation(figure, animate,
                               frames=200, 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())

Hopefully the power of NumPy should be pretty clear now.

This would be enormously slower and, I think, harder to understand using traditional lists.

Next: Experience - Practical: Numerical Python