Contents
- 0. Origin and How to Read This Note
- 1. Shared Framework: Black-Box Optimization Without Gradients
- 1.1 Four Problem Classes, One Predicament
- 1.2 Five Shared Building Blocks
- 1.3 Evaluation Budget: The Only Hard Currency
- 1.4 Exploration and Exploitation in Each of the Four Algorithms
- 1.5 Kinship with Reinforcement Learning
- 1.6 Quick Overview of the Four Algorithms
- 2. Particle Swarm Optimization (PSO)
- 2.1 Why It Is Needed: “Swarm Inertial Search” in Continuous Black-Box Spaces
- 2.2 Principles and Formulas
- 2.3 Convergence Conditions and the Stable Parameter Region
- 2.4 Velocity Clamping, Boundary Handling and Topology
- 2.5 Pseudocode: PSO (Full Version, with gbest/lbest, Cache and Out-of-Bounds Handling)
- 2.6 Section-by-Section Walkthrough of the Pseudocode
- 2.7 Per-Step Read/Write and State-Maintenance Checklist
- 2.8 Pitfall Checklist
- 2.9 Scope of Application
- 3. Genetic Algorithms (GA)
- 3.1 Why It Is Needed: “Breeding and Recombination” on Discrete Encodings
- 3.2 The Five Components
- 3.3 The Schema Theorem: Why GA “Exponentially Grows” Good Fragments
- 3.4 The Building Block Hypothesis: How Far It Holds
- 3.5 Mutation Probability: Why 1/l1/l1/l Is Commonly Used
- 3.6 Pseudocode: GA (Generational Model + Elitism, Real-Valued SBX)
- 3.7 Section-by-Section Walkthrough of the Pseudocode
- 3.8 Per-Step Read/Write and State-Maintenance Checklist
- 3.9 Pitfall Checklist
- 3.10 Scope of Application
- 4. Simulated Annealing (SA)
- 4.1 Why It Is Needed: Local Search That Allows “Temporarily Going Downhill”
- 4.2 Principles: The Metropolis Criterion
- 4.3 Why It Converges to the Global Optimum as Temperature Goes to Zero
- 4.4 Cooling Schedules: Logarithmic versus Geometric
- 4.5 Pseudocode: SA (Full Version)
- 4.6 Section-by-Section Walkthrough of the Pseudocode
- 4.7 Per-Step Read/Write and State-Maintenance Checklist
- 4.8 Pitfall Checklist
- 4.9 Scope of Application
- 5. Ant Colony Optimization (ACO)
- 5.1 Why It Is Needed: Treating “a Path” as a Learnable Object
- 5.2 Construction Rule: The Transition Probability
- 5.3 Pheromone Update: Evaporation and Deposition
- 5.4 Pheromone Initialization, the Elitist Strategy and MMAS
- 5.5 Pseudocode: ACO (Unified AS and MMAS)
- 5.6 Section-by-Section Walkthrough of the Pseudocode
- 5.7 Per-Step Read/Write and State-Maintenance Checklist
- 5.8 Pitfall Checklist
- 5.9 Scope of Application
- 6. Cross-Algorithm Summary: Putting the Four Algorithms in One Coordinate System
- 6.1 One Master Table
- 6.2 Six Key Divergences
- 6.3 The Algorithm-Selection Decision Chain
- 6.4 Four Combinations That Are Easiest to Mismatch
- 6.5 One-Page Summary
- 6.6 Three General Principles
- 6.7 Concept Mapping Against Reinforcement Learning
- References
- Appendix: Abbreviation Quick Reference
Metaheuristic Optimization Notes: Principles, Formulas and Pseudocode for PSO, Genetic Algorithms, Simulated Annealing and Ant Colony Optimization
0. Origin and How to Read This Note
This note follows the same writing approach as the site’s Deep Reinforcement Learning Core Algorithms note. That note ran along the main line “Bellman equation → dynamic programming → Monte Carlo → temporal difference → Q-learning/DQN → policy gradient → Actor-Critic → GAE → TRPO → PPO → SAC”, presenting for each algorithm its motivation, formulas, collapsible derivations, complete pseudocode, a section-by-section walkthrough, a gradient-flow and detach checklist, a pitfall checklist, and scope of application. This note carries the same skeleton onto a completely different family of methods: metaheuristic algorithms (a general class of search methods that do not assume the objective function is differentiable or analytically available, and instead approach the optimum through an “evaluate–compare–update” loop).
The reason it is worth writing with the same skeleton is that the two families face strikingly similar engineering difficulties: both must allocate budget between “exploring new regions” and “exploiting existing information”; both fear premature convergence to a local optimum; both have plenty of implementation details where “the formula is one line but the pitfalls are ten”; and both need a checklist for deciding “whether this quantity should be kept or reset”. The difference is only that reinforcement learning decides the next step from gradients or Bellman recursions, whereas metaheuristics decide the next step from random perturbation, population information sharing, and acceptance rules.
Notation conventions (used uniformly throughout):
| Symbol | Meaning |
|---|---|
| one solution (decision variables), a -dimensional real vector; in discrete problems a permutation, a path, or a 0/1 string | |
| the -th component of the solution, | |
| objective function, black box: it can only be evaluated, never differentiated | |
| feasible solution set (search space), defined by bounds and constraints | |
| population size (number of particles in a particle swarm, individuals in a GA, ants in an ACO) | |
| number of function evaluations, the unit in which budget is measured | |
| velocity of the -th particle | |
| inertia weight, controlling how much of the previous velocity is retained | |
| cognitive coefficient and social coefficient | |
| random numbers drawn uniformly from (redrawn for every update and every dimension) | |
| historical best position of particle (personal best) | |
| historical best position of the whole swarm (or neighborhood) (global best) | |
| fitness, the “larger is better” score obtained from by a scaling transform in a GA | |
| crossover probability and mutation probability | |
| temperature, controlling how permissive SA is in accepting worse solutions | |
| initial temperature and final temperature | |
| number of inner-loop iterations at one temperature (Markov chain length) | |
| geometric cooling factor, | |
| pheromone concentration on edge | |
| heuristic information on edge , usually | |
| relative weights of pheromone and heuristic information (subscripted to avoid confusion with the cooling factor ) | |
| evaporation rate | |
| pheromone deposition constant |
Note: the original papers of the four algorithms each use different notation (PSO uses ; GA uses for string length; ACO uses both as pheromone exponents). This note unifies everything into the table above and records the original notation where it first appears in the text. Every step of a derivation states which identity or which assumption it uses, so that it can be verified line by line.
How to read: Chapter 1 is the shared framework, and it explains the problem, the building blocks and the budget that the four algorithms share — if you read only one chapter, read this one. Chapters 2 to 5 expand the algorithms in the order particle swarm → genetic algorithm → simulated annealing → ant colony, and every chapter follows the same skeleton: why it is needed → principles and formulas → collapsible derivations → complete pseudocode → section-by-section walkthrough → per-step read/write and state-maintenance checklist → pitfall checklist → scope of application. Chapter 6 is the cross-cutting summary, containing one master table, six key divergences, one algorithm-selection decision chain, and a “metaheuristics ↔ reinforcement learning” concept-mapping table (this section is the key to understanding “why the two families look so alike”).
The whole note contains 14 collapsible derivations: 2 in Chapter 1 and 3 in each of Chapters 2 through 5. If you only want to re-check the formulas, jump directly to the corresponding derivation through the table below:
| Index | Location | Content of the derivation |
|---|---|---|
| Derivation 1 | 1.2 | Curse of dimensionality: why grid enumeration is infeasible in high dimensions |
| Derivation 2 | 1.4 | What the no-free-lunch theorem says and what it does not say |
| Derivation 3 | 2.2 | Three-term decomposition of the PSO velocity update and its second-order difference form |
| Derivation 4 | 2.3 | Convergence conditions of PSO and its stable parameter region |
| Derivation 5 | 2.4 | Why velocity clamping is equivalent to limiting the single-step exploration radius |
| Derivation 6 | 3.3 | Expected number of offspring under roulette-wheel selection and the schema theorem |
| Derivation 7 | 3.4 | Why crossover can recombine building blocks |
| Derivation 8 | 3.5 | Bounds on the mutation probability and schema survival |
| Derivation 9 | 4.2 | Detailed balance and the Boltzmann stationary distribution |
| Derivation 10 | 4.3 | Why the chain converges to the global optimum as temperature goes to zero |
| Derivation 11 | 4.4 | The trade-off between logarithmic cooling and geometric cooling |
| Derivation 12 | 5.2 | The form of the ACO transition probability and the meaning of its two exponents |
| Derivation 13 | 5.3 | Correspondence between pheromone update and reinforcement learning |
| Derivation 14 | 5.5 | Origin and role of the MMAS pheromone upper and lower bounds |
1. Shared Framework: Black-Box Optimization Without Gradients
1.1 Four Problem Classes, One Predicament
The four algorithms look very different: PSO lets particles “fly” in a continuous space, GA “breeds” on discrete encodings, SA “anneals” along a single solution path, and ACO lets ants “lay pheromone” on a graph. But all of them were invented to deal with the same class of problems:
- The objective function is a black box. Given a , you can only call a simulator or a cost function to obtain ; you cannot obtain , and often not even a closed-form expression. Communications engineering offers many examples: the bit error rate curve of a set of filter coefficients, the sidelobe level of an antenna array, the throughput of a precoding scheme — these usually come only from link-level simulation, whose internals are lookup tables, branches and stochastic processes, and are simply not differentiable.
- The objective function is multimodal. There are many local optima, and gradient methods starting from different initial values fall into different pits. Parameter calibration of radio-frequency devices, array layout, and resource allocation all belong to this class.
- The variables may be discrete or combinatorial. When the variable is “which set of parameters to choose”, “which path to take”, or “which node to assign a task to”, the solution space is not but a discrete set, and the gradient is not even defined. The Travelling Salesman Problem (TSP, finding the shortest closed tour that visits every city exactly once), job-shop scheduling, and network routing are typical cases.
- The constraints are complex. The feasible region may consist of several disconnected parts, its boundary is defined jointly by a pile of inequalities, integrality conditions and logical conditions, and projecting onto the feasible region is itself a sub-problem.
Taken together, these four items amount to “black box + multimodal + discrete + constrained”. Traditional optimization methods each have one hard weakness on these four items:
| Method | Information used | Hard weakness |
|---|---|---|
| Gradient descent / Newton’s method | First- or second-order derivatives | Not differentiable; only local convergence; sensitive to initialization |
| Grid search / enumeration | Evaluations only at grid points | Curse of dimensionality; accuracy limited by grid spacing |
| Convex optimization / linear programming | Analytical structure, convexity | Modeling distortion when the problem is non-convex or non-analytical |
| Dynamic programming | Optimal substructure | State-space explosion; requires an exact model |
| Branch and bound | Relaxed lower bounds | Bounds too loose on large combinatorial problems, pruning fails |
The role of metaheuristics is precisely: when all of the above methods fail, trade “controllable randomness + reusable evaluation information” for an approximate solution that is “good enough and can be stopped at any time”. They do not guarantee optimality; they only guarantee that “within a given evaluation budget, they are usually better than blind search, and cheap to implement”.
1.2 Five Shared Building Blocks
If you take the four algorithms apart, each is a different combination of five building blocks. Once this table is understood, the formulas in the next four chapters are merely “filling in the table”.
| Building block | Question it answers | PSO | GA | SA | ACO |
|---|---|---|---|---|---|
| Representation | What a solution looks like | -dimensional real vector | Encoded string (0/1, real, permutation) | One solution (any representation) | Path / construction sequence on a graph |
| Generator | Where new solutions come from | Velocity-driven displacement | Selection + crossover + mutation | Neighborhood perturbation | Stepwise construction by pheromone probability |
| Evaluation | How to score | Call | Call , then convert to | Call | Call (path length) |
| Selection / acceptance | Who stays | Unconditionally kept (naturally replaced after the position update) | Parents selected by fitness, elitism preserved | Accepted with Metropolis probability | Only pheromone is kept, no individuals |
| Memory | Where historical information lives | Personal best , global best | The whole population | Only the current solution and the historical best | Pheromone matrix |
The most important column of this table is “memory”. It determines whether the algorithm can “accumulate experience”:
- PSO’s memory is positional — it remembers “where is good”, but not “how to get there”;
- ACO’s memory is edge-based — it remembers “which edge is good” and encodes it directly as a path preference;
- GA’s memory is population-based — good genes stay in the population in the form of individuals, and bad genes are eliminated;
- SA has almost no memory — only the current solution; historical information is retained indirectly through “where the current solution happens to be”.
This also explains how each of the four algorithms fails: PSO’s memory is easily dragged off course by an early misjudged ; ACO’s pheromone is easily locked onto a suboptimal path discovered early; GA’s population loses diversity when selection pressure is too strong; and SA, having no memory, recomputes a lot and produces high-variance results across runs.
Derivation 1: The curse of dimensionality — why grid enumeration is infeasible in high dimensions
Suppose each dimension is discretized with grid points and the dimension is ; the total number of grid points is then . If only points are used per dimension:
For that is 100 evaluations, for it is , and for it is . If a single evaluation takes 1 millisecond, requires about 116 days; a metaheuristic at typically obtains a usable approximate solution with to evaluations.
More important is the product relationship between accuracy and dimension. If each dimension must reach an accuracy of and the interval length is , then the number of grid points per dimension is , and the total number of evaluations is
To improve accuracy tenfold (), the number of evaluations is multiplied by . This exponential relationship shows that on continuous problems of even moderate dimension, the route of “refining the grid” simply cannot be completed within budget; one must switch to active search in which “where to sample is decided by historical information” — which is exactly what the four metaheuristics have in common.
1.3 Evaluation Budget: The Only Hard Currency
Every comparison between metaheuristic algorithms ultimately reduces to the same unit: the number of objective function evaluations . The reason is direct: the computation of the search itself (random numbers, sorting, matrix multiplications) is usually far cheaper than one evaluation, and an evaluation often means running one simulation, one link-level Monte Carlo campaign, or driving a piece of real hardware.
This constraint has three direct consequences:
- Population size and number of iterations are two ways of spending the same budget. individuals over generations cost evaluations. A large gives richer population information per generation but fewer generations and insufficient fine search; a small allows more generations but is prone to premature convergence. A common compromise is between and , leaving the rest of the budget to iterations.
- “Convergence curve versus number of evaluations” is the correct way to report performance. Reporting only “the final best value” without the number of evaluations used hides the budget; two algorithms that reach the same solution after 100 and 10000 evaluations are not comparable at all. In engineering one should plot the “best value versus number of evaluations” curve and report the median number of evaluations needed to reach a given threshold.
- A cache is free speed-up. When the same set of parameters is evaluated repeatedly, return the stored value directly. PSO particles may stay in place, GA elites are copied, and SA may propose a neighborhood solution that has already been evaluated — all three produce duplicate evaluations. Caching values in a hash table keyed by the solution vector (mind floating-point precision and tolerances) can raise the effective budget by a few percent up to tens of percent.
1.4 Exploration and Exploitation in Each of the Four Algorithms
“Exploration” (going to regions you have not tried) and “exploitation” (refining the region currently believed to be good) are the common tension of all search algorithms. Its abstract form is exactly isomorphic to exploration–exploitation in reinforcement learning: every evaluation is a “pull of a lever”; you want to know which region is better on average, and you also want to spend budget in the region that currently looks best.
Each of the four algorithms writes this tension into different “knobs”:
| Algorithm | Knobs favoring exploration | Knobs favoring exploitation | How to tune |
|---|---|---|---|
| PSO | Large inertia weight , large velocity cap, sparse topology | Small , large , fully connected topology | Common practice: decrease linearly from 0.9 to 0.4 |
| GA | Large mutation probability , weak selection pressure | Large crossover probability , large tournament size, more elites | Adaptive (increase it when diversity is low) |
| SA | High initial temperature , slow cooling, long chain | Low final temperature, fast cooling | Temperature schedule curve |
| ACO | Large evaporation rate , small , low pheromone upper bound | Small , large , high pheromone lower bound | MMAS bounds and |
Note one easily confused point: “random” does not equal “exploration”. Pure random search samples independently of history every time, and its expected performance is fixed; the randomness of a metaheuristic only becomes meaningful when shaped by selection pressure — PSO multiplies random numbers onto “displacements pointing at the best”, GA performs random crossover between “selected parents”, SA filters random perturbations through an “acceptance rule”, and ACO weights random choices by “pheromone”. Randomness is the operator; selection pressure is the algorithm.
Derivation 2: What the no-free-lunch theorem says and what it does not say
The standard statement of the No Free Lunch (NFL) theorem (Wolpert & Macready, 1997) is: let the search space be finite, let the set of all possible objective functions form the set , and take a uniform distribution over ; then for any two algorithms , their average performance over all problems is the same:
The core of the proof is a counting argument: under the uniform distribution, the “sequence of evaluations” an algorithm sees is independent of the true values of the unevaluated points; no matter how the algorithm uses history to decide the next query point, the conditional expectation of the remaining points is identical, so any “clever” query strategy is on average no better than blind search. For every algorithm , one can construct an objective function that is “specifically adversarial to ” (assign bad values along ‘s visiting order and good values to points it never visits), making perform worst; averaging over these “adversarial functions” flattens the average performance of all algorithms.
Three things this theorem does not say are exactly why metaheuristics still work:
- It averages over “all possible objective functions”, whereas engineering problems are not drawn uniformly from that set. Real simulated objective functions carry strong structure: smoothness, separability, sparsity, weak coupling between variables, and low effective dimensionality induced by physical constraints. As long as an algorithm matches that structure, it can vastly outperform blind search on “this class of problems”.
- It does not rule out “being better on a certain class of problems”. NFL says “equal on average”, not “equal everywhere”. Hence the correct way to choose an algorithm is: identify the structure of the problem first, then choose an algorithm that matches it — which is exactly what the decision chain in Chapter 6 does.
- It does not constrain “costs other than evaluations”. Memory, parallelism, implementation difficulty and interpretability are all outside the theorem’s accounting, and engineering selection must count them too.
In one sentence: NFL denies the “universal algorithm” and affirms that “an algorithm must carry a prior about the problem”. Each metaheuristic is such a “prior declaration”: PSO declares “there is an attractor near the optimum and a good direction can be shared within the swarm”; GA declares “good local fragments can be combined into a better whole”; SA declares “although the objective landscape is multimodal, neighboring solutions are highly correlated”; ACO declares “a good path is made of good edges, and the quality of an edge can be learned from historical paths”.
1.5 Kinship with Reinforcement Learning
The relationship between these four algorithms and reinforcement learning (RL, a method in which an agent interacts with an environment and improves its decisions based on rewards) is much closer than it appears:
- ACO is essentially “constructive reinforcement learning”. An ant choosing edges step by step = an agent choosing actions step by step; path length = total episode reward; pheromone = a state–action value table; pheromone update = a Monte Carlo update with forgetting. Chapter 5 writes out this correspondence item by item.
- PSO can be seen as “policy search without gradients”. The particle position is the parameter vector, the velocity is the update direction of the parameters, the personal/global best are “the highest-return policies so far”, and the inertia term is momentum.
- GA is the ancestor of “evolution strategies”. Modern Evolution Strategies (ES, black-box optimization methods that estimate a gradient direction from population perturbations) share the four steps “sample–evaluate–select–recombine” with GA, only replacing “crossover” by “Gaussian perturbation + weighted averaging”.
- SA is the template of “stochastic acceptance with temperature”. It uses the same distribution as “Boltzmann exploration” in reinforcement learning (choosing an action with probability proportional to ); the only difference is that SA accepts “solutions” while RL accepts “actions”.
Therefore, reading this note side by side with the deep reinforcement learning note reveals a lot of structural isomorphism: both work inside a “sample–evaluate–update” loop, both pick a point between exploration and exploitation, and both need a checklist of “which quantities to keep and which to reset”. Section 6.7 gives the full concept-mapping table.
1.6 Quick Overview of the Four Algorithms
Before going into the details, build a sense of the coordinate system with one table (the full comparison table is in 6.1):
| Algorithm | One-sentence intuition | Best suited to | Most afraid of |
|---|---|---|---|
| PSO | A swarm of particles flies toward “the best place I have seen” and “the best place the swarm has seen” | Continuous, moderate dimension, fairly smooth objective | High dimension, multimodal with widely separated peaks, discrete variables |
| GA | Good individuals leave offspring, good fragments are combined by crossover | Discrete/combinatorial, clear encoding, constraints expressible as penalties | Needing fine local search, extremely small evaluation budget |
| SA | Temporarily going downhill is allowed; as temperature drops it only takes good paths | Combinatorial optimization, clear neighborhood structure, single-path improvement acceptable | Hard neighborhood design, needing parallelism, extremely small budget |
| ACO | Edges on good paths are more likely to be chosen by later ants | Path/construction-type combinatorial problems on graphs | Continuous variables, objectives not decomposable into a sum over “edges” |
2. Particle Swarm Optimization (PSO)
2.1 Why It Is Needed: “Swarm Inertial Search” in Continuous Black-Box Spaces
The problem Particle Swarm Optimization (PSO, Kennedy & Eberhart, 1995) solves is: in a -dimensional continuous space, with a non-differentiable, multimodal objective and a limited evaluation budget, how do you search?
Its design deliberately imitates a flock of birds foraging: each bird does not know exactly where the food is, but it knows where it was closest to food and it knows the best position reported by its companions; so it flies partly from its own memory and partly toward the direction the swarm reports, while retaining some of its previous flight inertia. These three things correspond to the three terms of the velocity update: the inertia term, the cognitive term, and the social term.
The most fundamental difference between PSO and gradient methods is: a gradient method asks at every step “in which direction does the function decrease fastest”; PSO asks at every step “where is the best position in my own history and where is the best position in the swarm’s history”. It does not require the objective to be differentiable, only that two solutions can be compared; its “direction” comes from differences of historical positions, not from derivatives.
2.2 Principles and Formulas
Let the swarm have particles, with particle at position and velocity . The update at iteration is
where are random numbers redrawn for every dimension and every update (this is the point most easily implemented as “draw only two scalars per iteration”). The original paper (Kennedy & Eberhart, 1995) wrote
that is, without an inertia term; the inertia weight was introduced by Shi & Eberhart (1998) to control “how much of the previous velocity is retained”.
The three coefficients act as follows:
| Term | Coefficient | Points at | Intuition | When too large | When too small |
|---|---|---|---|---|---|
| Inertia | Previous velocity | Keeps the direction of motion, crosses local regions | Flies everywhere, hard to converge | Brakes quickly, easily trapped in a local optimum | |
| Cognitive | “Trust your own past experience” | Everyone goes their own way, swarm information unused | Over-reliance on the swarm, loss of diversity | ||
| Social | “Trust the swarm’s experience” | The whole swarm collapses onto one point quickly, premature | Swarm cooperation fails, slow convergence |
Derivation 3: Three-term decomposition of the velocity update and its second-order difference form
Step 1: split the velocity update by “source of information”. The three terms of the velocity update depend on exactly three things: the past velocity, the personal historical best, and the swarm historical best.
The meaning of this step is: PSO’s “gradient” is not but a composite direction built from two “position differences”. The position difference is a vector pointing at a known good point, and its length adapts automatically to “how far away the good point is” — far away means a long step, close means a short step, so the behavior is naturally “coarse first, fine later” without any extra step-size schedule.
Step 2: eliminate velocity and write a second-order difference in positions only. Substituting into the velocity update gives
Rearranged into the form “current position + displacement”:
where
is the composite attractor obtained by weighting the personal best and the global best with the coefficients. This equation has exactly the form of a damped spring oscillator: the second difference of the displacement = inertia term (velocity) − stiffness × displacement away from the attractor. plays the role of the damping coefficient, and plays the role of spring stiffness.
Step 3: expected recursion of the one-dimensional simplified model. Set (personal best and global best coincide, the most ideal case), take expectations using , and write ; then
This is a constant-coefficient linear recursion whose behavior is entirely determined by the characteristic equation:
Step 4: read off the engineering meaning. When is small, the characteristic roots are real and the particle approaches monotonically or with monotone oscillation — slow but stable convergence; when grows until the discriminant , the roots become a pair of complex conjugates and the particle spirals around with decaying radius — which is exactly the typical PSO trajectory: large oscillation while exploring, then a spiral contraction onto the attractor. So larger is not better: if is too large the root modulus approaches 1 and the spiral decays extremely slowly or even diverges; if is too small the trajectory is too “straight” and lacks the detour that provides exploration.
2.3 Convergence Conditions and the Stable Parameter Region
Derivation 4: Convergence conditions of PSO and its stable parameter region
Step 1: write down the characteristic roots. For the characteristic equation obtained in Section 2:
the quadratic formula gives
The necessary and sufficient condition for the particle position sequence to converge to is that both characteristic roots have modulus strictly less than 1:
Step 2: discuss two cases.
Case A: the discriminant is nonnegative, , and the two roots are real. Then we need
Substituting the expression for and rearranging, this is equivalent to
(from we get ; from and the roots lying in we get the upper bound on .)
Case B: the discriminant is negative, , and the two roots are complex conjugates. Then the two roots have equal modulus, and by Vieta’s formulas
so the convergence condition simplifies to
This is the most useful one: as long as and the discriminant is negative (that is, ), the particle certainly converges in a spiral with rate . The closer is to 1, the slower the decay (the longer the exploration); the closer is to 0, the faster the decay (the faster the locking).
Step 3: merge the two conditions into the usual operating region. Combining the two cases, the classical conclusion is that the parameters should lie in the region
(strictly speaking, the bound on should be converted using ; in practice is often used directly as a rough boundary). Outside this region the particle trajectory diverges — the position flies rapidly to the boundary, is clipped, and then repeatedly sticks to the boundary.
Step 4: the Clerc constriction factor. Clerc & Kennedy (2002) gave a choice that “converges without extra velocity clamping”. Let and take
For , . The update is written as
Taking is equivalent to and . The practical meaning of this parameter set is: it builds “convergence” into the coefficients themselves instead of rescuing it afterwards with clamping. If you do not want to tune parameters, starting from this set is the most robust choice.
Step 5: why clamping is still needed in practice. The analysis above is in expectation and assumes a fixed . In a real run is constantly refreshed by other particles, and the random terms add variance; if one update happens to draw both close to 1, the displacement becomes huge for an instant and throws the particle far away from the attractor, after which it is forced to fly back with an even larger velocity, producing “boundary oscillation”. Clamping is a safety net for exactly these tail events (see Derivation 5).
2.4 Velocity Clamping, Boundary Handling and Topology
In a practical implementation, the PSO formula is only two lines; all the remaining complexity lies in four things:
- Velocity clamping. Set an upper bound for each dimension and, after the update, apply
A common choice is with .
-
Out-of-bounds position handling. Three common strategies: clamp to the boundary, reflect, or randomly reset inside the feasible region. Clamping is simplest but makes particles “stick to the boundary”, reflection preserves momentum, and random reset suits feasible regions that are not connected.
-
Topology. Taking as “the best of the whole swarm” gives the global version (gbest); taking it as “the best within a ring neighborhood” gives the local version (lbest). The local version splits the swarm into several small circles, so information spreads slowly and diversity is preserved well, which suits multimodal problems; the global version converges fast and is prone to premature convergence.
-
When to update and . They must be refreshed after all particles have finished their position updates and evaluations; otherwise particles updated earlier in the same round would use a “that has not been evaluated yet”, and the information of half the swarm is wasted.
Derivation 5: Why velocity clamping is equivalent to limiting the single-step exploration radius
Step 1: write out the upper bound on the single-step displacement. From the position update , the single-step displacement is simply . If every dimension is clamped to , then
Taking and writing for the domain length of dimension gives
Step 2: interpret this bound. The inequality says that a single step can cross at most ” times the diagonal length of the whole search box”. If is too large (say 1.0), one step crosses the entire space, particles cannot stay near the attractor, and the algorithm degenerates to random search; if is too small (say 0.01), particles crawl like snails and the budget is exhausted while they are still near the starting point. The clamping knob really controls the ratio between “the coarsest granularity” and “the finest granularity”, and it is usually used together with a schedule that decreases linearly from 0.9 to 0.4: in the early phase and are large, giving a coarse search; in the late phase they are small, giving a fine search.
Step 3: relation between clamping and convergence. Clamping does not change the characteristic roots (it acts only when the velocity exceeds the bound), so it cannot turn a divergent parameter set into a convergent one; it only compresses the “blast radius” of divergence into a controllable range. First make sure the parameters lie in the stable region of 2.3, then use clamping as the safety net — the order cannot be reversed.
2.5 Pseudocode: PSO (Full Version, with gbest/lbest, Cache and Out-of-Bounds Handling)
Algorithm: PSO (global version gbest; for the local version replace gbest on line 9 with the neighborhood best lbest)
Input: objective function f, dimension D, per-dimension bounds [x_min, x_max]
N number of particles (usually 20D ~ 50D)
T_max maximum number of iterations
w inertia weight (fixed, or decreased linearly from 0.9 to 0.4)
c1, c2 learning coefficients (usually 2.0/2.0, or Clerc's 1.49618/1.49618)
kappa velocity clamping ratio (v_max = kappa * (x_max - x_min), usually 0.1 ~ 0.5)
N_FE_max upper limit on the number of evaluations (a stopping condition together with T_max)
Output: gbest_x, gbest_f (historical best position and objective value of the whole swarm)
# ---------- Block 1: initialization ----------
for i = 1 .. N:
x_i ~ U(x_min, x_max)^D # uniform sampling per dimension, giving a D-dimensional vector
v_i ~ U(-v_max, v_max)^D # initial velocity, may also be set to 0
f_i <- f(x_i) # evaluation, counted into N_FE
p_i <- x_i, p_f_i <- f_i # personal best
gbest_x <- argmin_i p_f_i, gbest_f <- min_i p_f_i
# ---------- Block 2: main loop ----------
for t = 1 .. T_max:
for i = 1 .. N:
# 2.1 draw random numbers per dimension (note: redraw for every dimension)
for d = 1 .. D:
r1 ~ U(0,1), r2 ~ U(0,1)
v_id <- w * v_id
+ c1 * r1 * (p_id - x_id)
+ c2 * r2 * (gbest_x[d] - x_id)
v_id <- clip(v_id, -v_max[d], +v_max[d])
x_i <- x_i + v_i # position update
x_i <- handle_out_of_bounds(x_i) # clamp / reflect / random reset
# 2.2 evaluation (check the cache first to avoid duplicate evaluations)
if x_i in cache:
f_i <- cache[x_i]
else:
f_i <- f(x_i); N_FE <- N_FE + 1; cache[x_i] <- f_i
# 2.3 update the personal best (overwrite only when the new solution is better)
if f_i < p_f_i:
p_i <- x_i, p_f_i <- f_i
# 2.4 refresh the global best uniformly (must happen after the whole round is evaluated)
gbest_x <- argmin_i p_f_i, gbest_f <- min_i p_f_i
# 2.5 stopping conditions (stop when any one holds)
if N_FE >= N_FE_max: break
if swarm position variance < threshold and gbest_f unchanged for several consecutive generations: break
return gbest_x, gbest_f
The pseudocode deliberately marks the three places most easily written wrong: drawing random numbers per dimension, refreshing the global best uniformly, and checking the cache before evaluating. Each is explained below.
2.6 Section-by-Section Walkthrough of the Pseudocode
Block 1 ①: initialization uses uniform sampling; “the more uniform the better” is not required. A common practice is Latin Hypercube Sampling (LHS, a stratified sampling scheme that splits each dimension into intervals and takes exactly one point in each), which covers the space better than pure random sampling, with a visible difference especially when is large and is small. But there is no need to pursue “perfect uniformity”: PSO’s exploration comes from the subsequent velocity updates, and an overly dense initial set makes the close to each other and the swarm information monotonous.
Block 1 ②: the initial velocity may be zero or random. Setting it to zero makes the first generation entirely driven by the “cognitive + social” terms, giving a clearer direction; a random initial velocity provides extra diversity. Both work, but the key is consistency with the clamping — if the initial velocity is random, it must be clamped into .
Block 2 ③: random numbers must be redrawn per dimension. This is the number-one pitfall in PSO implementations. If only two scalars are drawn per iteration, all dimensions share the same random weights, the particle’s displacement direction is locked into a two-dimensional subspace (the true direction is only a combination determined by those two random numbers), and on high-dimensional problems this shows up as “some dimensions never move”. The correct implementation draws one pair per dimension.
Block 2 ④: compute velocity first, then position; the order cannot be reversed. The position update uses the updated velocity (), not the old one. Writing “move first, then update velocity” shifts the whole dynamics by one step, and the convergence behavior no longer matches the original algorithm.
Block 2 ⑤: refresh the global best uniformly. If gbest is updated inside the particle loop, particles processed earlier in the round use the old gbest while later ones use the new one, so information is not synchronized within the same generation. In practice the effect is small (the next generation corrects it), but in parallel implementations it makes results irreproducible. The standard practice is a single argmin after the whole round has been evaluated.
Block 2 ⑥: the cache must match with a tolerance. Floating-point vectors cannot be used as keys with exact equality: two “identical” updates may differ in the last digit because of rounding. In practice, round to or match by norm distance; if the hit rate is low (on continuous problems repeats are almost nonexistent) the cache can be dropped, but it is very effective for mixed integer/discrete cases or when many particles sit on the same attractor.
Block 2 ⑦: the stopping condition needs a double safeguard. Stopping only by generation count wastes budget when “the budget is not exhausted but the algorithm has converged”; stopping only by evaluation count keeps spinning when “the algorithm stagnated long ago”. The usual combination is: an cap plus “swarm position variance below a threshold and gbest_f not improving for consecutive generations”. Note that the variance criterion must be normalized per dimension, otherwise the threshold is hard to set on high-dimensional problems.
Block 2 ⑧: the local version changes only one line. Replace gbest_x with “the best in the neighborhood of particle ” and leave everything else unchanged. The ring topology (each particle connected only to neighbors on each side) is the most common local version: information propagates slowly around the ring, which amounts to turning “one convergence of the whole swarm” into “several small circles each converging and then merging”, and it is clearly more robust on multimodal problems.
2.7 Per-Step Read/Write and State-Maintenance Checklist
The reinforcement learning note has a “gradient-flow and detach checklist” that answers “which quantities must not carry gradients”. PSO has no gradients, and the corresponding question is “which quantities must be read and written at each step, which must be preserved, and which must be reset”. This table is the PSO version of that checklist:
| Quantity | When read | When written | Kept across generations | Consequence of writing it wrong |
|---|---|---|---|---|
| Every step | Every step (after the position update) | Kept (overwritten) | Forgetting the update leaves the particle motionless | |
| Every step | Every step (after the velocity update) | Must be kept | Zeroing it every step degenerates to greedy hill-climbing and loses inertial exploration | |
| Every step | Only when | Must be kept | Overwriting it every step turns “personal best” into “current position” and the cognitive term is always zero | |
| When comparing | Together with | Must be kept | Updating the position without the value corrupts the comparison | |
| Every step | Uniformly at the end of each round | Must be kept | Refreshing inside the particle loop desynchronizes the same generation | |
| Every step | Every generation (if scheduled) | Kept (decreasing) | Increasing it instead makes late exploration too strong and prevents convergence | |
| Cache | Before every evaluation | After every new evaluation | Kept | Exact floating-point equality makes almost every lookup miss |
Three decision rules, exactly isomorphic to the “ask whether it should change” of the detach checklist:
- “Historical best” is a read-only reference, not a variable being optimized. and are replaced only when “a better solution appears”, and at all other times they are never modified in any way beyond being used in the position update.
- “The previous velocity” must be kept across generations. The entire point of the inertia term is to reuse the previous velocity; if the velocity is reset at the start of every generation, has nothing to act on.
- “The evaluated value” and “the position” must be updated as a pair. Changing the position without the value, or the value without the position, distorts the judgment of “who is better” — a more insidious error than a mistyped formula.
2.8 Pitfall Checklist
| Symptom | Possible cause | Fix |
|---|---|---|
Particles quickly stick to the boundary and gbest stops improving | or lies outside the stable region, trajectory diverges | Use ; or decrease linearly to 0.4 |
| The whole swarm collapses onto one point early (premature) | Global topology + too large + population too small | Switch to lbest ring topology; increase ; reduce |
| Some dimensions never move | Only two scalars drawn per generation instead of per dimension | Draw one pair for every dimension |
| Convergence curve is sawtoothed and worsens late | not maintained (current best used as historical best) | Store the historical best separately and never overwrite it with the current solution |
| Results differ enormously between runs | Population too small, budget too small, no random-seed management | ; fix the seed for comparison experiments; take statistics over several independent runs |
| Almost no convergence at high dimension () | PSO’s dimensional scalability is limited | Reduce dimension / group variables; switch to CMA-ES (covariance matrix adaptation evolution strategy); or change the problem decomposition |
| Duplicate evaluations eat the budget | No cache, particles repeatedly evaluating the same position after settling on the attractor | Add a tolerance-based cache; or skip the evaluation when “position change below a threshold” |
| Objective magnitudes differ greatly and some dimensions dominate | Variables not normalized | Scale each dimension to or standardize; set the velocity cap on the normalized scale too |
Among these, “no convergence at high dimension” deserves a separate remark: the PSO velocity update assumes “all dimensions share the same attractor direction”, and when is large, the optimal values of different dimensions may conflict, so the shared direction makes the particle oscillate back and forth along conflicting directions. The engineering response is not “increase the population” but dimension reduction or variable grouping (split weakly coupled variables into groups and run a small PSO on each), or switching to CMA-ES, which can learn correlations between variables.
2.9 Scope of Application
Suitable: continuous variables, moderate dimension ( between 2 and 30 is best), objective functions that are fairly smooth but not differentiable, evaluation budgets between and , and tasks where taking the best of several independent runs is acceptable. Typical scenarios include: optimization of amplitude and phase weights in antenna arrays, calibration of filter coefficients, PID parameter tuning, continuous power or position variables in wireless resource allocation, and coarse search over machine learning hyperparameters (learning rate, regularization coefficient).
Not suitable:
- Discrete or combinatorial problems — PSO needs the concept of “position difference”, and there is no natural subtraction on permutations, paths, or 0/1 strings; discrete PSO variants exist (interpreting velocity as “the probability of taking 1”), but they usually perform worse than a dedicated GA or ACO.
- High dimension ( in the hundreds) with strongly coupled variables — the shared attractor direction fails, so switch to CMA-ES or variable grouping.
- Unimodal, differentiable, tiny budget — use gradient or Newton methods directly; PSO is a waste.
- Real-time decisions that must be strictly reproducible — PSO’s randomness makes every run different; real-time systems usually need a deterministic algorithm plus offline optimization.
3. Genetic Algorithms (GA)
3.1 Why It Is Needed: “Breeding and Recombination” on Discrete Encodings
The starting point of the Genetic Algorithm (GA, Holland, 1975) is: if the optimal solution of a problem is assembled from several “good local fragments”, then treating the fragments as heritable units and letting them recombine between individuals can find the global optimum faster than point-by-point search.
This statement holds only under two conditions: first, “good local fragments” really exist and can be evaluated independently (for example, a short and cheap sub-path in a TSP, or a set of non-conflicting tasks in scheduling); second, “recombination” does not break the fragments apart too often. The whole operator design of GA — the probabilities of selection, crossover and mutation — serves these two conditions.
The comparison with PSO is instructive: PSO constructs directions from “position differences” in a continuous space, assuming the solution space has a metric and supports subtraction; GA uses “encoding + bit/gene operations”, assuming the solution can be split into discrete units that can be exchanged. PSO’s search unit is “a point”; GA’s search unit is “a combination of fragments”.
3.2 The Five Components
GA has even fewer formulas than PSO; everything depends on “how the five components are chosen”. The combination of these five choices determines whether the GA is “usable” or “degenerates into random search”.
3.2.1 Encoding: The Solution Must Be Slicable and Recombination-Ready
| Encoding | Representation | Applicable to | Key point |
|---|---|---|---|
| Binary encoding | Each variable is represented by bits, string length | Discrete choices, switches, coarse-grained continuous | Accuracy ; Gray code reduces the “adjacent integers are far apart” problem |
| Real-valued encoding | The string is simply a real vector; crossover/mutation act directly on reals | Continuous variables, constrained optimization | Requires dedicated real-valued operators (SBX, polynomial mutation) |
| Permutation encoding | The string is a permutation of | TSP, scheduling, ordering | Ordinary crossover produces duplicated/missing elements; order-preserving crossovers such as OX and PMX are required |
| Integer/mixed encoding | Each gene takes a finite integer value, possibly mixed with reals | Resource allocation, parameter combinations | Mutation must keep the value legal |
The first principle of encoding design is: “adjacency” in the encoding space should agree as far as possible with adjacency in the actual problem space. If two practically similar solutions differ in many bits (for example, 7 and 8 differ in 4 bits under binary encoding), crossover and mutation frequently cause “leaping” destruction. Gray code (in which adjacent integers differ in only one bit) was designed exactly for this.
3.2.2 Fitness: Turning “Smaller Is Better” into “Larger Is Better”
The GA selection operator assumes “the larger the fitness, the more likely to be selected”, whereas engineering objective functions are usually minimized. Hence one transform is needed:
The former suits cases with and no upper bound, the latter cases where has a known upper bound. More important is scaling:
- Rank-based fitness: sort by and use the rank (or a linear function of the rank) as , which completely removes the monopoly caused by “one individual with extremely high fitness”.
- Windowing: in each generation use , where is the current-generation maximum, preventing all individuals from converging to similar fitness late in the run and thus disabling selection.
- Penalty: add the constraint violation to the objective,
where is the -th inequality constraint. If is too small the solutions are infeasible; if it is too large the boundary of the feasible region is hard to search finely.
3.2.3 Selection: Giving “Better” a Higher Breeding Probability
| Selection scheme | Procedure | Selection pressure | Characteristics |
|---|---|---|---|
| Roulette wheel | Sample with probability | Medium | Simple to implement; high variance when fitness values differ greatly |
| Tournament | Draw at random and take the best | Controlled by | Most common; is mild, larger means stronger pressure |
| Ranking | Assign probabilities linearly by rank | Precisely controllable | Suits unknown fitness scales |
| Truncation | Only the top fraction reproduces | Strong | Fast convergence but large loss of diversity |
Selection pressure is the only quantity here that needs to be understood: it measures “how much more a good individual breeds than an ordinary one”. If the pressure is too small, the population drifts randomly and converges slowly; if it is too large, the population is filled by a few individuals within a few generations, crossover loses meaning (because the parents are almost identical), and the algorithm converges prematurely.
3.2.4 Crossover: The Core Operator That Distinguishes GA from Other Algorithms
| Crossover | Procedure | Applicable encoding | Characteristics |
|---|---|---|---|
| One-point | Pick one cut point at random and exchange the fragments after it | Binary, permutation (with repair) | Small disruption, weak recombination |
| Two-point | Pick two cut points and exchange the middle fragment | Same as above | More balanced than one-point |
| Uniform | Each bit comes from parent 1 or parent 2 with probability | Binary, real | Large disruption, strong exploration |
| Simulated binary (SBX) | Simulate binary crossover by distribution, producing two children | Real | The standard operator for continuous GA; controls how close the children are to the parents |
| Order crossover (OX) / PMX | Keep one block in order, fill the rest in order | Permutation | Guarantees that the child is still a legal permutation |
The one-dimensional form of SBX (Deb & Agrawal, 1995): for a pair of parents , draw and compute the spread factor
The two children are
The larger is, the closer is to 1 and the closer the children are to the parents (strong exploitation); the smaller is, the more likely the children are far from the parents (strong exploration). A common choice is .
3.2.5 Mutation: Insurance for Diversity
For binary encoding, mutation is bit flipping:
For real-valued encoding, polynomial mutation is common:
The larger is, the smaller the perturbation (fine local search); the smaller it is, the larger the perturbation (jumping exploration). A common choice is .
The division of labor between mutation and crossover must be remembered: crossover is responsible for “combining existing fragments”, mutation for “introducing fragments that have never appeared”. With crossover alone, after some generations all individuals share the same set of alleles and no new value can ever be found (premature convergence); with mutation alone, the algorithm degenerates into a random walk. The two probabilities must be tuned as a pair.
3.3 The Schema Theorem: Why GA “Exponentially Grows” Good Fragments
Derivation 6: Expected number of offspring under roulette-wheel selection and the schema theorem
Step 1: define a schema. A schema is a string template with wildcards; for example, with binary string length , means “position 1 is 1, position 3 is 0, position 6 is 1, anything elsewhere”. Two quantities characterize its “structure”:
- order : the number of fixed positions, 3 in the example above;
- defining length : the distance between the leftmost and rightmost fixed positions, in the example above.
Step 2: compute the expected number of offspring under roulette-wheel selection. Let the population size at generation be , the fitness of individual be , and its selection probability be
The expected number of times a single individual is selected is . Summing over all individuals belonging to schema gives
where is the average fitness of the individuals in . This step is the entire source of “selection makes good schemas grow exponentially”: if , then is multiplied by a factor greater than 1 every generation, growing as after generations.
Step 3: subtract the destruction caused by crossover and mutation. Crossover can break a schema: the fixed positions of can only be split when the cut point falls inside the defining length. A one-point crossover has possible cut positions, of which fall inside , so the probability of not being destroyed is
Mutation flips fixed positions: the probability that a single position is not flipped is , and the probability that all fixed positions survive is . For small use the first-order approximation
Step 4: combine into the schema theorem. Multiply the selection gain by the two destruction factors (the destruction events are approximately independent), giving
Step 5: read off three things.
- Schemas with short defining length, low order and high fitness grow fastest. Such schemas are called building blocks. They are unlikely to be broken by crossover and unlikely to be destroyed by mutation, while selection keeps weighting them — together these three cause exponential growth.
- The crossover probability and the mutation probability form the “destruction budget”. If the combined term approaches 1, no schema can survive and the GA degenerates into random search.
- This inequality is a lower bound, not an equality. It ignores the positive role of crossover in “creating” new schemas and ignores the correlation between selection and destruction, so it only describes “good schemas do not disappear too fast” and does not prove that GA converges to the optimum.
3.4 The Building Block Hypothesis: How Far It Holds
The schema theorem is often extrapolated into a stronger proposition — the Building Block Hypothesis: GA gradually assembles the global optimum by repeatedly discovering, combining, and growing schemas with short defining length, low order and high fitness.
This hypothesis has many counterexamples in practice, for three reasons:
- Building blocks may conflict with each other. Two individually excellent short schemas may reduce overall fitness when combined (epistasis, meaning interaction effects between genes). The GA then oscillates between the two building blocks and cannot keep both.
- Crossover destroys building blocks that are still forming. Especially when the population has already converged to a few individuals, the two parents of a crossover are almost identical and the children carry no new combination — “recombination” exists in name only.
- “Hitchhiking”. If a low-fitness gene happens to sit on the same string as a high-fitness building block, it is copied along with it even though it contributes nothing to the whole. The schema theorem cannot distinguish “positions that genuinely contribute fitness” from “positions that hitchhike”.
The conclusion of Derivation 6 should therefore be used correctly: the schema theorem states “under what conditions good fragments do not disappear”, not “the algorithm will certainly assemble the optimum”. The engineering response is to maintain diversity explicitly (niching, crowding distance, shared fitness), or to switch to algorithms that handle variable correlations (CMA-ES, GA with linkage learning).
Derivation 7: Why crossover can recombine building blocks, and why it fails
Step 1: the recombination mechanism of one-point crossover. Let two parents carry complementary building blocks and :
where are useless fragments, lies to the left of the cut point and to the right. If the cut point happens to fall on the boundary between and , the child
obtains both building blocks at once. This is “recombination”: crossover does not create new genes, it only re-pairs existing good fragments.
Step 2: the probability of success. If occupies positions, occupies positions and the string length is , only a few positions at the – junction are suitable cut points. Roughly, the probability that one-point crossover falls exactly “between the two building blocks” is about , so recombination events are rare and must accumulate over many generations.
Step 3: the two ways to fail. First, the cut point falls inside or and splits the building block itself (the probability is governed by the defining length); second, and are already on the “same side” in the parents, so crossover cannot move them onto the same child (this requires the two parents to carry exactly complementary fragment layouts). These two failures explain why GA needs a larger population: only when the population contains enough different fragment layouts is there a chance of forming complementary parents such as “left A, right B” and “left Y, right B”.
Step 4: why recombination fails after convergence. When the population is filled by a few elites, the genes of any two parents are almost identical, crossover produces “approximate copies of the parents”, the children have fitness comparable to the parents, and selection pressure no longer drives improvement. The only operator that can still introduce new information is mutation — which is why “after premature convergence only mutation can save you” — and mutation is far less efficient than recombination.
3.5 Mutation Probability: Why Is Commonly Used
Derivation 8: Bounds on the mutation probability and schema survival
Step 1: write out the “expected number of mutations per string”. With string length and per-position mutation probability , the number of mutations on one string follows a binomial distribution with expectation
Taking gives exactly one mutation per string per generation on average. This is the most common default, for the reason that it guarantees every individual a chance to introduce a new gene without shuffling the whole string.
Step 2: look at schema survival. From the derivation in 3.3, a schema of order survives mutation with probability . With and , the survival probability is , close to 1; when grows to , the survival probability drops to , and a schema of order 3 survives with probability only — equivalent to blowing up all the structure accumulated in the previous generation.
Step 3: determine the bounds.
- Lower bound: if is too small (say ), an allele that has already been lost can hardly be reintroduced. With population size and string length , the expected number of mutations per generation is only , that is, one mutation event every ten generations, and the search stagnates too early.
- Upper bound: if is too large (say ), GA degenerates into random search, the destruction term in the schema theorem exceeds 0.5, and no building block longer than 2 can survive reliably.
Step 4: why the best value depends on the problem. For problems that “need fine local search” (such as continuous parameter calibration), should be small and large; for problems that “need to jump out of local optima repeatedly” (such as multimodal combinatorial optimization), should be large, or adaptive mutation should be used (increase when population diversity drops). There is no globally optimal , only a that matches the selection pressure and the encoding length.
3.6 Pseudocode: GA (Generational Model + Elitism, Real-Valued SBX)
Algorithm: GA (generational model, E elites preserved; for binary encoding replace crossover/mutation by one-point crossover and bit flipping)
Input: objective function f, encoding scheme, dimension D, per-dimension bounds [x_min, x_max]
N population size (usually 20 ~ 100)
T_max maximum number of generations
p_c crossover probability (usually 0.8 ~ 0.95)
p_m mutation probability (usually 1/l for binary, 1/D or 0.1 ~ 0.2 for real)
eta_c crossover distribution index (usually 10 ~ 30)
eta_m mutation distribution index (usually 20 ~ 100)
E number of elites preserved (usually 1 ~ 4)
Output: best_x, best_f
# ---------- Block 1: initialization and first evaluation ----------
P <- sample N individuals uniformly in [x_min, x_max]^D
for i = 1 .. N:
f_i <- f(P[i]) # a cache may be added
best_x <- P[argmin_i f_i], best_f <- min_i f_i
# ---------- Block 2: main evolutionary loop ----------
for t = 1 .. T_max:
# 2.1 elitism: the best E individuals enter the next generation unchanged
Elite <- the top E after sorting by f (they take part in neither crossover nor mutation)
# 2.2 selection: tournament, draw k and take the best (k is usually 2 ~ 3)
Parents <- empty set
for j = 1 .. N - E:
cand <- draw k individuals at random from P (with replacement)
Parents <- Parents + { the one with the smallest f among cand }
# 2.3 crossover: pair them up and apply SBX with probability p_c
Children <- empty set
for each pair (p1, p2) in Parents:
if rand() < p_c:
for d = 1 .. D:
u ~ U(0,1)
beta <- (2u)^(1/(eta_c+1)) if u <= 0.5
<- (1/(2(1-u)))^(1/(eta_c+1)) otherwise
c1[d] <- 0.5 * ((1+beta)*p1[d] + (1-beta)*p2[d])
c2[d] <- 0.5 * ((1-beta)*p1[d] + (1+beta)*p2[d])
Children <- Children + {c1, c2}
else:
Children <- Children + {p1, p2} # copy unchanged when there is no crossover
# 2.4 mutation: each gene undergoes polynomial mutation with probability p_m
for c in Children:
for d = 1 .. D:
if rand() < p_m:
u ~ U(0,1)
delta <- (2u)^(1/(eta_m+1)) - 1 if u < 0.5
<- 1 - (2(1-u))^(1/(eta_m+1)) otherwise
c[d] <- c[d] + delta * (x_max[d] - x_min[d])
c <- clip(c, x_min, x_max) # truncate out-of-bounds values
# 2.5 evaluate the children and update the best
for c in Children:
f_c <- f(c) # check the cache first
if f_c < best_f: best_x <- c, best_f <- f_c
# 2.6 generational replacement: elites + children (alternatively a (mu+lambda) merge-and-select)
P <- Elite + Children
return best_x, best_f
The line P <- Elite + Children hides an assumption: the number of Children is exactly . SBX produces two children per parent pair, so if the number of parents is and even, the number of children equals exactly; if it is odd, extra handling is needed (discard one parent or draw one more). This must be checked explicitly in the implementation, otherwise the population size drifts from generation to generation.
3.7 Section-by-Section Walkthrough of the Pseudocode
Block 1 ①: initialization must cover the bounds. As with PSO, uniform sampling or Latin hypercube sampling can be used. For real-valued encoding, an “inside-the-bounds check” is advisable after initialization — for some problems the feasible region is not the whole rectangle, and blind sampling wastes most of the budget outside the feasible region.
Block 2 ②: why elitism is mandatory. Without elitism, crossover and mutation may destroy the current best individual, producing a sawtoothed curve in which “the best value decreases with generation”. Preserving elites installs a “never decreasing” lower bound on the algorithm. But cannot be too large: when approaches , the population fills with copies of the elites, diversity collapses and crossover stops working. A common choice is to .
Block 2 ③: the tournament size is the direct knob for selection pressure. With , an individual’s selection probability is roughly linearly related to its rank and the pressure is mild; as grows, the probability that the best individual is selected rapidly approaches 1 and the pressure becomes strong. If the algorithm converges prematurely, first reduce to 2; if convergence is too slow, raise to 3 or 4.
Block 2 ④: SBX must produce both children together. SBX is naturally “a pair in, a pair out”, and the two children are distributed symmetrically about the midpoint of the parents. Keeping only one child artificially throws away half the exploration directions and makes the child distribution asymmetric. controls the distance between children and parents: as , approximately equal the parents, degenerating to copying; as , the children may move far beyond the parents and even outside the bounds, relying on truncation as a fallback.
Block 2 ⑤: mutation must be decided independently for each gene. A common error is “draw one random number per individual to decide whether the whole string mutates”. This makes mutation either happen entirely or not at all, completely wrecking the granularity of schema disruption. The correct implementation draws one random number for each gene.
Block 2 ⑥: evaluation and best-update must come after mutation. Crossover produces “children before mutation”; only after mutation are they final children. If the evaluation happens before mutation, the recorded best value corresponds to an intermediate solution that never entered the population, and best_x and best_f become mismatched.
Block 2 ⑦: choosing between (μ+λ) and (μ,λ). The generational model replaces the whole population each generation; (μ+λ) merges parents and children and keeps the best , which converges more stably but is more prone to premature convergence; (μ,λ) selects only from the children and forcibly discards the parents, giving better diversity but possibly losing good solutions. In practice, “elitism + generational model” is the common compromise.
Block 2 ⑧: converting between population size and evaluation budget. is the total number of evaluations (plus initialization and elite copies). If the budget is fixed at , then . If is too small, genetic diversity per generation is insufficient (building blocks cannot be assembled); if is too large, there are too few generations (recombination has no time to happen). Empirically lies between and , and the larger the combinatorial problem, the larger should be.
3.8 Per-Step Read/Write and State-Maintenance Checklist
| Quantity | When read | When written | Kept across generations | Consequence of writing it wrong |
|---|---|---|---|---|
| (population) | Every generation | End of every generation | Must be kept | Re-randomizing every generation degenerates to random search |
| (fitness) | During selection | After every evaluation | Kept | Running roulette wheel directly on untransformed objective values; negative values make probabilities illegal |
best_x, best_f | Compared every generation | Only when a better solution appears | Must be kept | Resetting every generation kills the “historical best” and the curve may decrease |
Elite | Start of every generation | Start of every generation | Copied across generations | Elites must not be mutated; mutating them accidentally means there is no elitism at all |
| Every generation | Constant or adaptive | Kept | If adaptation goes the wrong way (lowering when diversity is low), premature convergence is accelerated | |
| Random-number stream | Every operator | — | Kept (reproducible) | Without a fixed seed, experiments cannot be compared |
| Cache | Before evaluation | After evaluation | Kept across generations | Exact floating-point equality matching fails |
Three decision rules:
- “Elites” are read-only copies and take part in no operator. Once an elite is rewritten by crossover or mutation it is no longer “the best solution of the previous generation”, and the whole guarantee of elitism is void.
- “Fitness” and “objective value” must be stored separately. The objective value is used for reporting and comparison, the fitness for selection; confusing the two disables penalties, scaling and rank-based selection alike.
- “Population size” must be conserved. The number of individuals entering the next generation must be exactly ; any branch where “the number of children differs from the expectation” must explicitly top up or truncate, otherwise the drift in size silently changes the selection pressure.
3.9 Pitfall Checklist
| Symptom | Possible cause | Fix |
|---|---|---|
| Fast improvement in the first generations, then long stagnation | Population converged prematurely, crossover lost its recombination ability | Increase ; reduce tournament to 2; raise ; add niching/crowding distance |
| The best-value curve decreases | No elitism, or elites rewritten by operators | Add elitism with and let elites skip crossover and mutation |
| Binary encoding performs poorly at adjacent integers | Hamming distance of ordinary binary code disagrees with numeric distance | Switch to Gray code |
| Continuous problems converge to boundary values | Children produced by mutation/crossover go out of bounds and are simply truncated, piling up at the boundary | Use bounded SBX, reflective boundaries, or penalize boundary solutions |
| All individuals become identical after a few generations | Selection pressure too strong, too small, mutation rate too low | Reduce , increase , raise (or use adaptive mutation) |
| Many infeasible solutions on constrained problems | Penalty coefficient too small, or the initial population lies entirely outside the feasible region | Raise ; use a feasibility-first comparison rule; project into the feasible region at initialization |
| Permutation encoding produces duplicate cities or missing tasks | One-point crossover used without repair | Use order-preserving crossovers such as OX/PMX and validate legality after generating the children |
| Results differ enormously between runs | Randomness + too small a budget + no independent repetitions | Fix the seed for debugging; report the median and quartiles of 10 to 30 independent runs |
Among these, “one-point crossover on permutation encoding” is the most typical: after one-point crossover of two legal permutations, the child almost certainly contains duplicated and missing elements. One must either “deduplicate + fill the gaps” after crossover, or use a crossover operator designed specifically for permutations.
3.10 Scope of Application
Suitable: discrete or mixed variables, obvious combinatorial structure, and problems where “good fragments” can be defined clearly. Typical scenarios include: TSP and the Vehicle Routing Problem (VRP), job-shop scheduling, sparse layout of antenna arrays (which positions carry array elements), feature selection (which features enter the model), coarse search in neural architecture search, and “which set of parameters to choose” problems in wireless resource allocation.
Not suitable:
- Continuous, high-dimensional, requiring high accuracy — GA usually converges more slowly than CMA-ES and gradient-based methods, especially for .
- Extremely small evaluation budget (a few dozen evaluations) — GA needs a large enough population to assemble complementary building blocks; with too small a budget, PSO or local search is better.
- Objective functions with no decomposable fragment structure — if the combination of any two good solutions is not necessarily good (strong epistasis), the recombination advantage disappears and GA degenerates into random search with selection pressure.
- Requiring incremental improvement of a single feasible path — SA or local search is more suitable.
4. Simulated Annealing (SA)
4.1 Why It Is Needed: Local Search That Allows “Temporarily Going Downhill”
The problem Simulated Annealing (SA, Kirkpatrick et al., 1983; Černý, 1985) solves is: local search stops as soon as it reaches a local optimum — how do you make it climb out?
The predicament of local search (which accepts only better neighbors at every step) can be stated in one sentence: it can only see “downhill”, never “the higher mountain on the other side of the valley”. Starting from a local optimum, any single-step move makes the objective worse, so the algorithm stops there. To escape a local optimum one must allow “temporarily going downhill” — but allowing downhill moves brings a new problem: if worse solutions are accepted without limit, the algorithm degenerates into a random walk and never converges.
SA’s answer is: use a temperature parameter that decreases with “time” to control how permissive the algorithm is in accepting worse solutions. Early on the temperature is high, almost any solution is accepted, and the algorithm wanders over a large region; as the temperature drops, the probability of accepting a worse solution becomes smaller and smaller; when the temperature approaches zero, the algorithm degenerates into local search that “accepts only better solutions”. This process is exactly isomorphic to metal annealing (at high temperature atoms move freely; after slow cooling they settle into a low-energy crystal lattice).
The key difference from PSO and GA: SA is a single-point algorithm. It has no population, no crossover, no information sharing; it has only “the current solution” and “a temperature”. Hence it is the simplest to implement and the most memory-efficient, but it is also the most sensitive to the accidents of a single trajectory.
4.2 Principles: The Metropolis Criterion
Let the current solution be with objective value , and let a neighborhood generator produce a candidate solution ; define the objective difference
(this note minimizes , so means an improvement). The Metropolis acceptance criterion is
That is: an improvement is always accepted, a deterioration is accepted with the Boltzmann factor. The larger the temperature , the closer is to 1 and the more easily a worse solution is accepted; as , any positive difference drives the probability to zero.
Derivation 9: Detailed balance and the Boltzmann stationary distribution
Step 1: write “state transitions” as a Markov chain. At a fixed temperature , the inner loop of SA is a Markov chain whose state is the solution , with transition probability
where is the probability that the neighborhood generator “proposes” and is the Metropolis acceptance probability. Assume the proposal distribution is symmetric, that is, .
Step 2: verify detailed balance. We claim that the stationary distribution of the chain is the Boltzmann distribution
and we need to verify that for any two states :
Consider two cases.
Case 1: . Then
The left-hand side is ; the right-hand side is
By the symmetry of , the two sides are equal.
Case 2: . Then both directions carry an exponential factor, and the two sides are again equal by the symmetry of .
Step 3: derive stationarity from detailed balance. Detailed balance means
where the last step uses “transition probabilities sum to 1 over the target states”. This is exactly the definition of a stationary distribution , so the Boltzmann distribution is the stationary distribution of the chain.
Step 4: the engineering meaning of this result. It says that SA is not “walking around at random” but deliberately sampling a distribution weighted by . When the temperature is high the distribution is nearly uniform (it goes everywhere); when the temperature is low the distribution concentrates on regions of low (it stays near good solutions). This explains why SA can “roam globally first and converge locally later” on multimodal landscapes — not by luck, but through a Markov chain with an explicit stationary distribution.
4.3 Why It Converges to the Global Optimum as Temperature Goes to Zero
Derivation 10: Why the chain converges to the global optimum as temperature goes to zero
Step 1: write the weight ratio between the optimum and the runner-up. Let the global optimum value be and the second-best local optimum value be , with (assume for simplicity that the optimum is unique). Under the Boltzmann distribution, the ratio of the weights of the two states is
Step 2: take the limit. As , and the exponent tends to , hence
That is, the weight of the optimal state tends to infinity relative to any suboptimal state; after normalization,
where is the set of globally optimal solutions. This is the precise statement of “as the temperature goes to zero, the distribution stays only on the global optimum.”
Step 3: why “temperature goes to zero” is not “temperature equals zero”. If from the start, the chain moves only in strictly decreasing directions and can never leave a local optimum once it enters one; the final distribution then depends on the initial solution and is not the Boltzmann distribution. Hence the schedule must be “high temperature first, low temperature later”: the high-temperature phase lets the chain mix and washes out the influence of the initial solution; the low-temperature phase contracts the distribution onto the optimum.
Step 4: why SA in finite time does not guarantee optimality. The limit above requires and a chain that runs long enough at every temperature (reaching the stationary distribution). A practical algorithm satisfies neither condition: the temperature falls to the bottom in finitely many steps, and every temperature runs only steps. Hence practical SA returns a solution that is “very likely good”, not the theoretical optimum. The gap is determined jointly by the cooling rate and the chain length, which is exactly the trade-off discussed in 4.4.
4.4 Cooling Schedules: Logarithmic versus Geometric
Derivation 11: The trade-off between logarithmic cooling and geometric cooling
Step 1: write the three schedule families. There are three common cooling schemes:
Step 2: convergence of logarithmic cooling. Hajek (1988) proved: if the temperature decreases as
and is no smaller than “the escape depth of the deepest local optimum” (that is, the largest energy barrier that must be crossed to climb from that local optimum to a higher solution), then SA converges to the global optimum with probability 1. The intuitive reason is that “sums of escape probabilities” such as diverge under logarithmic cooling, so the chain has infinitely many chances to escape any local optimum.
Step 3: why logarithmic cooling is unusable. To cool to a sufficiently low temperature, logarithmic cooling requires a number of steps that grows exponentially with problem size. Roughly, to bring down to requires
When , , far beyond any engineering budget. It has a theoretical guarantee but no practical value.
Step 4: why geometric cooling became the default. Geometric cooling multiplies by a fixed ratio every step, and the number of steps needed to reach is
With , and , ; with , . It has no convergence guarantee, but the number of steps depends logarithmically on the “temperature span”, so it is controllable and can be budgeted. In engineering is usually between and : the closer to 1, the slower the cooling, the better the result, and the longer the runtime.
Step 5: three empirical rules for a practical schedule.
- Set the initial temperature by the acceptance rate. First generate a number of neighborhood solutions at random and record the acceptance rate; take the temperature at which the acceptance rate is about as . An acceptance rate that is too low means the initial temperature is not high enough and the algorithm is stuck in a local region from the start.
- Set the final temperature by “almost nothing is accepted”. When the acceptance rate drops below , the temperature is already low enough and further cooling is just idle spinning.
- Match the chain length to the neighborhood scale. If is too small, no temperature reaches the stationary distribution and the behavior of the chain depends on the residual state from the previous temperature; if is too large, the temperature cannot drop far enough. Common values are to , or a fixed to .
4.5 Pseudocode: SA (Full Version)
Algorithm: SA (single chain, single point; for the parallel version run several chains independently and take the best)
Input: objective function f, initial solution x0 (random, or a greedy/constructed solution)
neighbor(x) neighborhood generator (returns a candidate solution close to x)
T0 initial temperature (calibrated to an initial acceptance rate of about 0.8)
T_min final temperature (calibrated to an acceptance rate of about 1e-3)
alpha cooling factor (0.9 ~ 0.99)
L number of inner-loop iterations per temperature (usually 10D ~ 100D)
N_FE_max upper limit on the number of evaluations
Output: best_x, best_f
# ---------- Block 1: initialization ----------
x <- x0
f_x <- f(x); N_FE <- 1
best_x <- x, best_f <- f_x
T <- T0
# ---------- Block 2: outer temperature loop ----------
while T > T_min and N_FE < N_FE_max:
accept_count <- 0
# 2.1 inner loop: run L steps of the Markov chain at a fixed temperature
for k = 1 .. L:
x_new <- neighbor(x)
x_new <- repair_to_feasible(x_new) # project or reject if out of bounds
f_new <- f(x_new); N_FE <- N_FE + 1 # check the cache first
delta <- f_new - f_x
if delta <= 0:
accept <- True
else:
u ~ U(0,1)
accept <- (u < exp(-delta / T)) # use the log form to avoid underflow, see 4.6
if accept:
x <- x_new, f_x <- f_new
accept_count <- accept_count + 1
if f_x < best_f:
best_x <- x, best_f <- f_x
# 2.2 cooling (geometric schedule) and adaptive termination
T <- alpha * T
if accept_count == 0:
break # frozen, terminate early
return best_x, best_f
Two engineering details in the pseudocode deserve to be singled out: using a logarithmic comparison for the acceptance decision, and terminating early when the acceptance count reaches zero.
4.6 Section-by-Section Walkthrough of the Pseudocode
Block 1 ①: the initial solution may come from a constructive heuristic. The final quality of SA is insensitive to the initial solution (the high-temperature phase “washes it out”), but the budget is sensitive to it: a good initial solution lets the algorithm get through the high-temperature phase faster. In engineering, “greedy construction + SA improvement” is common; for example, in a TSP one first constructs a tour with nearest neighbor and then improves it with 2-opt/3-opt.
Block 2 ②: the purpose of the inner loop is “to let the chain approach stationarity”. At a fixed temperature the chain needs several steps to move from “the residual distribution of the previous temperature” to “the Boltzmann distribution of the current temperature”. If is too short the chain does not mix and SA degrades into a reinforced greedy hill-climbing that “cools at every step”; if is too long there are too few cooling steps, and the budget runs out before the final temperature is reached.
Block 2 ③: why the acceptance decision should use a logarithmic comparison. Computing directly underflows to 0 when is large (which is harmless in itself), but loses precision when is small. The more robust form compares
The two are mathematically equivalent (take the logarithm of and then compare), but the latter avoids exponential overflow and makes it easy to decide “reject” directly when is large.
Block 2 ④: the neighborhood generator determines SA’s “terrain resolution”. For continuous variables the usual choice is “add a Gaussian perturbation near the current solution”, with ; for a TSP, 2-opt (swap two edges and reverse a segment of the tour) or 3-opt; for scheduling, “swap the order of two tasks”. The neighborhood scale should decrease with temperature: large jumps at high temperature (global exploration), small adjustments at low temperature (fine local search). Fixing is a common mistake — the steps are then too small at high temperature and too large at low temperature.
Block 2 ⑤: terminate early when the acceptance count is zero. When the temperature is very low and no better solution can be found in the neighborhood, accept_count is 0 and the chain has “frozen” onto the current solution. Further cooling only burns evaluation budget (because worse solutions are all rejected and every evaluation is wasted). The early break is a necessary engineering safeguard.
Block 2 ⑥: best_x and the current solution x must be stored separately. The current solution of SA may be worse than the historical best because a worse solution was accepted; the reported result must use best_x, never the final x. This is one of the most common errors in SA implementations — many reproduction codes return the final solution directly, which makes the result look “worse than the best recorded midway”.
Block 2 ⑦: the order of constraint handling. “Repair” first, then “evaluate”. If the candidate solution is infeasible, either project it onto the feasible region (continuous problems) or reject it outright (discrete problems). Never evaluate first and then check feasibility — the evaluation of an infeasible solution is meaningless and wastes budget.
4.7 Per-Step Read/Write and State-Maintenance Checklist
| Quantity | When read | When written | Kept across temperatures | Consequence of writing it wrong |
|---|---|---|---|---|
x (current solution) | Every step | On acceptance | Must be kept | Resetting it to best_x every step degenerates into greedy hill-climbing and loses the point of annealing |
f_x | Every step | In sync with x | Must be kept | Changing x without f_x misaligns every computation |
best_x, best_f | Compared every step | Only when better | Must be kept | Replacing the historical best by the final solution makes the reported result worse |
T | Every step | End of every temperature | Decreasing | Forgetting to cool means eternal random walking; cooling too fast degenerates into local search |
L | Every temperature | Constant or adaptive | Kept | When it does not match the dimension the chain never mixes |
| Neighborhood scale | Every proposal | Decreasing with temperature | Kept (decreasing) | A fixed scale gives too little exploration at high temperature and too little refinement at low temperature |
accept_count | End of every temperature | Reset to zero at the start of every temperature | Reset at every temperature | Forgetting to reset makes the acceptance statistics accumulate across temperatures and triggers a false early termination |
| Cache | Before evaluation | After evaluation | Kept across temperatures | Exact floating-point matching fails |
The key judgment: accept_count is the only quantity that must be reset at every temperature; everything else is kept across temperatures. This is isomorphic to the lesson “advantages may be normalized but value targets may not” in reinforcement learning — statistics and state must be managed separately; mixing them produces the problem of “it looks converged, but the accounting basis was wrong”.
4.8 Pitfall Checklist
| Symptom | Possible cause | Fix |
|---|---|---|
| The result is almost identical to the initial solution | Initial temperature too low, too small, frozen within a few steps | Calibrate by the initial acceptance rate (about 0.8); raise above 0.95 |
| Runs for a long time but the result is still poor | Chain length too short, no mixing at each temperature; wrong neighborhood scale | Increase ( to ); let decrease with temperature |
| Acceptance rate stays near 1 for a long time and then suddenly freezes | Cooling curve too flat ( too close to 1) or final temperature set too high | Shorten the temperature span; take between 0.9 and 0.95 |
| The final solution is worse than the best recorded midway | Returned the current solution x instead of best_x | Always maintain best_x/best_f separately |
| Many evaluations wasted on infeasible solutions | Evaluating before checking feasibility; the neighborhood generator ignores constraints | Repair/project first, then evaluate; reject illegal candidates outright for discrete problems |
| Results vary enormously between runs | Single chain, insufficient budget, random initial value | Run multiple chains in parallel (different initial values) and take the best; or take statistics over several runs |
| Almost no movement on high-dimensional continuous problems | Neighborhood perturbation is independent and identically distributed per dimension, so the “effective step” is too small relative to the search space in high dimensions | Scale per dimension (e.g. ); switch to an adaptive neighborhood |
| Still improving after the temperature reaches | Final temperature too high, or L so large that each temperature takes too long | Lower (acceptance rate ); derive backward from the budget |
4.9 Scope of Application
Suitable: combinatorial optimization, a clear neighborhood structure, and problems where point-by-point improvement of “a single path” is acceptable. Typical scenarios include: 2-opt/3-opt improvement for TSP and VRP, integrated circuit placement, graph partitioning, frequency assignment, sparse layout of antenna arrays, parameter calibration (fine local refinement of continuous variables), and fine tuning of machine learning hyperparameters.
Not suitable:
- Very expensive objective evaluations with a budget of only a few dozen calls — SA needs enough chain steps to be effective; with too small a budget a constructive heuristic is better.
- Requiring parallelism with linear speed-up — single-chain SA is inherently serial; multiple chains can run in parallel, but they share no information and the speed-up is limited by the statistical gain of “taking the best”.
- Neighborhood structure hard to define — the entire effect of SA relies on the assumption that “the objective values of neighboring solutions are highly correlated”; if a single neighborhood jump crosses the whole search space, the Metropolis acceptance probability loses meaning.
- Requiring a strict convergence guarantee with a sufficient budget — “logarithmic cooling + extremely long chains” can be used, but it is practically infeasible; real applications should accept “approximately optimal”.
5. Ant Colony Optimization (ACO)
5.1 Why It Is Needed: Treating “a Path” as a Learnable Object
The fundamental difference between Ant Colony Optimization (ACO, Dorigo, 1992; Dorigo & Gambardella, 1997) and the previous three algorithms is: it does not search for “a solution vector”, it searches for “a construction path”.
For a problem such as the TSP, the solution is an order in which all cities are visited. GA treats this order as a permutation encoding and applies crossover and mutation to the whole string; SA treats it as a path and modifies it locally with neighborhood moves such as 2-opt; ACO treats it as “a sequence of edges chosen step by step” — an ant starts from some city, at every step chooses the next unvisited city by probability, and after a full round it obtains a complete tour. The construction process of the solution is itself the search process, and the “preferences” used during construction are written into a pheromone table.
This viewpoint brings two immediate benefits:
- Constraints are satisfied naturally. An ant chooses only from the set of “unvisited cities”, so the constructed tour is always legal (every city visited once) and needs no post-hoc repair. GA’s one-point crossover breaks permutation legality, and SA’s 2-opt must also be careful to keep the tour legal.
- Experience can be reused “per edge”. The experience of a good path is decomposed into “which edges are good” and written into , and later ants can use it from any position; by contrast, PSO’s is “a point” and GA’s population is “the whole string”, so neither can decompose local experience for separate reuse.
The price is: ACO can only handle problems whose objective decomposes into a sum over edges or steps. If the objective is “the duration of the longest segment of the tour” or “the global load-balancing variance”, an ant halfway through the tour cannot evaluate “whether the current partial part is good”, and the pheromone loses its learnable signal.
5.2 Construction Rule: The Transition Probability
Take the TSP as the example. There are cities, the distance from city to city is , and the heuristic information is taken as
that is, “the shorter the edge, the more it is worth taking”. The pheromone is what the algorithm itself learns about “how many good paths have used this edge in history”. If ant is currently at city and the set of unvisited cities is , the probability of choosing the next city is
where is the pheromone exponent and is the heuristic exponent. The original papers denote these two exponents by ; this note adds subscripts to avoid confusion with the cooling factor .
The structure of this formula is worth remembering: it is a weighted geometric mean of “historical experience” and “local greediness”. The pheromone term represents “the roads others have taken”, the heuristic term represents “the short edges visible right now”; the two exponents decide whose voice is louder.
Derivation 12: The form of the transition probability and the meaning of its two exponents
Step 1: write the probability in exponential-family form. Take the logarithm of the transition probability:
The last term depends only on the current city and the candidate set and has no influence on “which edge to choose”; it is a normalization constant. Hence the choice preference is determined entirely by .
Step 2: explain the two extremes. Let :
Then the ant looks only at pheromone and ignores edge lengths entirely. If the initial pheromone is uniform, the first round is completely random; later rounds are determined entirely by historical paths — this is pure positive feedback, and it easily amplifies a path discovered by accident early on without bound (premature convergence).
Let :
Then the ant looks only at edge lengths, which is equivalent to “randomized greedy construction” (degenerating to deterministic nearest neighbor as ). It has no learning ability at all — every round produces the same result and the pheromone is purely decorative.
Step 3: understand as an “inverse temperature”. Suppose the values of are close to each other; expanding around its mean makes equivalent to “amplifying the pheromone differences by a factor of ”. The larger is, the more the probability concentrates on the edge with the highest pheromone (more greedy, more like low-temperature Boltzmann selection); the smaller is, the closer the probability is to uniform (more exploration, more like high temperature). This plays exactly the same role as the SA temperature and the softmax temperature in reinforcement learning.
Step 4: the probability of a whole path is the product of the stepwise probabilities. Since each step’s choice depends only on “the current city + the unvisited set”, the construction probability of the whole tour is
This is the “likelihood of a sequential decision”: the probability of a path is the product of the probabilities of all its steps. The goal of the pheromone update is to make the construction probability of “good paths” larger — formally consistent with “raising the probability of high-return trajectories” in policy gradients (see Derivation 13).
5.3 Pheromone Update: Evaporation and Deposition
After all ants have finished one round of construction, the pheromone is updated in two steps:
where is the evaporation rate, is the number of ants, and is the pheromone deposited by ant on edge . The most common deposition rule (the Ant-Cycle model) is
is the length of the tour constructed by ant and is a constant. The meaning of this rule is: the shorter the tour, the larger the reward each edge it used receives. Short edges are marked by more and stronger pheromone and are more likely to be chosen in the next round, forming positive feedback.
The two steps each do their own job:
- Evaporation is “forgetting”, equivalent to giving old information an exponential decay; it prevents an early wrong path from being locked in forever, and also keeps the pheromone from accumulating without bound until numerical overflow.
- Deposition is “reinforcement”, writing the good experience of the current round into the table.
Derivation 13: Correspondence between pheromone update and reinforcement learning
Step 1: write the update as a “value update with forgetting”. Let be regarded as “the value estimate of edge ” and as the learning rate; then the update
can be rearranged as
This has exactly the form “value ← value + learning rate × (target − value)”, where the target term is
By the Ant-Cycle model, (if the ant used the edge), so is proportional to “the sum of the reciprocals of the tour lengths of the ants that used this edge” — it is a Monte Carlo estimate of the return of the paths this edge participated in.
Step 2: correspond item by item. Compare ACO with reinforcement learning (especially “constructive” sequential decision making):
| Quantity in ACO | Counterpart in RL | Remark |
|---|---|---|
| Current city + unvisited set | State | The state is determined jointly by “position + visited set” |
| Choosing the next city | Action | The action space changes with the state (legal actions = unvisited cities) |
| Policy | A softmax policy weighted by pheromone and heuristic information | |
| Tour length | Episode return (negated) | The goal is to minimize , equivalent to maximizing |
| State–action value | The same table serves both as policy parameter and as value estimate | |
| Evaporation | Learning rate / forgetting factor | Controls how fast old estimates are overwritten |
| Sum of deposits from several ants | Average of Monte Carlo returns | Uses several episodes to reduce variance |
| MMAS bounds | Value clipping | Prevents the estimate from being blown up by extreme samples |
Step 3: point out three key differences.
- No bootstrapping. Temporal difference (TD) methods in reinforcement learning update using “immediate reward + value estimate of the next state”; ACO uses only “the true length of the completed tour” and never uses “a value estimate of the unfinished part”. Hence ACO updates are purely Monte Carlo: high variance but unbiased.
- Policy and value are coupled. In Actor-Critic the policy network and the value network have two separate parameter sets; in ACO the pheromone determines both “the probability of choosing an edge” and “the value of the edge”. This brings one benefit (extremely simple implementation) and one drawback (exploration strength cannot be controlled independently: to explore more you can only lower , which also changes how the value is used).
- No discount factor. Every segment of the tour length has the same weight and there is no . This suits additive objectives such as “total tour length”, but not temporal problems where “earlier decisions matter more”.
5.4 Pheromone Initialization, the Elitist Strategy and MMAS
Two extremes of initial pheromone. AS usually initializes (a very small positive constant, such as ), letting the first round be dominated almost entirely by the heuristic; MMAS initializes to , making the first round favor exploration (because all edges are saturated and the only differences can come from ).
The elitist strategy. Each round, an extra portion of pheromone is given to the edges of “the best tour so far”:
is the number of elites and is the length of the global best tour. It amounts to giving “the current best solution” extra replication opportunities, which accelerates convergence but also accelerates premature convergence.
The MAX-MIN Ant System (MMAS, Stützle & Ho, 2000) is the most important improvement of ACO and contains three elements:
- Only one ant updates the pheromone — each round only the “iteration best” or the “global best” deposits, and the other ants deposit nothing. This replaces “averaging over many ants” with “learning only from the best”, greatly reducing variance.
- Pheromone is clamped to , preventing an edge from being reinforced without bound or driven completely to zero.
- Pheromone is initialized to and reset to when there has been no improvement for a long time (the restart mechanism).
Derivation 14: Origin and role of the MMAS pheromone upper and lower bounds
Step 1: compute the steady-state value of “an edge reinforced every round”. In MMAS, suppose an edge is used by the best ant every round with deposit (taking ); then the pheromone evolves as
This is a first-order linear recursion whose fixed point satisfies , and which converges to it from any initial value at rate :
Step 2: take the upper bound. Since (only the best tour can deposit, and the shorter the tour the larger the deposit), the steady-state upper bound is
This is the origin of the MMAS upper bound: it is the saturation value when “the optimal edge is reinforced every round”. Values beyond it are meaningless and only let that edge monopolize the choices.
Step 3: derive the lower bound from the “minimum selection probability”. In TSP construction there are at most candidate edges at each step. If we require that “the probability of any edge being chosen at any step is not below ”, then in the worst case (the other edges all have pheromone ) the pheromone of that edge must satisfy at least
Taking and solving for gives
The standard form given by Stützle & Ho (for an -city TSP with ) is
It differs from the rough form above by a factor, because “an edge must be chosen at least once during the whole -step construction” requires converting the single-step probability into a “whole-tour-level probability”. The engineering meaning of the two forms is the same: the lower bound guarantees that no edge is starved completely, so the search always retains a minimum level of diversity.
Step 4: three roles of the bounds.
- Preventing monopoly: the upper bound stops one edge from attracting all ants.
- Preventing starvation: the lower bound guarantees that an edge “temporarily judged bad” still has a chance to recover — this is exactly the ACO version of an “exploration floor”.
- A reproducible tuning baseline: are computed directly from and need no manual tuning, which makes MMAS far more robust than AS.
5.5 Pseudocode: ACO (Unified AS and MMAS)
Algorithm: ACO (Ant-Cycle model; TSP as the example, n cities and m ants)
Input: distance matrix d[i][j] (i,j = 1..n)
m number of ants (usually n or 2n; MMAS usually n)
T_max maximum number of iterations
alpha_tau pheromone exponent (usually 1)
beta_tau heuristic exponent (usually 2 ~ 5)
rho evaporation rate (usually 0.1 ~ 0.5)
Q deposition constant (1 is enough; the units are absorbed by rho)
mode "AS" or "MMAS"
tau_max, tau_min (MMAS) precomputed by the formulas in 5.4
Output: best_tour (sequence of cities), best_length
# ---------- Block 1: initialization ----------
if mode == "AS":
tau[i][j] <- tau0 (a very small constant, such as 1e-6) for all i != j
else: # MMAS
tau[i][j] <- tau_max
best_tour <- empty, best_length <- +inf
# ---------- Block 2: iterations ----------
for t = 1 .. T_max:
tours <- empty, lengths <- empty
# 2.1 every ant independently constructs one complete tour
for k = 1 .. m:
start <- pick a city at random (it may also be fixed to city 1)
tour <- [start], visited <- {start}
for step = 2 .. n:
i <- the last city of tour
# candidate set = all unvisited cities
for j in (1..n) \ visited:
w[i][j] <- tau[i][j]^alpha_tau * (1/d[i][j])^beta_tau
p[j] <- w[i][j] / sum_l w[i][l] # normalization
j <- sample according to p (roulette wheel)
tour <- tour + [j], visited <- visited + {j}
length <- total tour length(tour)
tours <- tours + {tour}, lengths <- lengths + {length}
# 2.2 optional local improvement (2-opt / 3-opt), which does not add evaluations of f
tour <- 2opt(tour)
if length < best_length:
best_tour <- tour, best_length <- length
# 2.3 evaporation (all edges decay uniformly)
for every edge (i,j):
tau[i][j] <- (1 - rho) * tau[i][j]
# 2.4 deposition
if mode == "AS":
for k = 1 .. m:
for (i,j) in tours[k]:
tau[i][j] <- tau[i][j] + Q / lengths[k]
else: # MMAS: only the single best ant deposits
tour_best <- the shortest tour of this round (or the global best; choose one, often alternating)
for (i,j) in tour_best:
tau[i][j] <- tau[i][j] + 1 / length(tour_best)
# 2.5 MMAS: clamp to [tau_min, tau_max]
if mode == "MMAS":
for every edge (i,j):
tau[i][j] <- clip(tau[i][j], tau_min, tau_max)
# optional: if best_length is unchanged for several consecutive rounds, reset tau <- tau_max
return best_tour, best_length
Four error-prone points in this pseudocode are: the candidate set must exclude visited cities, evaporation must come before deposition, only one ant deposits in MMAS, and clamping must come after deposition.
5.6 Section-by-Section Walkthrough of the Pseudocode
Block 1 ①: must be handled. If two cities coincide (distance zero), overflows. In engineering the diagonal () should be excluded from the candidates and a very small quantity added to zero distances: .
Block 1 ②: never initialize the pheromone to zero. If , all in the first round are zero (the denominator is zero) and ants cannot choose. AS uses a tiny constant and MMAS uses precisely to avoid this degeneracy.
Block 2 ③: the weights must be recomputed at every step. Because the candidate set changes with the visit progress, the normalization denominator is different at every step. Precomputing the weights as a full matrix and reading them in the loop is a common optimization, but note that “excluding visited cities” must take effect at every step.
Block 2 ④: the sampling method affects reproducibility. Roulette wheel (cumulative probabilities + one random number) is the simplest; when there are many candidates, “weighted alias sampling” (the alias method) can reduce a single-step sample from to . Note that ACO’s randomness must come from “sampling by probability” and must not be replaced by “taking the edge with the largest probability” — the latter degenerates into deterministic greediness and the learning signal of the pheromone disappears (all ants take the same path and there is no diversity left to compare).
Block 2 ⑤: local search is free quality improvement. Running 2-opt once after a tour is constructed (repeatedly trying to swap two edges and reverse the segment between them) adds almost no objective evaluations (the tour length can be updated incrementally) but raises the solution quality by a large margin. The golden combination for ACO is “pheromone construction + local search”; pure ACO usually loses to the hybrid “construction + 2-opt” version.
Block 2 ⑥: the order of evaporation and deposition. If deposition came before evaporation, the pheromone deposited in the current round would immediately be discounted by , equivalent to shrinking the learning rate by a factor of , which contradicts the formula. The standard order is “evaporate for all edges first, then deposit ant by ant”.
Block 2 ⑦: in MMAS only one ant deposits, and this is the key to reducing variance. In AS all ants deposit, equivalent to averaging Monte Carlo returns; in MMAS only the best deposits, equivalent to “learning only from the best sample”. The latter has lower variance and converges faster, but is also more prone to premature convergence, so it must be paired with the bounds and restarts.
Block 2 ⑧: clamping must come after deposition. If clamping came before deposition, the deposited value could again exceed the upper bound; if deposition comes first and clamping after, the final table values are guaranteed to lie inside the bounds. Reversing the order renders the upper bound meaningless.
Block 2 ⑨: the restart mechanism. When the best value has not improved for several consecutive rounds (for example rounds), MMAS resets all pheromone to , equivalent to “erasing the experience and exploring again”. It is the ACO version of “learning-rate restart” or “exploration boost”, used to counter premature convergence.
5.7 Per-Step Read/Write and State-Maintenance Checklist
| Quantity | When read | When written | Kept across rounds | Consequence of writing it wrong |
|---|---|---|---|---|
| (pheromone table) | Every sample | Every round: evaporation + deposition | Must be kept | Resetting every round degenerates into “several ants constructing independently and greedily”, with no learning |
visited (visited set) | Every sample | Add a new city at every step | Reset for every ant | Forgetting to reset leaves the second ant with no legal move; forgetting to add causes repeated visits |
tour (current tour) | Every step | Append at every step | Reset for every ant | Reusing it across ants makes the tour illegal |
best_tour, best_length | Compared every round | Only when better | Must be kept | Overwriting every round loses the historical best |
| Every round | Constant or adaptive | Kept | Forgetting to evaporate saturates the pheromone and all ants take the same tour | |
| Clamped every round | Constant (precomputed from ) | Kept | Wrong bounds make clamping ineffective or flatten the table to identical values | |
Within-round tours/lengths | When depositing after evaporation | Cleared at the start of every round | Reset every round | Accumulating across rounds double-counts the deposition |
Three judgment rules:
- Pheromone is the only “learned quantity” kept across rounds; all other ant-level state (
visited,tour) must be reset for every ant. This is the same discipline as “the value network is kept across episodes while the trajectory buffer is cleared every episode” in reinforcement learning. best_tourmust be updated from the “locally improved” tour, not from the raw constructed tour; otherwise what is reported is “the constructed solution”, not “the solution actually used”.- The pheromone table has dimension (for a TSP), and one must explicitly ensure that the positions are never used; if the diagonal also takes part in normalization, a pseudo-edge “from a city to itself” is introduced.
5.8 Pitfall Checklist
| Symptom | Possible cause | Fix |
|---|---|---|
| All tours identical in the first round | Initial pheromone is zero or huge, making the probabilities degenerate | AS uses ; MMAS uses and ensures is discriminative |
| After a few rounds all ants take the same tour (premature) | too small, too large, no bounds | Increase ; reduce ; use the MMAS and restarts |
| Pheromone values overflow or all become 0 | No evaporation leading to unbounded accumulation; or too large driving everything to zero | Evaporate every round; clamp in MMAS; take between 0.1 and 0.5 |
| The result is clearly worse than “greedy + 2-opt” | No local search; too small so edge lengths are ignored | Add 2-opt/3-opt; take between 2 and 5 |
| The convergence curve is flat for a long time and then suddenly jumps | Only the global best deposits and there is no restart, so the search stagnates | Alternate “iteration best” and “global best” deposition; add restarts |
| Results vary enormously between runs | Too few ants, too few rounds | Take between and ; add rounds; take statistics over several independent runs |
| Very poor results on non-TSP problems | The objective does not decompose into “a sum of edge weights”, or the constraints cannot be expressed as a “candidate set” | Change the modeling: write constraints into the candidate set; or switch to GA/SA |
| Runtime far above expectations | sampling per step, updates per round | Use incremental tour length, alias sampling, sparse pheromone (update only traversed edges) |
Among these, “poor results on non-TSP problems” deserves the most emphasis. The modeling premise of ACO is that “a solution = a sequence constructed step by step, and the local choice at each step can accumulate into the global objective”. If the objective contains non-additive terms such as “maximum”, “variance” or “minimum spacing”, or if the constraint is a “global resource cap” rather than “a set of choices available at each step”, constructive modeling breaks down — in that case one should switch to GA (writing constraints into the penalty function) or SA (writing constraints into neighborhood repair).
5.9 Scope of Application
Suitable: path and construction-type combinatorial problems on graphs, objectives decomposable into a sum of edge or step weights, and constraints expressible layer by layer as a “candidate set”. Typical scenarios include: TSP and VRP, network routing and load balancing, path planning for unmanned aerial vehicles or robots, job-shop scheduling (constructing “the operation order” as a sequence), set covering and graph coloring, frequency/channel assignment in communications (constructing “allocate resources to users” as stepwise choices), and port selection in antenna arrays.
Not suitable:
- Continuous or mixed variables — ACO needs “discrete candidates + stepwise construction”, and a continuous space has no natural “next candidate”.
- Objectives containing non-additive terms (maximum, variance, minimum spacing) — local construction cannot evaluate whether “the current partial part” is good.
- Requiring extremely fast convergence with a tiny budget — ACO needs several rounds before the pheromone accumulates enough discrimination; the first few rounds are essentially random construction.
- Solution spaces without an “edge” structure — for example pure function optimization, where ACO would have to construct a graph artificially, which usually costs more than it gains.
6. Cross-Algorithm Summary: Putting the Four Algorithms in One Coordinate System
6.1 One Master Table
| Dimension | PSO | GA | SA | ACO |
|---|---|---|---|---|
| Search unit | One point (particle) | One encoded string (individual) | One solution (single point) | One construction path (ant) |
| Population or single point | Population | Population | Single point (several chains may run in parallel) | Population (but individuals do not evolve) |
| Source of new solutions | Velocity-driven displacement | Selection + crossover + mutation | Neighborhood perturbation | Stepwise construction by probability |
| Form of memory | Positional () | Population-based (the whole string) | Almost none (only the current solution) | Edge-based (pheromone ) |
| Whether individuals are kept | Kept (overwritten) | Kept (generational replacement) | Not kept | Not kept (only pheromone remains) |
| Accepting worse solutions | Implicit (velocity may point to a worse region) | Implicit (mutation/crossover may produce worse children) | Explicit (Metropolis) | Implicit (probabilistic sampling) |
| Continuous variables | Native support | Needs real-valued encoding + SBX | Native support | Not supported |
| Discrete/combinatorial | Weak (needs a dedicated variant) | Strong | Strong (needs neighborhood design) | Strong (needs a graph structure) |
| Parallelism | High (particles are independent) | High (evaluations are independent) | Low (a single chain is serial) | High (ants construct independently) |
| Main parameters | ||||
| Theoretical guarantee | Stable parameter region (conditional) | Schema theorem (a lower bound, not a convergence guarantee) | Probability-1 convergence under logarithmic cooling | Convergence under specific conditions (MMAS is bounded) |
| Typical failure | Shared direction fails in high dimensions; premature convergence | Premature convergence; building blocks destroyed | Freezing; large variance of a single chain | Pheromone lock-in; failure on non-additive objectives |
| Best suited to | Continuous, moderate dimension, smooth multimodal | Discrete/combinatorial, fragments can be recombined | Combinatorial, clear neighborhood, single-path improvement | Construction-type combinatorial problems on graphs |
6.2 Six Key Divergences
Divergence 1: population or single point. PSO, GA and ACO are population algorithms; SA is a single-point algorithm. A population brings three benefits: parallel evaluation, information sharing, and lower variance; the price is that “managing population diversity” becomes a new tuning burden. SA’s single-point structure is the simplest to implement and the most memory-efficient, but its result is extremely sensitive to the accidents of a single trajectory — in engineering this is usually compensated by “running several chains in parallel” rather than by improving a single chain.
Divergence 2: where memory lives. This decides whether an algorithm “can decompose local experience for reuse”. PSO remembers positions (it knows “where is good” but not “how to get there”), GA remembers the whole string (fragments must be kept as a whole), ACO remembers edges (local experience can be reused independently), and SA remembers almost nothing. The “finer” the memory, the stronger the reuse ability, but the more easily it is misled by local experience — ACO’s pheromone lock-in and PSO’s misled are both consequences of “memory that is too fine or too strong”.
Divergence 3: how “worsening” is handled. SA explicitly allows worsening (Metropolis), while PSO, GA and ACO allow it implicitly: PSO’s velocity may carry particles into worse regions, GA’s crossover and mutation may produce worse children, and ACO’s probabilistic sampling may select a bad edge. The benefit of explicit allowance is analyzability (there is a stationary distribution); the drawback is that it needs a “temperature” to withdraw it. The benefit of implicit allowance is simplicity of implementation; the drawback is that the ability to “escape a local optimum” is uncontrollable.
Divergence 4: continuous or discrete. This almost decides the choice of algorithm. PSO and SA are natively usable in continuous spaces; GA needs real-valued encoding and real-valued operators (SBX, polynomial mutation); ACO is entirely unsuitable for continuous problems. In the other direction, PSO has no natural “position difference” on permutation/path problems and must invent a discrete variant; GA and ACO are in their element in discrete spaces. Look at the variable type first, then everything else.
Divergence 5: positive or negative feedback. ACO is a typical positive-feedback scheme (the pheromone of good paths accumulates); the core of SA is “negative feedback” — lowering the temperature suppresses the probability of accepting worse solutions; GA’s selection is “negative feedback” — bad individuals are eliminated; PSO’s is positive feedback (the whole swarm contracts onto one point). Positive feedback brings fast convergence, negative feedback brings stability. All four algorithms actually balance positive and negative feedback: ACO uses evaporation (negative) to balance deposition (positive), PSO uses inertia (maintaining direction) to balance the social term (contraction), GA uses mutation (introducing new information) to balance selection (elimination), and SA uses temperature (permissive) to balance cooling (tightening).
Divergence 6: is there a theoretical guarantee? This point is the most easily misread:
- SA has a probability-1 convergence guarantee under “logarithmic cooling + an infinitely long chain at every temperature”; the geometric cooling used in engineering has no such guarantee.
- GA’s schema theorem is a lower bound stating that “good schemas do not disappear too fast”, not that it “converges to the optimum”; the building-block hypothesis is heuristic and has many counterexamples.
- PSO’s convergence analysis yields a stable parameter region under the simplified model ” fixed, expectations taken”, not a guarantee of “convergence to the global optimum”; it only guarantees “convergence to an attractor”, which may be a local optimum.
- ACO’s convergence results depend on the specific variant (for example, the boundedness of MMAS and the ergodicity guaranteed by ), and are not “every ACO converges to the optimum”.
Practical implication: none of the four algorithms provides a “global optimality guarantee”; their value is “delivering a usable approximate solution within budget”. If a problem requires strict optimality, use branch and bound, integer programming, or dynamic programming; metaheuristics are a substitute for when those methods fail, not a “stronger method” that replaces them.
6.3 The Algorithm-Selection Decision Chain
Ask six questions in the following order and you can basically locate the algorithm to use:
- Is the objective differentiable? Is the problem unimodal? Yes → use gradient, Newton, or quasi-Newton methods; do not use metaheuristics. No → continue.
- Are the variables continuous, discrete, or mixed?
- Continuous → step 3.
- Discrete/combinatorial → step 4.
- Mixed → prefer GA (mixed encoding), or enumerate the discrete part and handle the continuous part with PSO/SA.
- Continuous case: how large is the dimension, how large is the budget?
- , budget to → PSO (fastest to implement, fewest parameters).
- , strongly coupled variables → CMA-ES (learns the covariance and suits high dimensions better than PSO).
- High-accuracy local refinement required → SA (small-step neighborhood) or “PSO coarse search + local-search refinement”.
- Discrete/combinatorial case: does the solution have a “path on a graph” structure? Does the objective decompose into a sum of edge weights?
- Yes → ACO (constructive modeling satisfies constraints naturally).
- No → step 5.
- Can the “good fragments” of the solution be defined and recombined independently?
- Yes → GA (crossover recombination is its core advantage).
- No → step 6.
- Is the neighborhood structure clear? Is point-by-point improvement of a single path acceptable?
- Yes → SA (or “constructive heuristic + SA improvement”).
- No → go back to step 2 and re-examine the encoding; if there is still no structure, the problem may need re-modeling rather than a different algorithm.
Three additional engineering judgments:
- Extremely small budget (a few dozen evaluations): do not use population algorithms; use “constructive heuristic + local search” directly, or a short-chain version of SA.
- Parallelism required with linear speed-up: evaluations in PSO, GA and ACO are naturally parallel; SA needs multiple chains in parallel (the chains share no information).
- An interpretable search process required: GA’s population evolution and ACO’s pheromone heat map can both be visualized; PSO’s particle trajectories can be plotted in low dimensions; SA has only one path, the most intuitive but also the least controllable.
6.4 Four Combinations That Are Easiest to Mismatch
| Wrong combination | Why it is wrong | Correct approach |
|---|---|---|
| PSO for a TSP / permutation problem | “Position difference” is undefined on permutations; forcing a definition (such as “swap distance”) makes the velocity lose its physical meaning | Use ACO (constructive) or GA (OX/PMX crossover) |
| GA for high-dimensional continuous fine tuning () | Binary/real encoding suffers severe crossover disruption in high dimensions and converges far more slowly than covariance-adaptive methods | Use CMA-ES, or PSO + local search |
| SA for large-scale parallel optimization | A single chain is serial and the chains share no information; the speed-up is limited by the statistical gain of “taking the best” | Use PSO/GA/ACO (populations are naturally parallel), or use SA as a local refinement stage |
| ACO for non-additive objectives (makespan, load variance) | The quality of “half a path” cannot be evaluated during construction, so the pheromone loses its learning signal | Use GA (penalty function for constraints) or SA (neighborhood repair for constraints) |
The common lesson of these four is: an algorithm’s “operators” must match the problem’s “structure”. PSO’s operator needs a metric, GA’s operator needs a splittable encoding, SA’s operator needs a neighborhood, and ACO’s operator needs an “edge-additive” objective. When operators and structure are mismatched, tuning can only alleviate the problem, never fix it.
6.5 One-Page Summary
| Algorithm | Remember it in three lines |
|---|---|
| PSO | Every particle remembers “my own best” and “the swarm’s best”; velocity = inertia + cognitive + social; parameters converge only inside . |
| GA | Selection lets good individuals reproduce more, crossover assembles good fragments, mutation introduces new genes; schemas (building blocks) with short defining length, low order and high fitness grow exponentially. |
| SA | Improvements are always accepted, deteriorations are accepted with probability ; as the temperature falls from high to low, the stationary distribution of the chain contracts from “uniform” to “global optimum”. |
| ACO | An ant chooses the next step with probability proportional to “pheromone × heuristic”; after finishing it deposits pheromone proportional to the reciprocal of the tour length, and all edges evaporate; positive feedback makes good paths increasingly attractive. |
6.6 Three General Principles
Principle 1: fix the budget before choosing the algorithm. The performance of any metaheuristic is relative to the evaluation budget; the question “which algorithm is better” is meaningless without a budget constraint. First work out “how long one evaluation takes and how many can be run in total”, then derive the population size, iteration count, and chain length backward from the budget.
Principle 2: obtain a feasible solution with a constructive heuristic first, then improve it with a metaheuristic. All four algorithms are good at “improving near an existing feasible solution” and bad at “constructing a feasible solution from scratch”. Use nearest neighbor for a TSP, list scheduling for scheduling, empirical values for parameter calibration, and then hand the result to SA/ACO/GA for improvement; this is usually an order of magnitude faster than a pure metaheuristic.
Principle 3: report statistics, not a single best run. Metaheuristics are stochastic algorithms, and the best value of one run is meaningless. The standard practice is: fix a random seed for debugging, and finally report the median, quartiles, and median number of evaluations needed to reach the target threshold over 10 to 30 independent runs; also report the “success rate” (how many runs reached the threshold). Reporting only “the best run” amounts to hiding the variance, which is seriously misleading in engineering.
6.7 Concept Mapping Against Reinforcement Learning
This section answers “why do these two families look so alike”. Putting the four algorithms and reinforcement learning in one table shows that they are almost different instances of the same abstraction:
| Concept in RL | PSO | GA | SA | ACO |
|---|---|---|---|---|
| State | Current particle position | One individual (encoded string) | Current solution | Current city + unvisited set |
| Action | Displacement after the velocity update | Selection/crossover/mutation operator | Neighborhood perturbation | Choosing the next edge |
| Policy | Velocity update rule (including random terms) | Operator probabilities () | Metropolis acceptance probability | Transition probability |
| Reward | (objective improvement) | (tour length negated) | ||
| Value | (historical best positions) | Population (carrier of good genes) | No explicit value | Pheromone |
| Exploration temperature | Large , large | Large , small | High | Small , large |
| Episode | One iteration | One generation | The chain at one temperature | The complete construction of one ant |
| Monte Carlo vs bootstrapping | Uses the true value (no bootstrapping) | Uses the true value | Uses the true | Uses the true tour length (no bootstrapping) |
| Experience replay | None (the historical best is the compressed experience) | The population is the experience pool | None | The pheromone table is the compressed experience |
| Target network / freezing | None | Elite preservation | None | The floor |
| Entropy regularization | Random terms | Mutation | High temperature | Evaporation + lower bound |
From this three “cross-domain” insights can be extracted:
- “The granularity of memory” determines how experience generalizes. The value function in reinforcement learning aggregates experience by state; ACO’s pheromone aggregates by edge; PSO aggregates by position; GA aggregates by the whole string. The finer the aggregation, the broader the reuse, and the more easily it is misled by local experience — this is isomorphic to the trade-off between “tabular methods and function approximation” in reinforcement learning.
- “Exploration strength” must decay over time, otherwise the algorithm does not converge. Reinforcement learning uses decay, entropy-coefficient decay, and temperature decay; metaheuristics use decay, adaptive , cooling, and adjustment of and . “Explore first, exploit later” is a cross-domain discipline, not a trick of any single algorithm.
- “Accepting worsening” is the only way out of a local optimum, but it has a price. SA uses temperature, reinforcement learning uses stochastic policies, GA uses mutation, ACO uses evaporation — all four mechanisms are essentially “giving a bad choice a controlled probability”. The price is higher variance and slower convergence; the benefit is avoiding premature convergence. No algorithm guarantees both “never getting worse” and “always escaping a local optimum”; this is the common lower bound of all search methods.
References
A. General surveys and theory of metaheuristics
- Wolpert, D. H., & Macready, W. G. (1997). No free lunch theorems for optimization. IEEE Transactions on Evolutionary Computation, 1(1), 67–82. (The original paper on the no-free-lunch theorem; it explains why no universal optimization algorithm exists and why an algorithm must carry a prior about the problem.)
- Goldberg, D. E. (1989). Genetic Algorithms in Search, Optimization, and Machine Learning. Addison-Wesley. (The classic textbook on genetic algorithms; the main source for the schema theorem, the building-block hypothesis, and engineering implementations.)
- Yang, X.-S. (2010). Engineering Optimization: An Introduction with Metaheuristic Applications. Wiley. (An engineering-oriented survey of metaheuristics; the unified framework and selection advice for the four algorithms.)
- Hajek, B. (1988). Cooling schedules for optimal annealing. Mathematics of Operations Research, 13(2), 311–329. (The rigorous result on the convergence of simulated annealing under logarithmic cooling; the basis of Derivation 11 in this note.)
B. Particle swarm optimization
- Kennedy, J., & Eberhart, R. (1995). Particle swarm optimization. Proceedings of ICNN’95, 1942–1948. (The original PSO paper; the initial form of the velocity update, still without an inertia weight.)
- Shi, Y., & Eberhart, R. (1998). A modified particle swarm optimizer. IEEE International Conference on Evolutionary Computation, 69–73. (Introduces the inertia weight ; the source of the linear-decrease strategy.)
- 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. (The constriction factor and the rigorous analysis of the convergence region; the basis of Derivation 4 in this note.)
- Trelea, I. C. (2003). The particle swarm optimization algorithm: convergence analysis and parameter selection. Information Processing Letters, 85(6), 317–325. (An alternative derivation of the PSO parameter stability region; a theoretical explanation of common parameter sets.)
C. Genetic algorithms
- Holland, J. H. (1975). Adaptation in Natural and Artificial Systems. University of Michigan Press. (The founding work on genetic algorithms; the source of the schema concept.)
- Deb, K., & Agrawal, R. B. (1995). Simulated binary crossover for continuous search space. Complex Systems, 9(2), 115–148. (The original SBX paper; the distributional interpretation of .)
- Deb, K., & Goyal, M. (1996). A combined genetic adaptive search (GeneAS) for engineering design. Computer Science and Informatics, 26, 30–45. (Polynomial mutation and the engineering implementation of real-coded GA.)
- Srinivas, M., & Patnaik, L. M. (1994). Genetic algorithms: a survey. IEEE Computer, 27(6), 17–26. (A survey of GA operators and parameter selection; the discussion of selection pressure and diversity.)
D. Simulated annealing
- Metropolis, N., Rosenbluth, A. W., Rosenbluth, M. N., Teller, A. H., & Teller, E. (1953). Equation of state calculations by fast computing machines. Journal of Chemical Physics, 21(6), 1087–1092. (The original source of the Metropolis acceptance criterion, predating the concept of annealing.)
- Kirkpatrick, S., Gelatt, C. D., & Vecchi, M. P. (1983). Optimization by simulated annealing. Science, 220(4598), 671–680. (The classic paper introducing annealing into combinatorial optimization; the engineering form of the temperature schedule and acceptance criterion.)
- Černý, V. (1985). Thermodynamical approach to the traveling salesman problem. Journal of Optimization Theory and Applications, 45(1), 41–51. (The paper that independently proposed simulated annealing for the TSP.)
- Bertsimas, D., & Tsitsiklis, J. N. (1993). Simulated annealing. Statistical Science, 8(1), 10–15. (A survey of SA convergence; a theoretical comparison of logarithmic and geometric cooling.)
E. Ant colony optimization
- 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. (The original paper on the Ant System; the complete definition of the pheromone update and transition probability.)
- 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. (The improved Ant Colony System version; local pheromone updates and the pseudo-random proportional rule.)
- Stützle, T., & Ho, H. H. (2000). MAX-MIN ant system. Future Generation Computer Systems, 16(8), 889–914. (The original MMAS paper; the derivation of and the restart mechanism, the basis of Derivation 14 in this note.)
- Blum, C. (2005). Ant colony optimization: introduction and recent trends. Physics of Life Reviews, 2(4), 353–373. (A survey of ACO; the applicability conditions of constructive modeling and theoretical progress.)
F. Engineering practice and algorithm selection
- Bäck, T., Fogel, D. B., & Michalewicz, Z. (Eds.). (1997). Handbook of Evolutionary Computation. Oxford University Press. (An engineering handbook of evolutionary computation; a systematic summary of encoding, operators, and constraint handling.)
- Hansen, N., & Ostermeier, A. (2001). Completely derandomized self-adaptation in evolution strategies. Evolutionary Computation, 9(2), 159–195. (The original CMA-ES paper; the preferred method for high-dimensional continuous black-box optimization, mentioned several times in this note as an alternative to PSO/GA.)
- Rardin, R. L., & Uzsoy, R. (2001). Experimental evaluation of heuristic optimization algorithms: a tutorial. Journal of Heuristics, 7(3), 261–304. (How to compare heuristic algorithms correctly; the conventions for budget accounting, multiple runs, and reporting statistics, corresponding to Principle 3 in 6.6.)
Appendix: Abbreviation Quick Reference
| Abbreviation | Full name | Explanation |
|---|---|---|
| ACO | Ant Colony Optimization | A population search method in which pheromone guides ants to construct paths step by step |
| AS | Ant System | The most original ACO version, in which all ants deposit pheromone |
| ACS | Ant Colony System | An improved ACO version with local pheromone updates and a pseudo-random proportional rule |
| CMA-ES | Covariance Matrix Adaptation Evolution Strategy | A high-dimensional continuous black-box method that learns correlations between variables |
| ES | Evolution Strategies | A family of black-box optimization methods that use population perturbation and selection |
| FE | Function Evaluation | An objective function evaluation (count), the unit for measuring the search budget |
| GA | Genetic Algorithm | A search method over an encoding space using selection, crossover and mutation |
| LHS | Latin Hypercube Sampling | A stratified sampling method that stratifies each dimension and then combines the samples |
| MCMC | Markov Chain Monte Carlo | A general framework for sampling a target distribution with a Markov chain |
| MMAS | MAX-MIN Ant System | An ACO variant that bounds the pheromone and lets only the best ant update it |
| NFL | No Free Lunch | The no-free-lunch theorem, stating that no algorithm is optimal for all problems |
| OX | Order Crossover | An order-preserving crossover operator designed for permutation encoding |
| PMX | Partially Mapped Crossover | A crossover operator designed for permutation encoding |
| PSO | Particle Swarm Optimization | A population search method in which velocity and personal/global bests guide the particles |
| RL | Reinforcement Learning | A method in which an agent interacts with an environment and improves decisions from rewards |
| SA | Simulated Annealing | A single-point search method that uses a decreasing temperature to control acceptance of worse solutions |
| SBX | Simulated Binary Crossover | A crossover operator for real-coded GA that mimics the behavior of binary crossover |
| TD | Temporal Difference | A method that updates values from “immediate reward + value estimate of the next state” |
| TSP | Travelling Salesman Problem | The problem of finding the shortest closed tour that visits every city exactly once |
| VRP | Vehicle Routing Problem | The problem of planning several delivery routes under capacity and time-window constraints |
Note on the origin and language of this article: This article is an original Chinese-language compilation; the formulas and pseudocode were checked item by item against the original references and classic textbooks listed above. The notation has been unified (for example, in the original PSO paper are written as , and in the original ACO papers are written as ), and every place where the notation differs from the original is annotated where it first appears in the text. The “complete pseudocode” for the four algorithms was written to the standard of “being directly implementable”, including engineering details such as caching, boundary handling, elitism, and pheromone clamping; for paper reproduction, please follow the operator definitions of the original references. All derivations in the text are pedagogical compilations, and the convergence analysis of PSO, the detailed balance and Boltzmann distribution of SA, the schema theorem of GA, and the MMAS bounds of ACO all provide intermediate steps that can be checked one by one; the applicability conditions of the theoretical conclusions (especially the point that “global optimality is not guaranteed”) are stated separately in Divergence 6 of 6.2.
Comments
Loading comments…
Want to leave a note? Sign in first — comments are open to every signed-in reader.