Collective behaviour as computation
A flock of birds turns as one body although no bird leads it. Reynolds reproduced this with three local rules for each simulated bird: avoid crowding neighbours, align with their heading, and move towards their centre [1]. Ant colonies find short paths between nest and food without a map, because ants deposit pheromone and prefer trails with more of it; shorter trails are completed faster and accumulate pheromone sooner. Honeybee colonies allocate foragers to flower patches in proportion to their quality through the waggle dance. These systems share decentralised control, simple agents, local interaction and emergent global behaviour, which Bonabeau, Dorigo and Theraulaz summarised as swarm intelligence [2].
Animation: Three rules make a flock
Each arrow follows only its neighbours. Set separation, alignment and cohesion and watch order emerge or dissolve. With alignment at zero, the flock never forms a common heading.
Formulas: The three rules of a flock
Each simulated bird has a position and a velocity , both vectors in the plane. Its neighbours are the birds within a radius , and is their number. Reynolds' three rules become three steering vectors [1]. Cohesion points from the bird to the centre of its neighbours, alignment is the difference between their mean velocity and its own, and separation points away from every neighbour closer than a smaller radius :
Here is the distance between the two birds, so each separation term is a vector of length one. The velocity changes by a weighted sum of the three vectors, and the bird then moves by its velocity:
The weights , and are the sliders of the animation, and the constants , and scale them to the units of the animation, in which the width of the field is 1. The animation also keeps every speed between 0.002 and 0.008 per step.
Worked example: One step of one bird
A bird at flies with . The neighbourhood radius is and the separation radius . Two other birds are near: bird A at (0.52, 0.31) with velocity (0.003, 0.002), and bird B at (0.56, 0.34) with velocity (0.006, 0.001). The weights are , and .
Step 1. Distances.
Both birds are neighbours, because both distances are below 0.09, but only A is closer than 0.03.
Step 2. Cohesion. The centre of the neighbours is , so .
Step 3. Alignment. The mean velocity is , so .
Step 4. Separation. Only A counts: .
Step 5. The new velocity and position. The three factors are , and :
The speed lies inside the allowed range. The bird turns away from A, which is too close, and slightly towards the group, which is the behaviour that the animation shows for the whole flock.
Particle swarm optimisation
Kennedy and Eberhart introduced particle swarm optimisation in 1995, inspired by bird flocking and social behaviour [3]. Each particle i has a position x, which is a candidate solution, and a velocity v. It remembers the best position p it has visited, and the swarm shares the best position g found by any particle. In every iteration, the velocity is updated as v = w v + c1 r1 (p - x) + c2 r2 (g - x), and the position as x = x + v, where r1 and r2 are random numbers between 0 and 1 drawn for each dimension.
The three terms have clear meanings. The inertia weight w keeps part of the previous motion; Shi and Eberhart introduced it to balance global and local search, with values around 0.4 to 0.9 [4]. The cognitive term, weighted by c1, pulls a particle back towards its own best experience. The social term, weighted by c2, pulls it towards the best experience of the swarm. Clerc and Kennedy analysed the dynamics and derived a constriction factor that guarantees convergence; the widely used setting w = 0.7298 with c1 = c2 = 1.49618 follows from it [5]. Particle swarms are easy to implement, need no gradients, and work well on continuous problems of moderate dimension, but like every metaheuristic they can stagnate in a local optimum.
Check your understanding. In the velocity update, what does the social term c2 r2 (g - x) do?
Formulas: The particle swarm update
Particle has a position and a velocity . It remembers its personal best position , and the swarm shares the global best position . In every iteration and for every dimension , two new random numbers and between 0 and 1 are drawn, and the particle moves by [3, 4]
The first term is the inertia, the second the cognitive pull towards the particle's own best position, and the third the social pull towards the best position of the swarm. After the move, the particle evaluates its new position and replaces , and possibly , if the new position is better. Clerc and Kennedy showed that the swarm converges when the velocity is multiplied by the constriction factor [5]
which gives the update . This is the inertia form above with and , .
Worked example: The constriction factor
With , so that :
These are the values and quoted in the lecture and used as the defaults of Part A of the interactive lab.
Worked example: One move of one particle
A particle searches the minimum of . It is at with and velocity . Its best position is with , and the swarm's best is with . The random numbers are and for the two dimensions.
Step 1. First dimension.
Step 2. Second dimension.
Step 3. Evaluation and memory.
The new value is better than the personal best 2.5, so becomes (1.108109, 0.849776). It is worse than the global best 0.05, so stays. In the first dimension the social term dominates and pulls the particle towards ; in the second dimension both pulls point upwards, and the particle overshoots , which is the oscillating search that the inertia and constriction keep under control. Part B of the interactive lab decomposes every update of a small swarm in the same way.
Tuning a PID controller with a swarm
The proportional-integral-derivative controller is the workhorse of industrial control. Its three gains shape the response: The proportional gain speeds up the reaction, the integral gain removes steady-state error, and the derivative gain damps oscillation [6]. Tuning them by hand is tedious, and classical rules assume simple process models. Controller tuning can instead be formulated as optimisation: Choose the gains that minimise a cost computed from a simulated step response, such as the integral of the time-weighted absolute error (ITAE), with penalties for overshoot and limits on the actuator. Particle swarms have been used in this way for automatic voltage regulators and many other loops [7].
The notebook applies the method to the speed control of a DC motor, using the standard model and parameters of the Control Tutorials for MATLAB and Simulink [8]. The armature voltage is limited to 24 volts, which makes the problem nonlinear, and the swarm evaluates all particles in one vectorised simulation. The cost function is part of the design: A cost that rewards speed alone drives the gains to their bounds, and adding a penalty on overshoot or control effort changes the optimum. The optimiser serves the engineer's definition of good behaviour; it cannot supply that definition.
Check your understanding. A swarm tunes a PID controller by minimising only the settling time, and the result shows violent oscillation of the actuator. What is the most likely cause?
Formulas: PID control, the DC motor and the cost of a response
A PID controller computes its output from the error between the set point and the measured output [6]:
The integral adds up past errors and removes a steady offset; the derivative reacts to the rate of change and damps the motion. A digital controller with the sampling time replaces the integral by a running sum and the derivative by a difference:
The lab filters the derivative with a time constant s, , and limits the armature voltage to V. The DC motor of the Control Tutorials couples the speed and the armature current [8]:
with inertia kg m², friction N m s, motor constant , resistance Ω and inductance H. At a constant voltage both derivatives vanish, so and , which gives the steady speed
The swarm judges a set of gains by the integral of the time-weighted absolute error over the simulated step response, approximated by a sum over the samples:
Late errors weigh more than early ones, so slow settling and lasting oscillation are expensive [7].
Worked example: The motor without control and the first two samples under PID control
Step 1. Open loop. One volt gives
so a constant voltage of V would be needed for 1 rad/s, and any change of load or friction would shift the speed. Feedback removes this dependence.
Step 2. The first sample, . The controller of the lab uses , and with s and a set point of 1 rad/s. The motor is at rest, so . The integral is ; the previous error is initialised to 1, so and the filtered derivative stays 0. The controller asks for
which the limit cuts to V. The motor equations give, with and ,
and one Euler step of 0.002 s gives and A.
Step 3. The second sample, . The speed is still 0, so , and . The demand V is again cut to 24 V. Now the current drives the rotor:
Step 4. The cost so far. The ITAE sum receives from the first sample and from the second. The voltage stays at its limit for many samples: The controller is saturated, which is the nonlinearity mentioned in the lecture. Part C of the interactive lab continues this table sample by sample for any gains, and Part D lets the swarm choose the gains.
Ant colony optimisation
Dorigo, Maniezzo and Colorni turned the pheromone mechanism into the Ant System for the travelling salesman problem [9]. Each artificial ant builds a complete tour city by city. From city i, it chooses the next unvisited city j with a probability proportional to the pheromone on edge (i, j) raised to a power alpha, times a heuristic desirability, usually the inverse distance, raised to a power beta. After all ants have finished, pheromone evaporates on every edge by a factor rho, and each ant deposits pheromone on the edges of its tour in inverse proportion to the tour length. Short tours therefore reinforce their edges, while evaporation forgets poor early choices.
The Ant Colony System added a stronger exploitation rule and local pheromone updates and was competitive on benchmark instances [10]; the monograph by Dorigo and Stützle presents the family and its applications to routing, scheduling and assignment [11]. Drilling holes in a printed circuit board is a classical travelling salesman application: The drill head must visit every hole once, and the travel time between holes is wasted production time. Benchmark libraries such as TSPLIB include instances that come from drilling problems [12].
Check your understanding. What is the purpose of pheromone evaporation in ant colony optimisation?
Formulas: Ant System and Ant Colony System
An ant at city chooses the next city among the cities it has not visited yet with the probability [9]
where is the pheromone on the edge from to , is the heuristic desirability, the inverse of the distance, and the exponents and set the weight of the two. When all ants have built their tours of lengths , the pheromone evaporates with the rate (rho) and every ant deposits pheromone on the edges of its tour:
The Ant Colony System changes three things [10]. With a probability an ant takes the best edge, , and otherwise it uses the probabilities above. Every ant that crosses an edge reduces its pheromone at once, , so that later ants try other edges. Only the best tour found so far deposits pheromone, .
Worked example: Choosing holes and updating pheromone
A drill must visit four holes at the corners of a rectangle: A , B , C and D , in centimetres. The distances are , and . The parameters are , , and , and all pheromone values start at 1.
Step 1. The first decision of an ant at A. With , only the heuristic matters: , and , which add up to 0.2136. Hence
Step 2. Two tours. Ant 1 builds A, B, C, D, A with length , and ant 2 builds A, C, B, D, A with length . Their deposits are and .
Step 3. Evaporation and deposit. Every edge keeps and receives the deposits of the ants that used it:
| Edge | Length | New pheromone |
|---|---|---|
| AB | 3 | 0.7 + 0.071429 = 0.771429 |
| AC | 5 | 0.7 + 0.055556 = 0.755556 |
| AD | 4 | 0.7 + 0.071429 + 0.055556 = 0.826985 |
| BC | 4 | 0.7 + 0.071429 + 0.055556 = 0.826985 |
| BD | 5 | 0.7 + 0.055556 = 0.755556 |
| CD | 3 | 0.7 + 0.071429 = 0.771429 |
Step 4. The next decision at A. The products are for B, for C and for D, with the sum 0.167615, so
Edge AD, which belongs to both tours, gained weight, and the diagonal AC, which belongs only to the longer tour, lost weight. Over many iterations this feedback concentrates the pheromone on the short tour around the rectangle, of length 14. Part E of the interactive lab repeats these calculations for any parameters and tours, and Part F runs a colony on a drilling sequence and shows the pheromone trails forming.
Artificial bee colony and the metaphor question
Karaboga and Basturk's artificial bee colony algorithm assigns roles to solutions [13]. Employed bees search around their food sources, onlooker bees choose sources in proportion to their quality and search around them, and scout bees replace sources that have not improved for a number of trials with random new ones. The scout phase gives the algorithm a built-in restart mechanism. Many further algorithms followed, inspired by fireflies, bats, wolves, whales and others, including the ant lion optimiser used to train neural networks for chaotic signal prediction in earlier work [14].
Sörensen argued that the flood of metaphor-based algorithms often hides old ideas behind new vocabulary and weak experiments [15]. The no free lunch theorems add that no algorithm can be best on all problems [16]. Engineers should therefore judge a metaheuristic by its search mechanism rather than its metaphor, compare it with established methods on the problem at hand, report results over many independent runs with statistics, and count function evaluations, not iterations, because a single evaluation of an engineering simulation may take minutes.
Check your understanding. A paper claims that a new animal-inspired algorithm beats PSO, based on one run per method with different numbers of function evaluations. What is the main weakness?
Formulas: The artificial bee colony
The colony keeps food sources , each a candidate solution [13]. An employed bee changes one randomly chosen component of its source , using a randomly chosen other source and a random number between and :
and keeps the new source only if it is better. For a minimisation problem with objective values , the fitness of a source is
Onlooker bees choose sources with the probabilities
and search around them in the same way. Every source counts the trials that failed to improve it; a source whose counter exceeds a limit is abandoned, and a scout bee replaces it with a random source [13].
Worked example: Employed bees, onlookers and the scout
The objective is with three sources: with , with , and with .
Step 1. An employed bee at source 1. It changes the second component, , with the partner and :
The new source has , better than 5, so it replaces source 1 and its trial counter returns to 0. Sources 2 and 3 are assumed not to improve in this phase, so their counters rise by one.
Step 2. Fitness and probabilities.
where .
Step 3. An onlooker. The cumulative probabilities are 0.257, 0.7093 and 1. A random number of 0.6 falls between 0.257 and 0.7093, so the onlooker searches around source 2, the best one, exactly as an employed bee would.
Step 4. The scout. If source 3 failed to improve in, say, 20 consecutive trials while the limit is 20, a scout replaces it with a random point of the search region. This restart keeps the colony from stagnating, which is the mechanism behind the metaphor. Part G of the interactive lab runs all three phases with every number shown.
Python step 6: Classes, objects and probabilistic choice
The Python step of this week is part of the Colab notebook, where every explanation stands next to a cell that runs it and the step closes with a quick check and exercises with immediate feedback. The printable lecture notes contain the same step together with the outputs of its code. The Colab button below opens the notebook at the step. Run the setup cell just above the step first, since the exercises use its check function.
Review cards
Select a card to turn it over.
Continue the week
The week continues with the simulation and the self-assessment of the interactive lab and with the Python step and the hands-on work of the Colab notebook. The week overview lists the discipline challenges, the weekly task and the research assignment.
Interactive lab Colab notebook Self-assessment Week overview and tasks
References
[1] Reynolds, C. W. (1987). Flocks, herds and schools: A distributed behavioral model. ACM SIGGRAPH Computer Graphics, 21(4), 25-34. https://doi.org/10.1145/37402.37406
[2] Bonabeau, E., Dorigo, M., & Theraulaz, G. (1999). Swarm Intelligence: From Natural to Artificial Systems. Oxford University Press.
[3] Kennedy, J., & Eberhart, R. (1995). Particle swarm optimization. In Proceedings of ICNN'95, International Conference on Neural Networks, Vol. 4 (pp. 1942-1948). IEEE. https://doi.org/10.1109/ICNN.1995.488968
[4] Shi, Y., & Eberhart, R. (1998). A modified particle swarm optimizer. In 1998 IEEE International Conference on Evolutionary Computation Proceedings (pp. 69-73). IEEE. https://doi.org/10.1109/ICEC.1998.699146
[5] Clerc, M., & Kennedy, J. (2002). The particle swarm: Explosion, stability, and convergence in a multidimensional complex space. IEEE Transactions on Evolutionary Computation, 6(1), 58-73. https://doi.org/10.1109/4235.985692
[6] Åström, K. J., & Hägglund, T. (1995). PID Controllers: Theory, Design, and Tuning (2nd ed.). Instrument Society of America.
[7] Gaing, Z.-L. (2004). A particle swarm optimization approach for optimum design of PID controller in AVR system. IEEE Transactions on Energy Conversion, 19(2), 384-391. https://doi.org/10.1109/TEC.2003.821821
[8] University of Michigan, Carnegie Mellon University, & University of Detroit Mercy (2026). Control Tutorials for MATLAB and Simulink: DC motor speed, system modeling. https://ctms.engin.umich.edu
[9] Dorigo, M., Maniezzo, V., & Colorni, A. (1996). Ant system: Optimization by a colony of cooperating agents. IEEE Transactions on Systems, Man, and Cybernetics, Part B, 26(1), 29-41. https://doi.org/10.1109/3477.484436
[10] Dorigo, M., & Gambardella, L. M. (1997). Ant colony system: A cooperative learning approach to the traveling salesman problem. IEEE Transactions on Evolutionary Computation, 1(1), 53-66. https://doi.org/10.1109/4235.585892
[11] Dorigo, M., & Stützle, T. (2004). Ant Colony Optimization. MIT Press.
[12] Reinelt, G. (1991). TSPLIB: A traveling salesman problem library. ORSA Journal on Computing, 3(4), 376-384. https://doi.org/10.1287/ijoc.3.4.376
[13] Karaboga, D., & Basturk, B. (2007). A powerful and efficient algorithm for numerical function optimization: Artificial bee colony (ABC) algorithm. Journal of Global Optimization, 39(3), 459-471. https://doi.org/10.1007/s10898-007-9149-x
[14] Kose, U. (2018). An ant-lion optimizer-trained artificial neural network system for chaotic electroencephalogram (EEG) prediction. Applied Sciences, 8(9), 1613. https://doi.org/10.3390/app8091613
[15] Sörensen, K. (2015). Metaheuristics: The metaphor exposed. International Transactions in Operational Research, 22(1), 3-18. https://doi.org/10.1111/itor.12001
[16] Wolpert, D. H., & Macready, W. G. (1997). No free lunch theorems for optimization. IEEE Transactions on Evolutionary Computation, 1(1), 67-82. https://doi.org/10.1109/4235.585893