Algorithm Search⌘K

Algorithmintro

Boids

Also called Reynolds flocking.

Reynolds's flocking rules of separation, alignment and cohesion, applied by each agent to its nearby agents, which give lifelike flocks without a leader.

Time
O(k r^2) totalO(r^2) per_step
Space
O(r) extra
Where
k = the number of steps; r = the number of boids
Properties
deterministiconlinenot randomized
Origin
Craig W. Reynolds, 1987

Boids are the flocking model of Craig Reynolds (1987). Each agent, a boid, sees only the boids within a radius RR and steers by three rules: separation, move away from boids that are too close; alignment, turn toward the mean velocity of the neighbors; and cohesion, move toward the mean position of the neighbors. The weighted sum of the three rules is the acceleration of the boid, and all boids update at the same time. No boid leads and none knows the whole flock, but the group moves as one flock, turns together, and parts and joins around obstacles. The rules are heuristics: they often give a flock, but they do not guarantee one. They are the classic example of local rules that give a global pattern in swarm robotics.

In plain words

Think of a bird in a large flock. It cannot see the whole flock, only the birds near it.

It follows three simple habits. If a neighbor is too close, it moves away so that they do not hit. It tries to fly in the same direction and at the same speed as its neighbors. And it moves a little toward the middle of its neighbors, so that it does not fall behind alone.

Every bird does the same thing at the same time. Nobody gives orders, and nobody has a plan of the flock. Still, the group soon flies together in one direction, and it bends and turns like a real flock. If the birds see too few neighbors, the flock can split into smaller groups.

The problem

The model. There are rr boids with positions pip_i and velocities viv_i in the plane. Boid ii sees the set Ni={j≠i:∥pj−pi∥≤R}N_i = \{ j \ne i : \lVert p_j - p_i \rVert \le R \}. Time runs in steps of length hh, and in each step all boids read the same snapshot and then move. The parameters are the weights ws,wa,wcw_s, w_a, w_c, a separation radius Rs≤RR_s \le R, a limit AA on the acceleration, and limits smin⁡s_{\min} and smax⁡s_{\max} on the speed.

Input. The start positions and velocities, the parameters, and the number kk of steps.

Output. The positions and velocities after kk steps. There is no exact goal; the usual measures are the order parameter ∥1r∑ivi/∥vi∥∥\left\lVert \frac1r \sum_i v_i / \lVert v_i \rVert \right\rVert, which is 1 when all boids head the same way, the number of groups, and the smallest distance between two boids.

How it differs from close pages. The Laplacian consensus protocol is the alignment rule alone on a fixed graph, and it has a proof. Boids add cohesion, separation and limits, and the graph changes with the positions, so the analysis of the consensus protocol does not carry over. Particle swarm optimization borrows the image of a flock to search for the minimum of a function, which is a different task.

The algorithm

  1. BOIDS(p, v, k)
  2. 1for step = 1 to k do
  3. 2for each boid i, in parallel, do
  4. 3N_i ← { j ≠ i : ‖p_j - p_i‖ ≤ R }
  5. 4s_i ← Σ_{j ∈ N_i, ‖p_i - p_j‖ ≤ R_s} (p_i - p_j) / ‖p_i - p_j‖² ▷ separation
  6. 5a_i ← mean_{j ∈ N_i} v_j - v_i ▷ alignment
  7. 6c_i ← mean_{j ∈ N_i} p_j - p_i ▷ cohesion
  8. 7u_i ← limit(w_s s_i + w_a a_i + w_c c_i, A) ▷ or prioritized allocation
  9. 8v_i ← v_i + h u_i, scaled to a speed in [s_min, s_max]
  10. 9p_i ← p_i + h v_i
  11. 10return p, v

A boid with no neighbors gets ui=0u_i = 0 and flies straight. Line L4 pushes harder the closer a neighbor is, with the inverse square of the distance as in many implementations; other strengths work too. Line L7 either scales the sum down to the norm AA, or uses Reynolds's prioritized acceleration allocation: the requests of separation, alignment and cohesion are taken in this order until their norms use up the budget AA, so that avoiding a collision wins over keeping up with the flock. Line L9 uses the new velocity, which is the symplectic Euler method. Reynolds's paper calls the three rules collision avoidance, velocity matching and flock centering. The implementation uses a full disk as the neighborhood, with no limit on the angle of view.

