02 Feb 2023

Python Playground Chapter 5: Reynold's Boids!

In October 2022, I started reading Python Playground and wrote an article to mark the day I started.

Simulation

As of today, I finished reading and coding for the fifth chapter of Python Playground - a simple simulation of a flock of birds.

Boids is an artificial simulation developed by Craig Reynolds to replicate the behavior of flocks of birds. The simulation follows a few simple rules:

  1. There has to be a minimum distance between the boids.
  2. The boids are pointed in the average direction of the flock’s movement.
  3. Each boid is moved towards the center of mass of its local flockmates.

The Simulation

The boids in the simulation are represented by a dark circle (the body) and a red circle (the beak). The beak indicates the direction the boid is facing.

The canvas itself follows rules similar to those of Conway’s game of life, but instead of taking the form of a torus, Reynold’s Boids use a continuous-space tiled boundary condition.

def applyBC(self):
        deltaR = 2.0
        for coord in self.pos:
            if coord[0] > width + deltaR:
                coord[0] = - deltaR
            if coord[0] < - deltaR:
                coord[0] = width + deltaR
            if coord[1] > height + deltaR:
                coord[1] = - deltaR
            if coord[1] < - deltaR:
                coord[1] = height + deltaR

As a result of these conditions, any bird that crosses the boundary ends up on the opposite side with the same velocity.

The rules of the simulation are then applied to the boids and a vector vel is added to the position of the boids to update their position with.

def applyRules(self):
        D = self.distMatrix < 25.0
        vel = self.pos*D.sum(axis=1).reshape(self.N, 1) - D.dot(self.pos)
        self.limit(vel, self.maxRuleVel)

        D = self.distMatrix < 50.0

        vel2 = D.dot(self.vel)
        self.limit(vel, self.maxRuleVel)
        vel += vel2

        vel3 = D.dot(self.pos) - self.pos
        self.limit(vel3, self.maxRuleVel)
        vel += vel3
        return vel

The first rule is maintaining a minimum distance of 25 units. The second rule is aligning the birds to the direction of the flock’s movement. D represents the matrix of distances between each boid in the simulation. The third rule is applying the movement towards the center of mass. All three rules are limited to make sure the velocities do not increase indefinitely.

Finally as a part of the homework, right-clicking on the simulation blows the birds in a random direction as if a gust of wind blew through them.

Simulation

That’s all I have for now. Live long and prosper.

References

Python Playground

Electronut Labs

My Code For This Chapter