Example

One boid by hand. Let R=1R = 1, Rs=0.5R_s = 0.5, ws=1.5w_s = 1.5, wa=wc=1w_a = w_c = 1, h=0.1h = 0.1 and no limits. Boid 1 is at (0,0)(0, 0) with velocity (1,0)(1, 0). Boid 2 is at (0.5,0)(0.5, 0) with velocity (0,1)(0, 1), boid 3 at (0,0.8)(0, 0.8) with velocity (1,1)(1, 1), and boid 4 is far away at (3,3)(3, 3).

  • Neighbors (line L3): boids 2 and 3, at distances 0.50.5 and 0.80.8.
  • Separation (line L4): only boid 2 is within RsR_s, so s1=(0−0.5,0)/0.25=(−2,0)s_1 = (0 - 0.5, 0) / 0.25 = (-2, 0).
  • Alignment (line L5): the mean velocity of the neighbors is (0.5,1)(0.5, 1), so a1=(−0.5,1)a_1 = (-0.5, 1).
  • Cohesion (line L6): the mean position is (0.25,0.4)(0.25, 0.4), so c1=(0.25,0.4)c_1 = (0.25, 0.4).
  • Steering (line L7): u1=1.5(−2,0)+(−0.5,1)+(0.25,0.4)=(−3.25,1.4)u_1 = 1.5 (-2, 0) + (-0.5, 1) + (0.25, 0.4) = (-3.25, 1.4).
  • Motion: v1=(1,0)+0.1(−3.25,1.4)=(0.675,0.14)v_1 = (1, 0) + 0.1 (-3.25, 1.4) = (0.675, 0.14), and p1=(0.0675,0.014)p_1 = (0.0675, 0.014).

The boid slows down, because boid 2 is close in front of it, and turns toward boid 3. With the limit A=2A = 2, the plain sum is scaled to about (−1.837,0.791)(-1.837, 0.791). The prioritized allocation instead spends the whole budget on separation, because its request (−3,0)(-3, 0) has norm 3, and gives (−2,0)(-2, 0).

A flock forms, or splits. The implementation places 20 boids at random in a square of side 2.5 with speed 1 and random headings (seed 8), with Rs=0.4R_s = 0.4, A=2A = 2, speeds in [0.5,1][0.5, 1] and h=0.1h = 0.1. At the start the order parameter is 0.1470.147. With R=2R = 2 it is 0.980.98 after 100 steps and stays near that value; after 600 steps there is one group, and no two boids are closer than 0.3270.327. With R=1.5R = 1.5 and the same start, the boids form two groups that fly in different directions, and the order parameter stays near 0.490.49. These numbers are measurements of one run, not guarantees.

Correctness

There is no specification to prove: the rules are heuristics. The proof shows what holds for the step itself. The new states do not depend on the order of the boids, and the step commutes with rotations, reflections and translations, so the boids need no common compass. On a complete graph without separation and without limits, the step is linear. Then the mean velocity never changes, alignment alone is a consensus step that brings all velocities to the mean, cohesion alone makes the boids oscillate about the center without settling, and both together, for a small enough step hh, make the flock contract to one point that moves with the mean velocity. Separation, a radius smaller than the flock, and the limits make the step nonlinear and the graph time-varying, and then the flock can split, as in the example.

Proof: The boids step is equivariant under relabeling and rigid motions, alignment alone is a consensus step, and on a complete graph alignment with cohesion makes the flock contract to one moving pointfull

Boids are not an algorithm with a specification that can be proved; the three rules are heuristics, and a run can split, stall or collide. What can be proved are structural facts of the step and the behavior of the linear part of the rules in the simplest case. Line numbers refer to the pseudocode on the boids page.

There are rr boids with positions pip_i and velocities viv_i in the plane, a neighbor radius RR, a separation radius RsR_s, weights ws,wa,wc≥0w_s, w_a, w_c \ge 0, a time step h>0h > 0, an acceleration limit AA and speed limits 0≤smin⁡≤smax⁡0 \le s_{\min} \le s_{\max}. Ni={j≠i:∥pj−pi∥≤R}N_i = \{ j \ne i : \lVert p_j - p_i \rVert \le R \}. One step computes, for every ii from the same snapshot, the steering uiu_i of lines L3 to L7 and then vi′=clamp⁡(vi+hui)v_i' = \operatorname{clamp}(v_i + h u_i) and pi′=pi+hvi′p_i' = p_i + h v_i' (lines L8 and L9), where the clamp scales a nonzero vector to a norm in [smin⁡,smax⁡][s_{\min}, s_{\max}] and does not change its direction.

Lemma 1 (relabeling). If the boids are listed in another order, the step gives the same new states in that order.

Proof. Every quantity in lines L3 to L9 for boid ii is a function of (pi,vi)(p_i, v_i) and of the set {(pj,vj):j≠i}\{(p_j, v_j) : j \ne i\}, through sums and means over NiN_i, which do not depend on the order. □\square

Lemma 2 (rigid motions). Let g(x)=Qx+bg(x) = Qx + b with QQ a rotation or reflection matrix and bb a vector. If every pip_i is replaced by g(pi)g(p_i) and every viv_i by QviQ v_i, then the step gives g(pi′)g(p_i') and Qvi′Q v_i'.

Proof. Distances do not change, so NiN_i and the test ∥pi−pj∥≤Rs\lVert p_i - p_j \rVert \le R_s do not change. Differences pi−pjp_i - p_j become Q(pi−pj)Q(p_i - p_j), and the separation term, which is ∑(pi−pj)/∥pi−pj∥2\sum (p_i - p_j) / \lVert p_i - p_j \rVert^2, becomes QQ times itself. The alignment term is a difference of velocities and the cohesion term is a difference of positions, so both become QQ times themselves. So uiu_i becomes QuiQ u_i. The norm limits of lines L7 and L8 only scale vectors by factors that depend on norms, and ∥Qx∥=∥x∥\lVert Q x \rVert = \lVert x \rVert, so they commute with QQ. The prioritized allocation also uses only the norms of the requests. Then vi′↦Qvi′v_i' \mapsto Q v_i' and pi+hvi′↦Qpi+b+hQvi′=g(pi′)p_i + h v_i' \mapsto Q p_i + b + h Q v_i' = g(p_i'). □\square

Lemma 3 (the linear part on a complete graph). Let RR be larger than the diameter of the flock at all times, so NiN_i is all other boids, let ws=0w_s = 0, and let there be no limits. With κ=r/(r−1)\kappa = r / (r - 1), pˉ=1r∑jpj\bar p = \frac1r \sum_j p_j and vˉ=1r∑jvj\bar v = \frac1r \sum_j v_j, the step is

vi′=vi+hκ(wa(vˉ−vi)+wc(pˉ−pi)),pi′=pi+hvi′.v_i' = v_i + h \kappa \left( w_a (\bar v - v_i) + w_c (\bar p - p_i) \right), \qquad p_i' = p_i + h v_i'.

Proof. The mean of the other velocities is rvˉ−vir−1\frac{r \bar v - v_i}{r - 1}, and minus viv_i this is rr−1(vˉ−vi)\frac{r}{r - 1} (\bar v - v_i). The same holds for positions. □\square

Lemma 4 (center of mass). Under the assumptions of Lemma 3, vˉ′=vˉ\bar v' = \bar v and pˉ′=pˉ+hvˉ\bar p' = \bar p + h \bar v. So the mean velocity never changes, and the center of mass moves on a straight line at constant speed.

Proof. Average the formulas of Lemma 3 over ii: the averages of vˉ−vi\bar v - v_i and of pˉ−pi\bar p - p_i are zero. □\square

Theorem 1 (alignment alone is a consensus step). Under the assumptions of Lemma 3 with wc=0w_c = 0, the velocity errors ei=vi−vˉe_i = v_i - \bar v satisfy ei′=(1−hκwa)eie_i' = (1 - h \kappa w_a) e_i. So all velocities converge to vˉ\bar v if and only if 0<hκwa<20 < h \kappa w_a < 2.

Proof. By Lemmas 3 and 4, vi′−vˉ′=vi−vˉ−hκwa(vi−vˉ)v_i' - \bar v' = v_i - \bar v - h \kappa w_a (v_i - \bar v). □\square

This is the Laplacian consensus protocol on the complete graph with the weights wa/(r−1)w_a / (r - 1).

Theorem 2 (cohesion alone does not settle). Under the assumptions of Lemma 3 with wa=0w_a = 0 and 0<h2κwc<40 < h^2 \kappa w_c < 4, let xi=pi−pˉx_i = p_i - \bar p and yi=vi−vˉy_i = v_i - \bar v. Then (xi′,yi′)=M(xi,yi)(x_i', y_i') = M (x_i, y_i) in each coordinate with

M=(1−h2κwch−hκwc1),det⁡M=1.M = \begin{pmatrix} 1 - h^2 \kappa w_c & h \\ -h \kappa w_c & 1 \end{pmatrix}, \qquad \det M = 1.

So no nonzero deviation goes to zero: the boids oscillate about the center of mass.

Proof. By Lemma 3, yi′=yi−hκwcxiy_i' = y_i - h \kappa w_c x_i and xi′=xi+hyi′x_i' = x_i + h y_i', which gives MM. Its determinant is (1−h2κwc)+h2κwc=1(1 - h^2 \kappa w_c) + h^2 \kappa w_c = 1. Its trace T=2−h2κwcT = 2 - h^2 \kappa w_c lies in (−2,2)(-2, 2), so the roots of z2−Tz+1z^2 - T z + 1 are two distinct complex conjugate numbers zz and zˉ\bar z with zzˉ=1z \bar z = 1, both of modulus one. Then MM is diagonalizable over the complex numbers, and Mk=Sdiag⁡(zk,zˉk)S−1M^k = S \operatorname{diag}(z^k, \bar z^k) S^{-1} with ∣zk∣=1|z^k| = 1. If Mkw→0M^k w \to 0 for a vector ww, then diag⁡(zk,zˉk)S−1w→0\operatorname{diag}(z^k, \bar z^k) S^{-1} w \to 0, so S−1w=0S^{-1} w = 0 and w=0w = 0. □\square

Theorem 3 (alignment and cohesion contract the flock). Under the assumptions of Lemma 3 with wa,wc>0w_a, w_c > 0, let a=hκwaa = h \kappa w_a and c=h2κwcc = h^2 \kappa w_c. If a<2a < 2 and c+2a<4c + 2a < 4, then every pi−pˉp_i - \bar p and every vi−vˉv_i - \bar v goes to zero geometrically, so the flock contracts to one point that moves with the constant velocity vˉ\bar v.

Proof. As in Theorem 2, yi′=(1−a)yi−hκwcxiy_i' = (1 - a) y_i - h \kappa w_c x_i and xi′=xi+hyi′x_i' = x_i + h y_i', so the deviation in each coordinate is multiplied by

M=(1−ch(1−a)−hκwc1−a),D=det⁡M=1−a,T=tr⁡M=2−c−a.M = \begin{pmatrix} 1 - c & h (1 - a) \\ -h \kappa w_c & 1 - a \end{pmatrix}, \qquad D = \det M = 1 - a, \qquad T = \operatorname{tr} M = 2 - c - a.

The eigenvalues are the roots of z2−Tz+Dz^2 - T z + D. A real quadratic z2−Tz+Dz^2 - T z + D has both roots in the open unit disk if and only if ∣D∣<1|D| < 1 and ∣T∣<1+D|T| < 1 + D (the Schur-Cohn or Jury test for degree two). Here ∣D∣<1|D| < 1 because 0<a<20 < a < 2. Next T<1+DT < 1 + D is 2−c−a<2−a2 - c - a < 2 - a, which holds because c>0c > 0. Last −T<1+D-T < 1 + D is c+a−2<2−ac + a - 2 < 2 - a, that is c+2a<4c + 2a < 4. So the spectral radius of MM is less than one, and Mk→0M^k \to 0 geometrically. ■\blacksquare

What is not proved here. With separation, a neighbor radius smaller than the flock, or the limits on acceleration and speed, the step is nonlinear and its graph changes over time. The flock can then split into groups, as the example on the page shows, and nothing above says that the boids align, stay together or avoid collisions. Results of this kind need other rules and assumptions, such as the flocking algorithms with potential functions of Olfati-Saber (2006), or the connectivity conditions of Jadbabaie, Lin and Morse (2003) for the Vicsek model; they are not proved here.

Complexity

  • Per step. Line L3 checks all pairs, which takes O(r2)O(r^2) time in the real RAM model. Lines L4 to L9 take O(∣Ni∣)O(|N_i|) time for boid ii, so O(r+m)O(r + m) for all boids, where mm is the number of pairs within distance RR.
  • With a grid. A uniform grid or spatial hashing with cells of side RR finds the neighbors by fixed-radius near neighbors search, in expected time O(r+m)O(r + m) per step when the boids are spread out, which makes the step linear in the size of the neighbor graph.
  • Steps. There is no bound on the number of steps until a flock forms, because a flock need not form.
  • Space. O(r)O(r) for the states and the new states.

Properties

  • Local and leaderless. Each boid uses only its own state and its neighbors.
  • Synchronous. All boids read one snapshot; updating boids one by one gives a different, order-dependent model.
  • Equivariant. Relabeling, translations and rotations of the start give the same motion, relabeled, moved or rotated.
  • Heuristic. No guarantee of a single flock, of alignment, or of no collisions.
  • Deterministic. The rules have no noise; the Vicsek model adds noise to the headings.

Variants and improvements

  • Vicsek model. Vicsek et al. (1995) kept only alignment, with constant speed and a random error in the heading, and found a transition from disorder to order as the density grows or the noise falls. Jadbabaie, Lin and Morse (2003) proved agreement of the headings for the noise-free model when the neighbor graph is connected often enough.
  • Provable flocking. Olfati-Saber (2006) replaced cohesion and separation by the gradient of a pair potential with a preferred distance and added velocity consensus, and proved that the flock keeps its shape, agrees on velocity and avoids collisions under stated conditions.
  • Field of view and obstacles. Many implementations let a boid see only in front of it and add rules for obstacles, goals and leaders, which is common in games and films.
  • Robots. On real robots, separation is replaced by a collision avoidance method with guarantees, such as reciprocal velocity obstacles or ORCA, and the boids rules give the preferred velocity.

When to use it

Use boids for animation, games and simulations of crowds, birds and fish, where a lifelike group motion matters more than a guarantee, and as a simple baseline for the motion of a robot swarm. Use the Laplacian consensus protocol or provable flocking laws when the group must agree or stay together for sure, and a collision avoidance method with guarantees when robots must not touch.

Pitfalls

  • Splitting. With a small neighbor radius the flock breaks into groups that never meet again, because boids that see no one fly straight.
  • Weights. Too much cohesion makes the flock oscillate and clump, too much separation makes it spread out, and good weights depend on the radius, the speed and the step.
  • Large steps. The explicit step can overshoot when hh times the weights is large, as for the consensus step; the linear analysis gives the bound in the simplest case.
  • Collisions. Separation is a soft rule. Boids can still pass through each other when they meet at high speed or when the acceleration limit is low.
  • Quadratic cost. Checking all pairs is slow for large flocks; use a grid for the neighbor search.
  • Snapshot. Updating each boid in place, so that later boids see the new states of earlier ones, makes the result depend on the order.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

boids.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/boids/. The authors are listed in prov/PDJW2G.jsonl.

"""Boids: Reynolds's three steering rules for a flock of agents in the plane.

Each boid i looks at the boids within the radius R and computes
  separation  sum over close neighbors of (p_i - p_j) / |p_i - p_j|^2,
  alignment   mean velocity of the neighbors minus v_i,
  cohesion    mean position of the neighbors minus p_i.
The weighted rules give a steering acceleration. The acceleration is limited
(optionally by prioritized allocation, separation first), the velocity is
kept between a minimum and a maximum speed, and all boids move at once.
The rules are heuristics; nothing here guarantees a flock.
"""

import math
import random
from dataclasses import dataclass
from typing import Sequence

Vec = tuple[float, float]


@dataclass
class Params:
    radius: float = 1.0        # neighbor radius R
    sep_radius: float = 0.4    # separation acts only within this distance
    w_sep: float = 1.5
    w_ali: float = 1.0
    w_coh: float = 1.0
    max_accel: float = math.inf
    min_speed: float = 0.0
    max_speed: float = math.inf
    dt: float = 0.1
    prioritized: bool = False  # allocate max_accel to separation, then alignment, then cohesion


def _norm(v: Vec) -> float:
    return math.hypot(v[0], v[1])


def _scale(v: Vec, s: float) -> Vec:
    return (v[0] * s, v[1] * s)


def _add(a: Vec, b: Vec) -> Vec:
    return (a[0] + b[0], a[1] + b[1])


def _clamp_norm(v: Vec, lo: float, hi: float) -> Vec:
    n = _norm(v)
    if n > hi:
        return _scale(v, hi / n)
    if 0 < n < lo:
        return _scale(v, lo / n)
    return v


def neighbors(i: int, pos: Sequence[Vec], radius: float) -> list[int]:
    return [j for j in range(len(pos)) if j != i and math.dist(pos[i], pos[j]) <= radius]


def rules(i: int, pos: Sequence[Vec], vel: Sequence[Vec], prm: Params) -> tuple[Vec, Vec, Vec]:
    """The three raw steering vectors (separation, alignment, cohesion) of boid i."""
    nb = neighbors(i, pos, prm.radius)  # @line L3
    if not nb:
        return (0.0, 0.0), (0.0, 0.0), (0.0, 0.0)
    px, py = pos[i]
    sx = sy = 0.0
    for j in nb:  # @line L4
        dx, dy = px - pos[j][0], py - pos[j][1]
        d2 = dx * dx + dy * dy
        if 0 < d2 <= prm.sep_radius ** 2:
            sx, sy = sx + dx / d2, sy + dy / d2
    k = len(nb)
    mvx = sum(vel[j][0] for j in nb) / k
    mvy = sum(vel[j][1] for j in nb) / k
    ali = (mvx - vel[i][0], mvy - vel[i][1])  # @line L5
    cx = sum(pos[j][0] for j in nb) / k
    cy = sum(pos[j][1] for j in nb) / k
    coh = (cx - px, cy - py)  # @line L6
    return (sx, sy), ali, coh


def allocate(requests: Sequence[Vec], budget: float) -> Vec:
    """Prioritized acceleration allocation: take requests in order until the budget is used."""
    acc, left = (0.0, 0.0), budget
    for r in requests:
        n = _norm(r)
        if n <= left:
            acc, left = _add(acc, r), left - n
        else:
            if n > 0:
                acc = _add(acc, _scale(r, left / n))
            break
    return acc


def steer(i: int, pos: Sequence[Vec], vel: Sequence[Vec], prm: Params) -> Vec:
    sep, ali, coh = rules(i, pos, vel, prm)
    req = [_scale(sep, prm.w_sep), _scale(ali, prm.w_ali), _scale(coh, prm.w_coh)]  # @line L7
    if prm.prioritized:
        return allocate(req, prm.max_accel)
    acc = _add(_add(req[0], req[1]), req[2])
    return _clamp_norm(acc, 0.0, prm.max_accel)


def step(pos: Sequence[Vec], vel: Sequence[Vec], prm: Params) -> tuple[list[Vec], list[Vec]]:
    """One synchronous step of the whole flock (semi-implicit Euler)."""
    acc = [steer(i, pos, vel, prm) for i in range(len(pos))]  # @line L2
    new_v = [_clamp_norm(_add(v, _scale(a, prm.dt)), prm.min_speed, prm.max_speed)  # @line L8
             for v, a in zip(vel, acc)]
    new_p = [_add(p, _scale(v, prm.dt)) for p, v in zip(pos, new_v)]  # @line L9
    return new_p, new_v  # @line L10


def simulate(pos: Sequence[Vec], vel: Sequence[Vec], prm: Params, steps: int):
    p = [tuple(map(float, x)) for x in pos]
    v = [tuple(map(float, x)) for x in vel]
    for _ in range(steps):  # @line L1
        p, v = step(p, v, prm)
    return p, v


def order_parameter(vel: Sequence[Vec]) -> float:
    """|mean of the unit headings|: 1 when all boids head the same way, near 0 when random."""
    hx = hy = 0.0
    for v in vel:
        n = _norm(v)
        if n > 0:
            hx, hy = hx + v[0] / n, hy + v[1] / n
    return math.hypot(hx, hy) / len(vel)


def random_flock(n: int, rng: random.Random, box: float = 3.0, speed: float = 1.0):
    pos = [(rng.uniform(0, box), rng.uniform(0, box)) for _ in range(n)]
    vel = []
    for _ in range(n):
        a = rng.uniform(0, 2 * math.pi)
        vel.append((speed * math.cos(a), speed * math.sin(a)))
    return pos, vel
test_boids.py 145 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/boids/. The authors are listed in prov/PDJW2G.jsonl.

import math
import random

from boids import Params, allocate, order_parameter, random_flock, rules, simulate, step


def close(a, b, tol=1e-9):
    return all(math.dist(x, y) <= tol for x, y in zip(a, b))


def brute_rules(i, pos, vel, prm):
    nb = [j for j in range(len(pos)) if j != i and math.dist(pos[i], pos[j]) <= prm.radius]
    if not nb:
        return (0.0, 0.0), (0.0, 0.0), (0.0, 0.0)
    sep = [0.0, 0.0]
    for j in nb:
        d = math.dist(pos[i], pos[j])
        if 0 < d <= prm.sep_radius:
            for c in range(2):
                sep[c] += (pos[i][c] - pos[j][c]) / d / d
    ali = tuple(sum(vel[j][c] for j in nb) / len(nb) - vel[i][c] for c in range(2))
    coh = tuple(sum(pos[j][c] for j in nb) / len(nb) - pos[i][c] for c in range(2))
    return tuple(sep), ali, coh


def test_hand_example() -> None:
    prm = Params(radius=1.0, sep_radius=0.5)
    pos = [(0.0, 0.0), (0.5, 0.0), (0.0, 0.8), (3.0, 3.0)]
    vel = [(1.0, 0.0), (0.0, 1.0), (1.0, 1.0), (-1.0, 0.0)]
    sep, ali, coh = rules(0, pos, vel, prm)
    assert close([sep], [(-2.0, 0.0)])
    assert close([ali], [(-0.5, 1.0)])
    assert close([coh], [(0.25, 0.4)])
    assert rules(3, pos, vel, prm) == ((0.0, 0.0), (0.0, 0.0), (0.0, 0.0))


def test_rules_against_brute_force() -> None:
    rng = random.Random(1)
    prm = Params(radius=1.2, sep_radius=0.5)
    for _ in range(50):
        pos, vel = random_flock(rng.randrange(1, 12), rng)
        for i in range(len(pos)):
            got, want = rules(i, pos, vel, prm), brute_rules(i, pos, vel, prm)
            assert close(got, want)


def test_permutation_equivariance() -> None:
    rng = random.Random(2)
    prm = Params(max_accel=2.0, min_speed=0.5, max_speed=2.0)
    pos, vel = random_flock(10, rng)
    perm = list(range(10))
    rng.shuffle(perm)
    p1, v1 = step(pos, vel, prm)
    p2, v2 = step([pos[k] for k in perm], [vel[k] for k in perm], prm)
    assert close(p2, [p1[k] for k in perm], 1e-12) and close(v2, [v1[k] for k in perm], 1e-12)


def test_translation_and_rotation_invariance() -> None:
    rng = random.Random(3)
    prm = Params(max_accel=3.0, min_speed=0.3, max_speed=2.0, prioritized=True)
    pos, vel = random_flock(12, rng)
    c, s, t = math.cos(0.7), math.sin(0.7), (5.0, -2.0)
    rot = lambda v: (c * v[0] - s * v[1], s * v[0] + c * v[1])
    p1, v1 = simulate(pos, vel, prm, 20)
    p2, v2 = simulate([rot(p) for p in pos], [rot(v) for v in vel], prm, 20)
    assert close(p2, [rot(p) for p in p1], 1e-9) and close(v2, [rot(v) for v in v1], 1e-9)
    p3, v3 = simulate([(p[0] + t[0], p[1] + t[1]) for p in pos], vel, prm, 20)
    assert close(p3, [(p[0] + t[0], p[1] + t[1]) for p in p1], 1e-9) and close(v3, v1, 1e-9)


def test_alignment_alone_is_consensus() -> None:
    rng = random.Random(4)
    prm = Params(radius=100.0, w_sep=0.0, w_coh=0.0, w_ali=1.0, dt=0.1)
    pos, vel = random_flock(8, rng)
    mean0 = tuple(sum(v[c] for v in vel) / 8 for c in range(2))
    p, v = simulate(pos, vel, prm, 200)
    mean1 = tuple(sum(x[c] for x in v) / 8 for c in range(2))
    assert math.dist(mean0, mean1) < 1e-12
    assert max(math.dist(x, mean0) for x in v) < 1e-9


def spread(q):
    c = tuple(sum(x[k] for x in q) / len(q) for k in range(2))
    return max(math.dist(x, c) for x in q)


def test_cohesion_alone_oscillates_about_a_fixed_center() -> None:
    rng = random.Random(5)
    prm = Params(radius=100.0, w_sep=0.0, w_ali=0.0, w_coh=1.0)
    pos, _ = random_flock(7, rng)
    vel = [(0.0, 0.0)] * 7
    c0 = tuple(sum(p[c] for p in pos) / 7 for c in range(2))
    p, v = pos, vel
    late = []
    for k in range(200):
        p, v = step(p, v, prm)
        if k >= 100:
            late.append(spread(p))
    c1 = tuple(sum(x[c] for x in p) / 7 for c in range(2))
    assert math.dist(c0, c1) < 1e-12
    assert max(late) > 0.5 * spread(pos)


def test_cohesion_with_alignment_contracts() -> None:
    rng = random.Random(8)
    prm = Params(radius=100.0, w_sep=0.0, w_ali=1.0, w_coh=1.0, dt=0.1)
    pos, vel = random_flock(7, rng)
    p, v = simulate(pos, vel, prm, 400)
    assert spread(p) < 1e-6 * spread(pos)
    assert spread(v) < 1e-6


def test_separation_pushes_apart() -> None:
    prm = Params(radius=1.0, sep_radius=0.5, w_ali=0.0, w_coh=0.0)
    p, _ = simulate([(0.0, 0.0), (0.2, 0.0)], [(0.0, 0.0), (0.0, 0.0)], prm, 5)
    assert p[0][0] < 0.0 < 0.2 < p[1][0] and abs(p[0][1]) < 1e-15


def test_prioritized_allocation() -> None:
    assert allocate([(3.0, 0.0), (0.0, 4.0)], 10.0) == (3.0, 4.0)
    assert allocate([(3.0, 0.0), (0.0, 4.0)], 5.0) == (3.0, 2.0)
    assert allocate([(6.0, 0.0), (0.0, 4.0)], 5.0) == (5.0, 0.0)


def test_limits_hold() -> None:
    rng = random.Random(6)
    prm = Params(max_accel=1.0, min_speed=0.5, max_speed=1.5, dt=0.1)
    pos, vel = random_flock(15, rng)
    for _ in range(30):
        new_p, new_v = step(pos, vel, prm)
        for v0, v1 in zip(vel, new_v):
            assert 0.5 - 1e-12 <= math.hypot(*v1) <= 1.5 + 1e-12
        pos, vel = new_p, new_v


def test_flock_aligns_on_this_seed() -> None:
    rng = random.Random(7)
    prm = Params(radius=2.0, sep_radius=0.4, max_accel=2.0, min_speed=0.5, max_speed=1.0)
    pos, vel = random_flock(20, rng, box=2.5)
    before = order_parameter(vel)
    _, v = simulate(pos, vel, prm, 300)
    assert before < 0.5 < 0.95 < order_parameter(v)

History

Craig Reynolds presented the boids at SIGGRAPH in 1987, with the three behaviors, a local neighborhood, and the prioritized allocation of acceleration, as a way to animate flocks without a script for each bird. Vicsek et al. (1995) studied the alignment rule with noise as a model in statistical physics. Jadbabaie, Lin and Morse (2003) gave the first proof of heading agreement for the Vicsek rule, and Olfati-Saber (2006) gave flocking algorithms with proofs, which links the boids to consensus and to multi-robot control.

References

  1. Craig W. Reynolds, Flocks, herds, and schools, a distributed behavioral model, Computer Graphics 21(4), Proceedings of SIGGRAPH 1987, pages 25 to 34 (the three behaviors, the local neighborhood, and the prioritized acceleration allocation)
  2. Tamas Vicsek, Andras Czirok, Eshel Ben-Jacob, Inon Cohen and Ofer Shochet, Novel type of phase transition in a system of self-driven particles, Physical Review Letters 75(6), 1995, pages 1226 to 1229 (constant speed particles that take the mean heading of their neighbors plus noise)
  3. Ali Jadbabaie, Jie Lin and A. Stephen Morse, Coordination of groups of mobile autonomous agents using nearest neighbor rules, IEEE Transactions on Automatic Control 48(6), 2003, pages 988 to 1001 (agreement of headings in the Vicsek model)
  4. Reza Olfati-Saber, Flocking for multi-agent dynamic systems, algorithms and theory, IEEE Transactions on Automatic Control 51(3), 2006, pages 401 to 420 (flocking algorithms with potential functions and proofs of cohesion, velocity agreement and collision avoidance)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.per_step
  • a full proof of time.total
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example