Contents

Metaheuristic Optimization Notes: Principles, Formulas and Pseudocode for PSO, Genetic Algorithms, Simulated Annealing and Ant Colony Optimization

Optimization Algorithms
#Metaheuristics#Particle Swarm Optimization#Genetic Algorithms#Simulated Annealing#Ant Colony Optimization#Black-box Optimization#Combinatorial 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):

SymbolMeaning
x\mathbf{x}one solution (decision variables), a DD-dimensional real vector; in discrete problems a permutation, a path, or a 0/1 string
xdx_dthe dd-th component of the solution, d=1,…,Dd=1,\dots,D
f(⋅)f(\cdot)objective function, black box: it can only be evaluated, never differentiated
X\mathcal{X}feasible solution set (search space), defined by bounds and constraints
NNpopulation size (number of particles in a particle swarm, individuals in a GA, ants in an ACO)
NFEN_{\mathrm{FE}}number of function evaluations, the unit in which budget is measured
vi\mathbf{v}_ivelocity of the ii-th particle
wwinertia weight, controlling how much of the previous velocity is retained
c1, c2c_1,\ c_2cognitive coefficient and social coefficient
r1, r2r_1,\ r_2random numbers drawn uniformly from [0,1][0,1] (redrawn for every update and every dimension)
pi\mathbf{p}_ihistorical best position of particle ii (personal best)
pg\mathbf{p}_ghistorical best position of the whole swarm (or neighborhood) (global best)
F(⋅)F(\cdot)fitness, the “larger is better” score obtained from ff by a scaling transform in a GA
pc, pmp_c,\ p_mcrossover probability and mutation probability
TTtemperature, controlling how permissive SA is in accepting worse solutions
T0, Tmin⁡T_0,\ T_{\min}initial temperature and final temperature
LLnumber of inner-loop iterations at one temperature (Markov chain length)
α\alphageometric cooling factor, T←αTT\leftarrow\alpha T
τij\tau_{ij}pheromone concentration on edge (i,j)(i,j)
ηij\eta_{ij}heuristic information on edge (i,j)(i,j), usually 1/dij1/d_{ij}
ατ, βτ\alpha_{\tau},\ \beta_{\tau}relative weights of pheromone and heuristic information (subscripted to avoid confusion with the cooling factor α\alpha)
ρ\rhoevaporation rate
QQpheromone deposition constant

Note: the original papers of the four algorithms each use different notation (PSO uses ϕ1,ϕ2\phi_1,\phi_2; GA uses ll for string length; ACO uses α,β\alpha,\beta 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:

IndexLocationContent of the derivation
Derivation 11.2Curse of dimensionality: why grid enumeration is infeasible in high dimensions
Derivation 21.4What the no-free-lunch theorem says and what it does not say
Derivation 32.2Three-term decomposition of the PSO velocity update and its second-order difference form
Derivation 42.3Convergence conditions of PSO and its stable parameter region
Derivation 52.4Why velocity clamping is equivalent to limiting the single-step exploration radius
Derivation 63.3Expected number of offspring under roulette-wheel selection and the schema theorem
Derivation 73.4Why crossover can recombine building blocks
Derivation 83.5Bounds on the mutation probability and schema survival
Derivation 94.2Detailed balance and the Boltzmann stationary distribution
Derivation 104.3Why the chain converges to the global optimum as temperature goes to zero
Derivation 114.4The trade-off between logarithmic cooling and geometric cooling
Derivation 125.2The form of the ACO transition probability and the meaning of its two exponents
Derivation 135.3Correspondence between pheromone update and reinforcement learning
Derivation 145.5Origin 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:

  1. The objective function is a black box. Given a x\mathbf{x}, you can only call a simulator or a cost function to obtain f(x)f(\mathbf{x}); you cannot obtain ∇f\nabla f, 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.
  2. 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.
  3. 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 RD\mathbb{R}^D 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.
  4. 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:

MethodInformation usedHard weakness
Gradient descent / Newton’s methodFirst- or second-order derivativesNot differentiable; only local convergence; sensitive to initialization
Grid search / enumerationEvaluations only at grid pointsCurse of dimensionality; accuracy limited by grid spacing
Convex optimization / linear programmingAnalytical structure, convexityModeling distortion when the problem is non-convex or non-analytical
Dynamic programmingOptimal substructureState-space explosion; requires an exact model
Branch and boundRelaxed lower boundsBounds 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 blockQuestion it answersPSOGASAACO
RepresentationWhat a solution looks likeDD-dimensional real vectorEncoded string (0/1, real, permutation)One solution (any representation)Path / construction sequence on a graph
GeneratorWhere new solutions come fromVelocity-driven displacementSelection + crossover + mutationNeighborhood perturbationStepwise construction by pheromone probability
EvaluationHow to scoreCall ffCall ff, then convert to FFCall ffCall ff (path length)
Selection / acceptanceWho staysUnconditionally kept (naturally replaced after the position update)Parents selected by fitness, elitism preservedAccepted with Metropolis probabilityOnly pheromone is kept, no individuals
MemoryWhere historical information livesPersonal best pi\mathbf{p}_i, global best pg\mathbf{p}_gThe whole populationOnly the current solution and the historical bestPheromone matrix τij\tau_{ij}

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 pg\mathbf{p}_g; 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 mm grid points and the dimension is DD; the total number of grid points is then mDm^D. If only m=10m=10 points are used per dimension:

Ngrid(D)=10DN_{\text{grid}}(D)=10^D

For D=2D=2 that is 100 evaluations, for D=6D=6 it is 10610^6, and for D=10D=10 it is 101010^{10}. If a single evaluation takes 1 millisecond, D=10D=10 requires about 116 days; a metaheuristic at D=10D=10 typically obtains a usable approximate solution with 10410^4 to 10510^5 evaluations.

More important is the product relationship between accuracy and dimension. If each dimension must reach an accuracy of ε\varepsilon and the interval length is LL, then the number of grid points per dimension is m=L/εm=L/\varepsilon, and the total number of evaluations is

Ngrid=(Lε)DN_{\text{grid}}=\left(\frac{L}{\varepsilon}\right)^D

To improve accuracy tenfold (ε→ε/10\varepsilon\to\varepsilon/10), the number of evaluations is multiplied by 10D10^D. 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 NFEN_{\mathrm{FE}}. 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:

  1. Population size and number of iterations are two ways of spending the same budget. NN individuals over KK generations cost NKN K evaluations. A large NN gives richer population information per generation but fewer generations and insufficient fine search; a small NN allows more generations but is prone to premature convergence. A common compromise is NN between 20D20D and 50D50D, leaving the rest of the budget to iterations.
  2. “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.
  3. 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 ff 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”:

AlgorithmKnobs favoring explorationKnobs favoring exploitationHow to tune
PSOLarge inertia weight ww, large velocity cap, sparse topologySmall ww, large c1,c2c_1,c_2, fully connected topologyCommon practice: decrease ww linearly from 0.9 to 0.4
GALarge mutation probability pmp_m, weak selection pressureLarge crossover probability pcp_c, large tournament size, more elitesAdaptive pmp_m (increase it when diversity is low)
SAHigh initial temperature T0T_0, slow cooling, long chain LLLow final temperature, fast coolingTemperature schedule curve
ACOLarge evaporation rate ρ\rho, small βτ\beta_{\tau}, low pheromone upper boundSmall ρ\rho, large ατ\alpha_{\tau}, high pheromone lower boundMMAS bounds and ρ\rho

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 X\mathcal{X} be finite, let the set of all possible objective functions f:X→Yf:\mathcal{X}\to\mathcal{Y} form the set F\mathcal{F}, and take a uniform distribution over F\mathcal{F}; then for any two algorithms A1,A2A_1,A_2, their average performance over all problems is the same:

1∣F∣∑f∈FP(A1 finds optimum of f within NFE evaluations)=1∣F∣∑f∈FP(A2 finds optimum of f within NFE evaluations)\frac{1}{|\mathcal{F}|}\sum_{f\in\mathcal{F}} P\left(A_1 \text{ finds optimum of } f \text{ within } N_{\mathrm{FE}} \text{ evaluations}\right) = \frac{1}{|\mathcal{F}|}\sum_{f\in\mathcal{F}} P\left(A_2 \text{ finds optimum of } f \text{ within } N_{\mathrm{FE}} \text{ evaluations}\right)

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 AA, one can construct an objective function that is “specifically adversarial to AA” (assign bad values along AA‘s visiting order and good values to points it never visits), making AA 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:

  1. 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”.
  2. 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.
  3. 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 eQ/Te^{Q/T}); 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):

AlgorithmOne-sentence intuitionBest suited toMost afraid of
PSOA swarm of particles flies toward “the best place I have seen” and “the best place the swarm has seen”Continuous, moderate dimension, fairly smooth objectiveHigh dimension, multimodal with widely separated peaks, discrete variables
GAGood individuals leave offspring, good fragments are combined by crossoverDiscrete/combinatorial, clear encoding, constraints expressible as penaltiesNeeding fine local search, extremely small evaluation budget
SATemporarily going downhill is allowed; as temperature drops it only takes good pathsCombinatorial optimization, clear neighborhood structure, single-path improvement acceptableHard neighborhood design, needing parallelism, extremely small budget
ACOEdges on good paths are more likely to be chosen by later antsPath/construction-type combinatorial problems on graphsContinuous 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 DD-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 NN particles, with particle ii at position xi∈RD\mathbf{x}_i\in\mathbb{R}^D and velocity vi∈RD\mathbf{v}_i\in\mathbb{R}^D. The update at iteration tt is

vi(t+1)=w vi(t)+c1r1(pi−xi(t))+c2r2(pg−xi(t))\mathbf{v}_i^{(t+1)} = w\,\mathbf{v}_i^{(t)} + c_1 r_1\left(\mathbf{p}_i-\mathbf{x}_i^{(t)}\right) + c_2 r_2\left(\mathbf{p}_g-\mathbf{x}_i^{(t)}\right) xi(t+1)=xi(t)+vi(t+1)\mathbf{x}_i^{(t+1)} = \mathbf{x}_i^{(t)} + \mathbf{v}_i^{(t+1)}

where r1,r2∼U(0,1)r_1,r_2\sim\mathcal{U}(0,1) 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

vid←vid+ϕ1r1(pid−xid)+ϕ2r2(pgd−xid)v_{id}\leftarrow v_{id}+\phi_1 r_1\left(p_{id}-x_{id}\right)+\phi_2 r_2\left(p_{gd}-x_{id}\right)

that is, without an inertia term; the inertia weight ww was introduced by Shi & Eberhart (1998) to control “how much of the previous velocity is retained”.

The three coefficients act as follows:

TermCoefficientPoints atIntuitionWhen too largeWhen too small
InertiawwPrevious velocityKeeps the direction of motion, crosses local regionsFlies everywhere, hard to convergeBrakes quickly, easily trapped in a local optimum
Cognitivec1c_1pi−xi\mathbf{p}_i-\mathbf{x}_i“Trust your own past experience”Everyone goes their own way, swarm information unusedOver-reliance on the swarm, loss of diversity
Socialc2c_2pg−xi\mathbf{p}_g-\mathbf{x}_i“Trust the swarm’s experience”The whole swarm collapses onto one point quickly, prematureSwarm 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.

vi(t+1)=wvi(t)⏟inertia+c1r1(pi−xi(t))⏟cognitive+c2r2(pg−xi(t))⏟social\mathbf{v}_i^{(t+1)} =\underbrace{w\mathbf{v}_i^{(t)}}_{\text{inertia}} +\underbrace{c_1 r_1\left(\mathbf{p}_i-\mathbf{x}_i^{(t)}\right)}_{\text{cognitive}} +\underbrace{c_2 r_2\left(\mathbf{p}_g-\mathbf{x}_i^{(t)}\right)}_{\text{social}}

The meaning of this step is: PSO’s “gradient” is not ∇f\nabla f but a composite direction built from two “position differences”. The position difference pi−xi\mathbf{p}_i-\mathbf{x}_i 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 vi(t)=xi(t)−xi(t−1)\mathbf{v}_i^{(t)}=\mathbf{x}_i^{(t)}-\mathbf{x}_i^{(t-1)} into the velocity update gives

xi(t+1)=xi(t)+w(xi(t)−xi(t−1))+c1r1(pi−xi(t))+c2r2(pg−xi(t))\mathbf{x}_i^{(t+1)} =\mathbf{x}_i^{(t)} +w\left(\mathbf{x}_i^{(t)}-\mathbf{x}_i^{(t-1)}\right) +c_1 r_1\left(\mathbf{p}_i-\mathbf{x}_i^{(t)}\right) +c_2 r_2\left(\mathbf{p}_g-\mathbf{x}_i^{(t)}\right)

Rearranged into the form “current position + displacement”:

xi(t+1)−xi(t)=w(xi(t)−xi(t−1))−(c1r1+c2r2)(xi(t)−pi ⋆)\mathbf{x}_i^{(t+1)}-\mathbf{x}_i^{(t)} =w\left(\mathbf{x}_i^{(t)}-\mathbf{x}_i^{(t-1)}\right) -\left(c_1 r_1+c_2 r_2\right)\left(\mathbf{x}_i^{(t)}-\mathbf{p}_i^{\,\star}\right)

where

pi ⋆=c1r1 pi+c2r2 pgc1r1+c2r2\mathbf{p}_i^{\,\star}=\frac{c_1 r_1\,\mathbf{p}_i+c_2 r_2\,\mathbf{p}_g}{c_1 r_1+c_2 r_2}

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. ww plays the role of the damping coefficient, and c1r1+c2r2c_1r_1+c_2r_2 plays the role of spring stiffness.

Step 3: expected recursion of the one-dimensional simplified model. Set pi=pg=pp_i=p_g=p (personal best and global best coincide, the most ideal case), take expectations using E[r1]=E[r2]=1/2\mathbb{E}[r_1]=\mathbb{E}[r_2]=1/2, and write c=(c1+c2)/2c=(c_1+c_2)/2; then

E[x(t+1)]=(1+w−c)E[x(t)]−w E[x(t−1)]+c p\mathbb{E}\left[x^{(t+1)}\right] =\left(1+w-c\right)\mathbb{E}\left[x^{(t)}\right] -w\,\mathbb{E}\left[x^{(t-1)}\right] +c\,p

This is a constant-coefficient linear recursion whose behavior is entirely determined by the characteristic equation:

λ2−(1+w−c)λ+w=0\lambda^2-\left(1+w-c\right)\lambda+w=0

Step 4: read off the engineering meaning. When cc is small, the characteristic roots are real and the particle approaches pp monotonically or with monotone oscillation — slow but stable convergence; when cc grows until the discriminant (1+w−c)2−4w<0(1+w-c)^2-4w<0, the roots become a pair of complex conjugates and the particle spirals around pp with decaying radius — which is exactly the typical PSO trajectory: large oscillation while exploring, then a spiral contraction onto the attractor. So larger cc is not better: if cc is too large the root modulus approaches 1 and the spiral decays extremely slowly or even diverges; if cc 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:

λ2−(1+w−c)λ+w=0\lambda^2-(1+w-c)\lambda+w=0

the quadratic formula gives

λ1,2=(1+w−c)±(1+w−c)2−4w2\lambda_{1,2}=\frac{(1+w-c)\pm\sqrt{(1+w-c)^2-4w}}{2}

The necessary and sufficient condition for the particle position sequence to converge to pp is that both characteristic roots have modulus strictly less than 1:

max⁡{∣λ1∣,∣λ2∣}<1\max\left\{|\lambda_1|,|\lambda_2|\right\}<1

Step 2: discuss two cases.

Case A: the discriminant is nonnegative, Δ=(1+w−c)2−4w≥0\Delta=(1+w-c)^2-4w\ge 0, and the two roots are real. Then we need

−1<λ1,2<1-1<\lambda_{1,2}<1

Substituting the expression for λ\lambda and rearranging, this is equivalent to

0≤c<2(1+w),∣w∣<10\le c<2(1+w),\qquad |w|<1

(from λ1λ2=w\lambda_1\lambda_2=w we get ∣w∣<1|w|<1; from λ1+λ2=1+w−c\lambda_1+\lambda_2=1+w-c and the roots lying in (−1,1)(-1,1) we get the upper bound on cc.)

Case B: the discriminant is negative, Δ<0\Delta<0, and the two roots are complex conjugates. Then the two roots have equal modulus, and by Vieta’s formulas

∣λ1∣2=∣λ2∣2=λ1λ2=w|\lambda_1|^2=|\lambda_2|^2=\lambda_1\lambda_2=w

so the convergence condition simplifies to

0<w<10<w<1

This is the most useful one: as long as w<1w<1 and the discriminant is negative (that is, (1+w−c)2<4w(1+w-c)^2<4w), the particle certainly converges in a spiral with rate w\sqrt{w}. The closer ww is to 1, the slower the decay (the longer the exploration); the closer ww 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

0≤w<1,0<c1+c2<4(1+w)0\le w<1,\qquad 0<c_1+c_2<4(1+w)

(strictly speaking, the bound on cc should be converted using c=(c1+c2)/2c=(c_1+c_2)/2; in practice c1+c2<4(1+w)c_1+c_2<4(1+w) 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 φ=c1+c2\varphi=c_1+c_2 and take

χ=2∣2−φ−φ2−4φ∣\chi=\frac{2}{\left|2-\varphi-\sqrt{\varphi^2-4\varphi}\right|}

For φ=4.1\varphi=4.1, χ≈0.7298\chi\approx0.7298. The update is written as

vi←χ[vi+c1r1(pi−xi)+c2r2(pg−xi)]\mathbf{v}_i\leftarrow\chi\left[\mathbf{v}_i+c_1r_1\left(\mathbf{p}_i-\mathbf{x}_i\right)+c_2r_2\left(\mathbf{p}_g-\mathbf{x}_i\right)\right]

Taking c1=c2=χ⋅2.05≈1.49618c_1=c_2=\chi\cdot 2.05\approx1.49618 is equivalent to w=χw=\chi and c1+c2≈2.992c_1+c_2\approx2.992. 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 pi=pg=pp_i=p_g=p. In a real run pg\mathbf{p}_g is constantly refreshed by other particles, and the random terms add variance; if one update happens to draw r1,r2r_1,r_2 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:

  1. Velocity clamping. Set an upper bound vdmax⁡v_d^{\max} for each dimension and, after the update, apply
vid←clip⁡(vid, −vdmax⁡, vdmax⁡)v_{id}\leftarrow \operatorname{clip}\left(v_{id},\ -v_d^{\max},\ v_d^{\max}\right)

A common choice is vdmax⁡=κ(xdmax⁡−xdmin⁡)v_d^{\max}=\kappa\left(x_d^{\max}-x_d^{\min}\right) with κ∈[0.1,0.5]\kappa\in[0.1,0.5].

  1. 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.

  2. Topology. Taking pg\mathbf{p}_g 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.

  3. When to update pi\mathbf{p}_i and pg\mathbf{p}_g. 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 pg\mathbf{p}_g “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 x(t+1)=x(t)+v(t+1)\mathbf{x}^{(t+1)}=\mathbf{x}^{(t)}+\mathbf{v}^{(t+1)}, the single-step displacement is simply v(t+1)\mathbf{v}^{(t+1)}. If every dimension is clamped to vdmax⁡v_d^{\max}, then

∥x(t+1)−x(t)∥2=∥v(t+1)∥2≤∑d=1D(vdmax⁡)2\left\|\mathbf{x}^{(t+1)}-\mathbf{x}^{(t)}\right\|_2 =\left\|\mathbf{v}^{(t+1)}\right\|_2 \le\sqrt{\sum_{d=1}^{D}\left(v_d^{\max}\right)^2}

Taking vdmax⁡=κ(xdmax⁡−xdmin⁡)v_d^{\max}=\kappa\left(x_d^{\max}-x_d^{\min}\right) and writing LdL_d for the domain length of dimension dd gives

∥Δx∥2≤κ∑d=1DLd2=κ∥L∥2\left\|\Delta\mathbf{x}\right\|_2\le\kappa\sqrt{\sum_{d=1}^{D}L_d^2} =\kappa\left\|\mathbf{L}\right\|_2

Step 2: interpret this bound. The inequality says that a single step can cross at most ”κ\kappa times the diagonal length of the whole search box”. If κ\kappa 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 κ\kappa 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 ww linearly from 0.9 to 0.4: in the early phase ww and κ\kappa 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 NN intervals and takes exactly one point in each), which covers the space better than pure random sampling, with a visible difference especially when DD is large and NN 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 pi\mathbf{p}_i 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 vmax⁡v^{\max}.

Block 2 ③: random numbers must be redrawn per dimension. This is the number-one pitfall in PSO implementations. If only two scalars r1,r2r_1,r_2 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 (x(t+1)=x(t)+v(t+1)\mathbf{x}^{(t+1)}=\mathbf{x}^{(t)}+\mathbf{v}^{(t+1)}), 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 10−810^{-8} 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 NFEN_{\mathrm{FE}} cap plus “swarm position variance below a threshold and gbest_f not improving for KK 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 ii” and leave everything else unchanged. The ring topology (each particle connected only to kk 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:

QuantityWhen readWhen writtenKept across generationsConsequence of writing it wrong
xi\mathbf{x}_iEvery stepEvery step (after the position update)Kept (overwritten)Forgetting the update leaves the particle motionless
vi\mathbf{v}_iEvery stepEvery step (after the velocity update)Must be keptZeroing it every step degenerates to greedy hill-climbing and loses inertial exploration
pi\mathbf{p}_iEvery stepOnly when f(xi)<pf,if(\mathbf{x}_i)<p_{f,i}Must be keptOverwriting it every step turns “personal best” into “current position” and the cognitive term is always zero
pf,ip_{f,i}When comparingTogether with pi\mathbf{p}_iMust be keptUpdating the position without the value corrupts the comparison
pg\mathbf{p}_gEvery stepUniformly at the end of each roundMust be keptRefreshing inside the particle loop desynchronizes the same generation
wwEvery stepEvery generation (if scheduled)Kept (decreasing)Increasing it instead makes late exploration too strong and prevents convergence
CacheBefore every evaluationAfter every new evaluationKeptExact floating-point equality makes almost every lookup miss

Three decision rules, exactly isomorphic to the “ask whether it should change” of the detach checklist:

  1. “Historical best” is a read-only reference, not a variable being optimized. pi\mathbf{p}_i and pg\mathbf{p}_g 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.
  2. “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, ww has nothing to act on.
  3. “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

SymptomPossible causeFix
Particles quickly stick to the boundary and gbest stops improvingww or c1+c2c_1+c_2 lies outside the stable region, trajectory divergesUse w=0.7298, c1=c2=1.49618w=0.7298,\ c_1=c_2=1.49618; or decrease ww linearly to 0.4
The whole swarm collapses onto one point early (premature)Global topology + too large c2c_2 + population too smallSwitch to lbest ring topology; increase NN; reduce c2c_2
Some dimensions never moveOnly two scalars drawn per generation instead of per dimensionDraw one pair r1,r2r_1,r_2 for every dimension
Convergence curve is sawtoothed and worsens latepg\mathbf{p}_g 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 runsPopulation too small, budget too small, no random-seed managementN≥20DN\ge 20D; fix the seed for comparison experiments; take statistics over several independent runs
Almost no convergence at high dimension (D>50D>50)PSO’s dimensional scalability is limitedReduce dimension / group variables; switch to CMA-ES (covariance matrix adaptation evolution strategy); or change the problem decomposition
Duplicate evaluations eat the budgetNo cache, particles repeatedly evaluating the same position after settling on the attractorAdd a tolerance-based cache; or skip the evaluation when “position change below a threshold”
Objective magnitudes differ greatly and some dimensions dominateVariables not normalizedScale each dimension to [0,1][0,1] 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 DD 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 (DD between 2 and 30 is best), objective functions that are fairly smooth but not differentiable, evaluation budgets between 10310^3 and 10510^5, 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 (DD 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

EncodingRepresentationApplicable toKey point
Binary encodingEach variable is represented by bb bits, string length l=∑bdl=\sum b_dDiscrete choices, switches, coarse-grained continuousAccuracy Δd=(xdmax⁡−xdmin⁡)/(2bd−1)\Delta_d=(x_d^{\max}-x_d^{\min})/(2^{b_d}-1); Gray code reduces the “adjacent integers are far apart” problem
Real-valued encodingThe string is simply a real vector; crossover/mutation act directly on realsContinuous variables, constrained optimizationRequires dedicated real-valued operators (SBX, polynomial mutation)
Permutation encodingThe string is a permutation of 1..n1..nTSP, scheduling, orderingOrdinary crossover produces duplicated/missing elements; order-preserving crossovers such as OX and PMX are required
Integer/mixed encodingEach gene takes a finite integer value, possibly mixed with realsResource allocation, parameter combinationsMutation 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:

F(x)=11+f(x)orF(x)=fmax⁡−f(x)F(\mathbf{x})=\frac{1}{1+f(\mathbf{x})}\quad\text{or}\quad F(\mathbf{x})=f_{\max}-f(\mathbf{x})

The former suits cases with f≥0f\ge0 and no upper bound, the latter cases where ff has a known upper bound. More important is scaling:

  • Rank-based fitness: sort by ff and use the rank (or a linear function of the rank) as FF, which completely removes the monopoly caused by “one individual with extremely high fitness”.
  • Windowing: in each generation use F=fmax⁡(t)−fF=f_{\max}^{(t)}-f, where fmax⁡(t)f_{\max}^{(t)} 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 v(x)v(\mathbf{x}) to the objective,
F(x)=11+f(x)+λ∑jmax⁡(0,gj(x))F(\mathbf{x})=\frac{1}{1+f(\mathbf{x})+\lambda\sum_j\max\left(0,g_j(\mathbf{x})\right)}

where gjg_j is the jj-th inequality constraint. If λ\lambda 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 schemeProcedureSelection pressureCharacteristics
Roulette wheelSample with probability Fi/∑jFjF_i/\sum_j F_jMediumSimple to implement; high variance when fitness values differ greatly
TournamentDraw kk at random and take the bestControlled by kkMost common; k=2k=2 is mild, larger kk means stronger pressure
RankingAssign probabilities linearly by rankPrecisely controllableSuits unknown fitness scales
TruncationOnly the top τ\tau fraction reproducesStrongFast 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

CrossoverProcedureApplicable encodingCharacteristics
One-pointPick one cut point at random and exchange the fragments after itBinary, permutation (with repair)Small disruption, weak recombination
Two-pointPick two cut points and exchange the middle fragmentSame as aboveMore balanced than one-point
UniformEach bit comes from parent 1 or parent 2 with probability ppBinary, realLarge disruption, strong exploration
Simulated binary (SBX)Simulate binary crossover by distribution, producing two childrenRealThe standard operator for continuous GA; ηc\eta_c controls how close the children are to the parents
Order crossover (OX) / PMXKeep one block in order, fill the rest in orderPermutationGuarantees that the child is still a legal permutation

The one-dimensional form of SBX (Deb & Agrawal, 1995): for a pair of parents p1,p2p_1,p_2, draw u∼U(0,1)u\sim\mathcal{U}(0,1) and compute the spread factor

βq={(2u)1ηc+1,u≤0.5(12(1−u))1ηc+1,u>0.5\beta_q= \begin{cases} \left(2u\right)^{\frac{1}{\eta_c+1}}, & u\le 0.5\\[4pt] \left(\dfrac{1}{2(1-u)}\right)^{\frac{1}{\eta_c+1}}, & u>0.5 \end{cases}

The two children are

c1=12[(1+βq)p1+(1−βq)p2],c2=12[(1−βq)p1+(1+βq)p2]c_1=\frac{1}{2}\left[\left(1+\beta_q\right)p_1+\left(1-\beta_q\right)p_2\right],\qquad c_2=\frac{1}{2}\left[\left(1-\beta_q\right)p_1+\left(1+\beta_q\right)p_2\right]

The larger ηc\eta_c is, the closer βq\beta_q is to 1 and the closer the children are to the parents (strong exploitation); the smaller ηc\eta_c is, the more likely the children are far from the parents (strong exploration). A common choice is ηc∈[10,30]\eta_c\in[10,30].

3.2.5 Mutation: Insurance for Diversity

For binary encoding, mutation is bit flipping:

xi←1−xiwith probability pmx_i\leftarrow 1-x_i\quad\text{with probability } p_m

For real-valued encoding, polynomial mutation is common:

δk={(2u)1ηm+1−1,u<0.51−[2(1−u)]1ηm+1,u≥0.5\delta_k= \begin{cases} \left(2u\right)^{\frac{1}{\eta_m+1}}-1, & u<0.5\\[4pt] 1-\left[2(1-u)\right]^{\frac{1}{\eta_m+1}}, & u\ge 0.5 \end{cases} xk←xk+δk(xkU−xkL)x_k\leftarrow x_k+\delta_k\left(x_k^{U}-x_k^{L}\right)

The larger ηm\eta_m is, the smaller the perturbation (fine local search); the smaller it is, the larger the perturbation (jumping exploration). A common choice is ηm∈[20,100]\eta_m\in[20,100].

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 HH is a string template with wildcards; for example, with binary string length l=6l=6, H=1∗0∗∗1H=1*0**1 means “position 1 is 1, position 3 is 0, position 6 is 1, anything elsewhere”. Two quantities characterize its “structure”:

  • order o(H)o(H): the number of fixed positions, 3 in the example above;
  • defining length δ(H)\delta(H): the distance between the leftmost and rightmost fixed positions, 6−1=56-1=5 in the example above.

Step 2: compute the expected number of offspring under roulette-wheel selection. Let the population size at generation tt be NN, the fitness of individual ii be FiF_i, and its selection probability be

pi=Fi∑j=1NFj=FiNFˉ,Fˉ=1N∑jFjp_i=\frac{F_i}{\sum_{j=1}^{N}F_j}=\frac{F_i}{N\bar F},\qquad \bar F=\frac{1}{N}\sum_j F_j

The expected number of times a single individual is selected is Npi=Fi/FˉNp_i=F_i/\bar F. Summing over all individuals belonging to schema HH gives

E[m(H,t+1)]selection=∑i∈HFiFˉ=m(H,t)f(H,t)FˉE\left[m(H,t+1)\right]_{\text{selection}} =\sum_{i\in H}\frac{F_i}{\bar F} =m(H,t)\frac{f(H,t)}{\bar F}

where f(H,t)f(H,t) is the average fitness of the individuals in HH. This step is the entire source of “selection makes good schemas grow exponentially”: if f(H,t)>Fˉf(H,t)>\bar F, then m(H,t)m(H,t) is multiplied by a factor greater than 1 every generation, growing as (f(H)/Fˉ)k(f(H)/\bar F)^k after kk generations.

Step 3: subtract the destruction caused by crossover and mutation. Crossover can break a schema: the fixed positions of HH can only be split when the cut point falls inside the defining length. A one-point crossover has l−1l-1 possible cut positions, of which δ(H)\delta(H) fall inside δ(H)\delta(H), so the probability of not being destroyed is

1−pcδ(H)l−11-p_c\frac{\delta(H)}{l-1}

Mutation flips fixed positions: the probability that a single position is not flipped is 1−pm1-p_m, and the probability that all o(H)o(H) fixed positions survive is (1−pm)o(H)(1-p_m)^{o(H)}. For small pmp_m use the first-order approximation

(1−pm)o(H)≈1−o(H)pm(1-p_m)^{o(H)}\approx 1-o(H)p_m

Step 4: combine into the schema theorem. Multiply the selection gain by the two destruction factors (the destruction events are approximately independent), giving

E[m(H,t+1)] ≥ m(H,t) f(H,t)Fˉ[1−pcδ(H)l−1−o(H)pm]E\left[m(H,t+1)\right]\ \ge\ m(H,t)\,\frac{f(H,t)}{\bar F}\left[1-p_c\frac{\delta(H)}{l-1}-o(H)p_m\right]

Step 5: read off three things.

  1. 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.
  2. The crossover probability pcp_c and the mutation probability pmp_m form the “destruction budget”. If the combined term pcδ/(l−1)+o(H)pmp_c\delta/(l-1)+o(H)p_m approaches 1, no schema can survive and the GA degenerates into random search.
  3. 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:

  1. 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.
  2. 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.
  3. “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 AA and BB:

p1=[A | X],p2=[Y | B]p_1=\left[A\ \middle|\ X\right],\qquad p_2=\left[Y\ \middle|\ B\right]

where X,YX,Y are useless fragments, AA lies to the left of the cut point and BB to the right. If the cut point happens to fall on the boundary between AA and BB, the child

c=[A | B]c=\left[A\ \middle|\ B\right]

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 AA occupies aa positions, BB occupies bb positions and the string length is ll, only a few positions at the AA–BB junction are suitable cut points. Roughly, the probability that one-point crossover falls exactly “between the two building blocks” is about 1/(l−1)1/(l-1), so recombination events are rare and must accumulate over many generations.

Step 3: the two ways to fail. First, the cut point falls inside AA or BB and splits the building block itself (the probability is governed by the defining length); second, AA and BB 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 1/l1/l 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 ll and per-position mutation probability pmp_m, the number of mutations on one string follows a binomial distribution Binomial(l,pm)\mathrm{Binomial}(l,p_m) with expectation

E[#mutation]=l pm\mathbb{E}\left[\#\text{mutation}\right]=l\,p_m

Taking pm=1/lp_m=1/l 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 o(H)o(H) survives mutation with probability (1−pm)o(H)(1-p_m)^{o(H)}. With pm=1/lp_m=1/l and o(H)=1o(H)=1, the survival probability is 1−1/l1-1/l, close to 1; when pmp_m grows to 0.50.5, the survival probability drops to 2−o(H)2^{-o(H)}, and a schema of order 3 survives with probability only 1/81/8 — equivalent to blowing up all the structure accumulated in the previous generation.

Step 3: determine the bounds.

  • Lower bound: if pmp_m is too small (say 10−410^{-4}), an allele that has already been lost can hardly be reintroduced. With population size N=50N=50 and string length l=20l=20, the expected number of mutations per generation is only 50×20×10−4=0.150\times20\times10^{-4}=0.1, that is, one mutation event every ten generations, and the search stagnates too early.
  • Upper bound: if pmp_m is too large (say 0.50.5), GA degenerates into random search, the destruction term o(H)pmo(H)p_m 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), pmp_m should be small and ηm\eta_m large; for problems that “need to jump out of local optima repeatedly” (such as multimodal combinatorial optimization), pmp_m should be large, or adaptive mutation should be used (increase pmp_m when population diversity drops). There is no globally optimal pmp_m, only a pmp_m 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 N−EN-E. SBX produces two children per parent pair, so if the number of parents is N−EN-E and even, the number of children equals N−EN-E 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 EE elites installs a “never decreasing” lower bound on the algorithm. But EE cannot be too large: when EE approaches NN, the population fills with copies of the elites, diversity collapses and crossover stops working. A common choice is E=1E=1 to 44.

Block 2 ③: the tournament size kk is the direct knob for selection pressure. With k=2k=2, an individual’s selection probability is roughly linearly related to its rank and the pressure is mild; as kk grows, the probability that the best individual is selected rapidly approaches 1 and the pressure becomes strong. If the algorithm converges prematurely, first reduce kk to 2; if convergence is too slow, raise kk 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. ηc\eta_c controls the distance between children and parents: as ηc→∞\eta_c\to\infty, c1=c2c_1=c_2 approximately equal the parents, degenerating to copying; as ηc→0\eta_c\to0, 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 μ\mu, 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. N×Tmax⁡N\times T_{\max} is the total number of evaluations (plus initialization and elite copies). If the budget is fixed at NFEN_{\mathrm{FE}}, then Tmax⁡≈NFE/NT_{\max}\approx N_{\mathrm{FE}}/N. If NN is too small, genetic diversity per generation is insufficient (building blocks cannot be assembled); if NN is too large, there are too few generations (recombination has no time to happen). Empirically NN lies between 2020 and 100100, and the larger the combinatorial problem, the larger NN should be.

3.8 Per-Step Read/Write and State-Maintenance Checklist

QuantityWhen readWhen writtenKept across generationsConsequence of writing it wrong
PP (population)Every generationEnd of every generationMust be keptRe-randomizing every generation degenerates to random search
FiF_i (fitness)During selectionAfter every evaluationKeptRunning roulette wheel directly on untransformed objective values; negative values make probabilities illegal
best_x, best_fCompared every generationOnly when a better solution appearsMust be keptResetting every generation kills the “historical best” and the curve may decrease
EliteStart of every generationStart of every generationCopied across generationsElites must not be mutated; mutating them accidentally means there is no elitism at all
pc,pm,ηc,ηmp_c,p_m,\eta_c,\eta_mEvery generationConstant or adaptiveKeptIf adaptation goes the wrong way (lowering pmp_m when diversity is low), premature convergence is accelerated
Random-number streamEvery operator—Kept (reproducible)Without a fixed seed, experiments cannot be compared
CacheBefore evaluationAfter evaluationKept across generationsExact floating-point equality matching fails

Three decision rules:

  1. “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.
  2. “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.
  3. “Population size” must be conserved. The number of individuals entering the next generation must be exactly NN; 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

SymptomPossible causeFix
Fast improvement in the first generations, then long stagnationPopulation converged prematurely, crossover lost its recombination abilityIncrease NN; reduce tournament kk to 2; raise pmp_m; add niching/crowding distance
The best-value curve decreasesNo elitism, or elites rewritten by operatorsAdd elitism with E≥1E\ge1 and let elites skip crossover and mutation
Binary encoding performs poorly at adjacent integersHamming distance of ordinary binary code disagrees with numeric distanceSwitch to Gray code
Continuous problems converge to boundary valuesChildren produced by mutation/crossover go out of bounds and are simply truncated, piling up at the boundaryUse bounded SBX, reflective boundaries, or penalize boundary solutions
All individuals become identical after a few generationsSelection pressure too strong, NN too small, mutation rate too lowReduce kk, increase NN, raise pmp_m (or use adaptive mutation)
Many infeasible solutions on constrained problemsPenalty coefficient λ\lambda too small, or the initial population lies entirely outside the feasible regionRaise λ\lambda; use a feasibility-first comparison rule; project into the feasible region at initialization
Permutation encoding produces duplicate cities or missing tasksOne-point crossover used without repairUse order-preserving crossovers such as OX/PMX and validate legality after generating the children
Results differ enormously between runsRandomness + too small a budget + no independent repetitionsFix 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 D>50D>50.
  • 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 x\mathbf{x} with objective value f(x)f(\mathbf{x}), and let a neighborhood generator produce a candidate solution x′\mathbf{x}'; define the objective difference

Δf=f(x′)−f(x)\Delta f=f(\mathbf{x}')-f(\mathbf{x})

(this note minimizes ff, so Δf<0\Delta f<0 means an improvement). The Metropolis acceptance criterion is

P(accept x′)={1,Δf≤0exp⁡(−ΔfT),Δf>0P\left(\text{accept }\mathbf{x}'\right)= \begin{cases} 1, & \Delta f\le 0\\[4pt] \exp\left(-\dfrac{\Delta f}{T}\right), & \Delta f>0 \end{cases}

That is: an improvement is always accepted, a deterioration is accepted with the Boltzmann factor. The larger the temperature TT, the closer e−Δf/Te^{-\Delta f/T} is to 1 and the more easily a worse solution is accepted; as T→0T\to0, 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 TT, the inner loop of SA is a Markov chain whose state is the solution x\mathbf{x}, with transition probability

P(x→x′)=q(x,x′)a(x,x′)P\left(\mathbf{x}\to\mathbf{x}'\right)=q\left(\mathbf{x},\mathbf{x}'\right)a\left(\mathbf{x},\mathbf{x}'\right)

where q(x,x′)q(\mathbf{x},\mathbf{x}') is the probability that the neighborhood generator “proposes” x′\mathbf{x}' and a(x,x′)a(\mathbf{x},\mathbf{x}') is the Metropolis acceptance probability. Assume the proposal distribution is symmetric, that is, q(x,x′)=q(x′,x)q(\mathbf{x},\mathbf{x}')=q(\mathbf{x}',\mathbf{x}).

Step 2: verify detailed balance. We claim that the stationary distribution of the chain is the Boltzmann distribution

πT(x)=1Z(T)exp⁡(−f(x)T),Z(T)=∑yexp⁡(−f(y)T)\pi_T(\mathbf{x})=\frac{1}{Z(T)}\exp\left(-\frac{f(\mathbf{x})}{T}\right),\qquad Z(T)=\sum_{\mathbf{y}}\exp\left(-\frac{f(\mathbf{y})}{T}\right)

and we need to verify that for any two states x,x′\mathbf{x},\mathbf{x}':

πT(x) P(x→x′)=πT(x′) P(x′→x)\pi_T(\mathbf{x})\,P\left(\mathbf{x}\to\mathbf{x}'\right) = \pi_T(\mathbf{x}')\,P\left(\mathbf{x}'\to\mathbf{x}\right)

Consider two cases.

Case 1: f(x′)≤f(x)f(\mathbf{x}')\le f(\mathbf{x}). Then

P(x→x′)=q(x,x′)⋅1,P(x′→x)=q(x′,x)exp⁡(−f(x)−f(x′)T)P\left(\mathbf{x}\to\mathbf{x}'\right)=q\left(\mathbf{x},\mathbf{x}'\right)\cdot 1,\qquad P\left(\mathbf{x}'\to\mathbf{x}\right)=q\left(\mathbf{x}',\mathbf{x}\right)\exp\left(-\frac{f(\mathbf{x})-f(\mathbf{x}')}{T}\right)

The left-hand side is πT(x)q(x,x′)\pi_T(\mathbf{x})q(\mathbf{x},\mathbf{x}'); the right-hand side is

πT(x′)q(x′,x)exp⁡(−f(x)−f(x′)T)=q(x′,x)Zexp⁡(−f(x′)T−f(x)−f(x′)T)=q(x′,x)Zexp⁡(−f(x)T)\pi_T(\mathbf{x}')q\left(\mathbf{x}',\mathbf{x}\right)\exp\left(-\frac{f(\mathbf{x})-f(\mathbf{x}')}{T}\right) =\frac{q\left(\mathbf{x}',\mathbf{x}\right)}{Z}\exp\left(-\frac{f(\mathbf{x}')}{T}-\frac{f(\mathbf{x})-f(\mathbf{x}')}{T}\right) =\frac{q\left(\mathbf{x}',\mathbf{x}\right)}{Z}\exp\left(-\frac{f(\mathbf{x})}{T}\right)

By the symmetry of qq, the two sides are equal.

Case 2: f(x′)>f(x)f(\mathbf{x}')>f(\mathbf{x}). Then both directions carry an exponential factor, and the two sides are again equal by the symmetry of qq.

Step 3: derive stationarity from detailed balance. Detailed balance means

∑xπT(x)P(x→x′)=πT(x′)∑xP(x′→x)=πT(x′)\sum_{\mathbf{x}}\pi_T(\mathbf{x})P\left(\mathbf{x}\to\mathbf{x}'\right) =\pi_T(\mathbf{x}')\sum_{\mathbf{x}}P\left(\mathbf{x}'\to\mathbf{x}\right) =\pi_T(\mathbf{x}')

where the last step uses “transition probabilities sum to 1 over the target states”. This is exactly the definition of a stationary distribution πTP=πT\pi_T P=\pi_T, 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 e−f/Te^{-f/T}. 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 ff (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 f⋆f^{\star} and the second-best local optimum value be f2f_2, with f2>f⋆f_2>f^{\star} (assume for simplicity that the optimum is unique). Under the Boltzmann distribution, the ratio of the weights of the two states is

πT(x⋆)πT(x2)=exp⁡(−f⋆−f2T)=exp⁡(f2−f⋆T)\frac{\pi_T(\mathbf{x}^{\star})}{\pi_T(\mathbf{x}_2)} =\exp\left(-\frac{f^{\star}-f_2}{T}\right) =\exp\left(\frac{f_2-f^{\star}}{T}\right)

Step 2: take the limit. As T→0+T\to0^+, f2−f⋆>0f_2-f^{\star}>0 and the exponent tends to +∞+\infty, hence

πT(x⋆)πT(x2)→∞\frac{\pi_T(\mathbf{x}^{\star})}{\pi_T(\mathbf{x}_2)}\to\infty

That is, the weight of the optimal state tends to infinity relative to any suboptimal state; after normalization,

lim⁡T→0+πT(x)={1/∣X⋆∣,x∈X⋆0,otherwise\lim_{T\to0^+}\pi_T(\mathbf{x})= \begin{cases} 1/|\mathcal{X}^{\star}|, & \mathbf{x}\in\mathcal{X}^{\star}\\ 0, & \text{otherwise} \end{cases}

where X⋆\mathcal{X}^{\star} 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 T=0T=0 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 T→0T\to0 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 LL 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:

log cooling:  Tk=T0log⁡(1+k),geometric cooling:  Tk=T0 αk,linear cooling:  Tk=T0−k ΔT\text{log cooling: }\ T_k=\frac{T_0}{\log\left(1+k\right)},\qquad \text{geometric cooling: }\ T_k=T_0\,\alpha^k,\qquad \text{linear cooling: }\ T_k=T_0-k\,\Delta T

Step 2: convergence of logarithmic cooling. Hajek (1988) proved: if the temperature decreases as

Tk≥clog⁡(1+k)T_k\ge\frac{c}{\log\left(1+k\right)}

and cc 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 ∑ke−Δ/Tk\sum_k e^{-\Delta/T_k} 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 TkT_k down to Tmin⁡T_{\min} requires

k≈exp⁡(cTmin⁡)k\approx\exp\left(\frac{c}{T_{\min}}\right)

When c/Tmin⁡=30c/T_{\min}=30, k≈1013k\approx10^{13}, far beyond any engineering budget. It has a theoretical guarantee but no practical value.

Step 4: why geometric cooling became the default. Geometric cooling Tk=T0αkT_k=T_0\alpha^k multiplies by a fixed ratio every step, and the number of steps needed to reach Tmin⁡T_{\min} is

k=log⁡(Tmin⁡/T0)log⁡αk=\frac{\log\left(T_{\min}/T_0\right)}{\log\alpha}

With T0=100T_0=100, Tmin⁡=10−3T_{\min}=10^{-3} and α=0.95\alpha=0.95, k≈224k\approx 224; with α=0.99\alpha=0.99, k≈1115k\approx1115. 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 α\alpha is usually between 0.90.9 and 0.990.99: 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.

  1. Set the initial temperature T0T_0 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 0.80.8 as T0T_0. 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.
  2. Set the final temperature Tmin⁡T_{\min} by “almost nothing is accepted”. When the acceptance rate drops below 10−310^{-3}, the temperature is already low enough and further cooling is just idle spinning.
  3. Match the chain length LL to the neighborhood scale. If LL 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 LL is too large, the temperature cannot drop far enough. Common values are L=10DL=10D to 100D100D, or a fixed L=100L=100 to 10001000.

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 LL 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 LL is too short the chain does not mix and SA degrades into a reinforced greedy hill-climbing that “cools at every step”; if LL 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 exp⁡(−Δ/T)\exp(-\Delta/T) directly underflows to 0 when Δ/T\Delta/T is large (which is harmless in itself), but loses precision when Δ/T\Delta/T is small. The more robust form compares

log⁡u<−ΔT,u∼U(0,1)\log u < -\frac{\Delta}{T},\qquad u\sim\mathcal{U}(0,1)

The two are mathematically equivalent (take the logarithm of uu and then compare), but the latter avoids exponential overflow and makes it easy to decide “reject” directly when Δ\Delta 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”, x′=x+ϵ\mathbf{x}'=\mathbf{x}+\boldsymbol{\epsilon} with ϵ∼N(0,σ2I)\boldsymbol{\epsilon}\sim\mathcal{N}(0,\sigma^2 I); 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 σ\sigma should decrease with temperature: large jumps at high temperature (global exploration), small adjustments at low temperature (fine local search). Fixing σ\sigma 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

QuantityWhen readWhen writtenKept across temperaturesConsequence of writing it wrong
x (current solution)Every stepOn acceptanceMust be keptResetting it to best_x every step degenerates into greedy hill-climbing and loses the point of annealing
f_xEvery stepIn sync with xMust be keptChanging x without f_x misaligns every Δ\Delta computation
best_x, best_fCompared every stepOnly when betterMust be keptReplacing the historical best by the final solution makes the reported result worse
TEvery stepEnd of every temperatureDecreasingForgetting to cool means eternal random walking; cooling too fast degenerates into local search
LEvery temperatureConstant or adaptiveKeptWhen it does not match the dimension the chain never mixes
Neighborhood scale σ\sigmaEvery proposalDecreasing with temperatureKept (decreasing)A fixed scale gives too little exploration at high temperature and too little refinement at low temperature
accept_countEnd of every temperatureReset to zero at the start of every temperatureReset at every temperatureForgetting to reset makes the acceptance statistics accumulate across temperatures and triggers a false early termination
CacheBefore evaluationAfter evaluationKept across temperaturesExact 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

SymptomPossible causeFix
The result is almost identical to the initial solutionInitial temperature too low, α\alpha too small, frozen within a few stepsCalibrate T0T_0 by the initial acceptance rate (about 0.8); raise α\alpha above 0.95
Runs for a long time but the result is still poorChain length LL too short, no mixing at each temperature; wrong neighborhood scaleIncrease LL (10D10D to 100D100D); let σ\sigma decrease with temperature
Acceptance rate stays near 1 for a long time and then suddenly freezesCooling curve too flat (α\alpha too close to 1) or final temperature set too highShorten the temperature span; take α\alpha between 0.9 and 0.95
The final solution is worse than the best recorded midwayReturned the current solution x instead of best_xAlways maintain best_x/best_f separately
Many evaluations wasted on infeasible solutionsEvaluating before checking feasibility; the neighborhood generator ignores constraintsRepair/project first, then evaluate; reject illegal candidates outright for discrete problems
Results vary enormously between runsSingle chain, insufficient budget, random initial valueRun multiple chains in parallel (different initial values) and take the best; or take statistics over several runs
Almost no movement on high-dimensional continuous problemsNeighborhood perturbation is independent and identically distributed per dimension, so the “effective step” is too small relative to the search space in high dimensionsScale σ\sigma per dimension (e.g. σd∝Ld\sigma_d\propto L_d); switch to an adaptive neighborhood
Still improving after the temperature reaches Tmin⁡T_{\min}Final temperature too high, or L so large that each temperature takes too longLower Tmin⁡T_{\min} (acceptance rate 10−310^{-3}); derive LL 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:

  1. 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.
  2. Experience can be reused “per edge”. The experience of a good path is decomposed into “which edges are good” and written into τij\tau_{ij}, and later ants can use it from any position; by contrast, PSO’s pg\mathbf{p}_g 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 nn cities, the distance from city ii to city jj is dijd_{ij}, and the heuristic information is taken as

ηij=1dij\eta_{ij}=\frac{1}{d_{ij}}

that is, “the shorter the edge, the more it is worth taking”. The pheromone τij\tau_{ij} is what the algorithm itself learns about “how many good paths have used this edge in history”. If ant kk is currently at city ii and the set of unvisited cities is Nik\mathcal{N}_i^k, the probability of choosing the next city jj is

pijk=τijατ ηijβτ∑l∈Nikτilατ ηilβτ,j∈Nikp_{ij}^{k}= \frac{\tau_{ij}^{\alpha_{\tau}}\,\eta_{ij}^{\beta_{\tau}}} {\sum_{l\in\mathcal{N}_i^{k}}\tau_{il}^{\alpha_{\tau}}\,\eta_{il}^{\beta_{\tau}}}, \qquad j\in\mathcal{N}_i^{k}

where ατ\alpha_{\tau} is the pheromone exponent and βτ\beta_{\tau} is the heuristic exponent. The original papers denote these two exponents by α,β\alpha,\beta; this note adds subscripts to avoid confusion with the cooling factor α\alpha.

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:

log⁡pijk=ατlog⁡τij+βτlog⁡ηij−log⁡(∑l∈Nikτilατηilβτ)\log p_{ij}^{k} =\alpha_{\tau}\log\tau_{ij}+\beta_{\tau}\log\eta_{ij} -\log\left(\sum_{l\in\mathcal{N}_i^{k}}\tau_{il}^{\alpha_{\tau}}\eta_{il}^{\beta_{\tau}}\right)

The last term depends only on the current city ii 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 ατlog⁡τij+βτlog⁡ηij\alpha_{\tau}\log\tau_{ij}+\beta_{\tau}\log\eta_{ij}.

Step 2: explain the two extremes. Let βτ=0\beta_{\tau}=0:

pijk=τijατ∑lτilατp_{ij}^{k}=\frac{\tau_{ij}^{\alpha_{\tau}}}{\sum_{l}\tau_{il}^{\alpha_{\tau}}}

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 ατ=0\alpha_{\tau}=0:

pijk=ηijβτ∑lηilβτp_{ij}^{k}=\frac{\eta_{ij}^{\beta_{\tau}}}{\sum_{l}\eta_{il}^{\beta_{\tau}}}

Then the ant looks only at edge lengths, which is equivalent to “randomized greedy construction” (degenerating to deterministic nearest neighbor as βτ→∞\beta_{\tau}\to\infty). It has no learning ability at all — every round produces the same result and the pheromone is purely decorative.

Step 3: understand ατ\alpha_{\tau} as an “inverse temperature”. Suppose the values of τij\tau_{ij} are close to each other; expanding log⁡τij\log\tau_{ij} around its mean makes ατlog⁡τij\alpha_{\tau}\log\tau_{ij} equivalent to “amplifying the pheromone differences by a factor of ατ\alpha_{\tau}”. The larger ατ\alpha_{\tau} is, the more the probability concentrates on the edge with the highest pheromone (more greedy, more like low-temperature Boltzmann selection); the smaller ατ\alpha_{\tau} 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 π=(i1,i2,…,in)\pi=(i_1,i_2,\dots,i_n) is

P(π)=∏t=1n−1pitit+1kP(\pi)=\prod_{t=1}^{n-1}p_{i_t i_{t+1}}^{k}

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:

τij←(1−ρ)τij+∑k=1mΔτijk\tau_{ij}\leftarrow\left(1-\rho\right)\tau_{ij}+\sum_{k=1}^{m}\Delta\tau_{ij}^{k}

where ρ∈(0,1)\rho\in(0,1) is the evaporation rate, mm is the number of ants, and Δτijk\Delta\tau_{ij}^{k} is the pheromone deposited by ant kk on edge (i,j)(i,j). The most common deposition rule (the Ant-Cycle model) is

Δτijk={QLk,if ant k uses edge (i,j)0,otherwise\Delta\tau_{ij}^{k}= \begin{cases} \dfrac{Q}{L_k}, & \text{if ant } k \text{ uses edge } (i,j)\\ 0, & \text{otherwise} \end{cases}

LkL_k is the length of the tour constructed by ant kk and QQ 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 Qij≡τijQ_{ij}\equiv\tau_{ij} be regarded as “the value estimate of edge (i,j)(i,j)” and ρ\rho as the learning rate; then the update

τij←(1−ρ)τij+∑kΔτijk\tau_{ij}\leftarrow(1-\rho)\tau_{ij}+\sum_k\Delta\tau_{ij}^{k}

can be rearranged as

τij←τij+ρ(1ρ∑kΔτijk−τij)\tau_{ij}\leftarrow\tau_{ij}+\rho\left(\frac{1}{\rho}\sum_k\Delta\tau_{ij}^{k}-\tau_{ij}\right)

This has exactly the form “value ← value + learning rate × (target − value)”, where the target term is

G^ij=1ρ∑kΔτijk\widehat{G}_{ij}=\frac{1}{\rho}\sum_k\Delta\tau_{ij}^{k}

By the Ant-Cycle model, Δτijk=Q/Lk\Delta\tau_{ij}^{k}=Q/L_k (if the ant used the edge), so G^ij\widehat{G}_{ij} 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 ACOCounterpart in RLRemark
Current city ii + unvisited set Nik\mathcal{N}_i^kState ssThe state is determined jointly by “position + visited set”
Choosing the next city jjAction aaThe action space changes with the state (legal actions = unvisited cities)
pijkp_{ij}^{k}Policy π(a∣s)\pi(a\mid s)A softmax policy weighted by pheromone and heuristic information
Tour length LkL_kEpisode return GG (negated)The goal is to minimize LkL_k, equivalent to maximizing −Lk-L_k
τij\tau_{ij}State–action value Q(s,a)Q(s,a)The same table serves both as policy parameter and as value estimate
Evaporation ρ\rhoLearning rate / forgetting factorControls how fast old estimates are overwritten
Sum of deposits from several antsAverage of Monte Carlo returnsUses several episodes to reduce variance
MMAS boundsValue clippingPrevents the estimate from being blown up by extreme samples

Step 3: point out three key differences.

  1. 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.
  2. Policy and value are coupled. In Actor-Critic the policy network and the value network have two separate parameter sets; in ACO the pheromone τ\tau 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 ατ\alpha_{\tau}, which also changes how the value is used).
  3. No discount factor. Every segment of the tour length has the same weight and there is no γ\gamma. 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 τij=τ0\tau_{ij}=\tau_0 (a very small positive constant, such as 10−610^{-6}), letting the first round be dominated almost entirely by the heuristic; MMAS initializes to τmax⁡\tau_{\max}, making the first round favor exploration (because all edges are saturated and the only differences can come from η\eta).

The elitist strategy. Each round, an extra portion of pheromone is given to the edges of “the best tour so far”:

τij←τij+e⋅QLgb,(i,j)∈πgb\tau_{ij}\leftarrow\tau_{ij}+e\cdot\frac{Q}{L_{gb}},\qquad (i,j)\in\pi_{gb}

ee is the number of elites and LgbL_{gb} 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:

  1. 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.
  2. Pheromone is clamped to [τmin⁡,τmax⁡][\tau_{\min},\tau_{\max}], preventing an edge from being reinforced without bound or driven completely to zero.
  3. Pheromone is initialized to τmax⁡\tau_{\max} and reset to τmax⁡\tau_{\max} 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 Δ=1/Lgb\Delta=1/L_{gb} (taking Q=1Q=1); then the pheromone evolves as

τ(t+1)=(1−ρ)τ(t)+Δ\tau^{(t+1)}=(1-\rho)\tau^{(t)}+\Delta

This is a first-order linear recursion whose fixed point satisfies τ\*=Δ/ρ\tau^\*=\Delta/\rho, and which converges to it from any initial value at rate (1−ρ)t(1-\rho)^t:

τ(t)=τ\*+(τ(0)−τ\*)(1−ρ)t\tau^{(t)}=\tau^{\*}+\left(\tau^{(0)}-\tau^{\*}\right)(1-\rho)^{t}

Step 2: take the upper bound. Since Δ≤1/Lgb\Delta\le 1/L_{gb} (only the best tour can deposit, and the shorter the tour the larger the deposit), the steady-state upper bound is

τmax⁡=1ρ Lgb\tau_{\max}=\frac{1}{\rho\,L_{gb}}

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 n−1n-1 candidate edges at each step. If we require that “the probability of any edge being chosen at any step is not below pbestp_{\text{best}}”, then in the worst case (the other n−2n-2 edges all have pheromone τmax⁡\tau_{\max}) the pheromone of that edge must satisfy at least

τmin⁡αττmin⁡ατ+(n−2)τmax⁡ατ≥pbest\frac{\tau_{\min}^{\alpha_{\tau}}}{\tau_{\min}^{\alpha_{\tau}}+(n-2)\tau_{\max}^{\alpha_{\tau}}}\ge p_{\text{best}}

Taking ατ=1\alpha_{\tau}=1 and solving for τmin⁡\tau_{\min} gives

τmin⁡=τmax⁡(1−pbest)n−2+pbest\tau_{\min}=\frac{\tau_{\max}\left(1-p_{\text{best}}\right)}{n-2+p_{\text{best}}}

The standard form given by Stützle & Ho (for an nn-city TSP with pbest=0.05p_{\text{best}}=0.05) is

τmin⁡=τmax⁡(1−pbestn)(n2−1)pbestn\tau_{\min}= \frac{\tau_{\max}\left(1-\sqrt[n]{p_{\text{best}}}\right)} {\left(\dfrac{n}{2}-1\right)\sqrt[n]{p_{\text{best}}}}

It differs from the rough form above by a ⋅n\sqrt[n]{\cdot} factor, because “an edge must be chosen at least once during the whole nn-step construction” requires converting the single-step probability pbestp_{\text{best}} 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.

  1. Preventing monopoly: the upper bound stops one edge from attracting all ants.
  2. 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”.
  3. A reproducible tuning baseline: τmax⁡,τmin⁡\tau_{\max},\tau_{\min} are computed directly from ρ,Lgb,n\rho,L_{gb},n 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 ①: dij=0d_{ij}=0 must be handled. If two cities coincide (distance zero), ηij=1/0\eta_{ij}=1/0 overflows. In engineering the diagonal (i=ji=j) should be excluded from the candidates and a very small quantity ϵ\epsilon added to zero distances: ηij=1/(dij+ϵ)\eta_{ij}=1/(d_{ij}+\epsilon).

Block 1 ②: never initialize the pheromone to zero. If τij=0\tau_{ij}=0, all pijp_{ij} in the first round are zero (the denominator is zero) and ants cannot choose. AS uses a tiny constant and MMAS uses τmax⁡\tau_{\max} precisely to avoid this degeneracy.

Block 2 ③: the weights must be recomputed at every step. Because the candidate set Nik\mathcal{N}_i^k 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 O(n)O(n) to O(1)O(1). 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 ρ\rho, equivalent to shrinking the learning rate by a factor of ρ\rho, 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 mm ants deposit, equivalent to averaging mm 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 nn rounds), MMAS resets all pheromone to τmax⁡\tau_{\max}, 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

QuantityWhen readWhen writtenKept across roundsConsequence of writing it wrong
τij\tau_{ij} (pheromone table)Every sampleEvery round: evaporation + depositionMust be keptResetting every round degenerates into “several ants constructing independently and greedily”, with no learning
visited (visited set)Every sampleAdd a new city at every stepReset for every antForgetting to reset leaves the second ant with no legal move; forgetting to add causes repeated visits
tour (current tour)Every stepAppend at every stepReset for every antReusing it across ants makes the tour illegal
best_tour, best_lengthCompared every roundOnly when betterMust be keptOverwriting every round loses the historical best
ρ\rhoEvery roundConstant or adaptiveKeptForgetting to evaporate saturates the pheromone and all ants take the same tour
τmax⁡,τmin⁡\tau_{\max},\tau_{\min}Clamped every roundConstant (precomputed from ρ,Lgb,n\rho,L_{gb},n)KeptWrong bounds make clamping ineffective or flatten the table to identical values
Within-round tours/lengthsWhen depositing after evaporationCleared at the start of every roundReset every roundAccumulating across rounds double-counts the deposition

Three judgment rules:

  1. 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.
  2. best_tour must 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”.
  3. The pheromone table has dimension n×nn\times n (for a TSP), and one must explicitly ensure that the i=ji=j 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

SymptomPossible causeFix
All tours identical in the first roundInitial pheromone is zero or huge, making the probabilities degenerateAS uses τ0=10−6\tau_0=10^{-6}; MMAS uses τmax⁡\tau_{\max} and ensures η\eta is discriminative
After a few rounds all ants take the same tour (premature)ρ\rho too small, ατ\alpha_{\tau} too large, no boundsIncrease ρ\rho; reduce ατ\alpha_{\tau}; use the MMAS τmin⁡\tau_{\min} and restarts
Pheromone values overflow or all become 0No evaporation leading to unbounded accumulation; or ρ\rho too large driving everything to zeroEvaporate every round; clamp in MMAS; take ρ\rho between 0.1 and 0.5
The result is clearly worse than “greedy + 2-opt”No local search; βτ\beta_{\tau} too small so edge lengths are ignoredAdd 2-opt/3-opt; take βτ\beta_{\tau} between 2 and 5
The convergence curve is flat for a long time and then suddenly jumpsOnly the global best deposits and there is no restart, so the search stagnatesAlternate “iteration best” and “global best” deposition; add restarts
Results vary enormously between runsToo few ants, too few roundsTake mm between nn and 2n2n; add rounds; take statistics over several independent runs
Very poor results on non-TSP problemsThe 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 expectationsO(n)O(n) sampling per step, O(mn2)O(mn^2) updates per roundUse 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

DimensionPSOGASAACO
Search unitOne point (particle)One encoded string (individual)One solution (single point)One construction path (ant)
Population or single pointPopulationPopulationSingle point (several chains may run in parallel)Population (but individuals do not evolve)
Source of new solutionsVelocity-driven displacementSelection + crossover + mutationNeighborhood perturbationStepwise construction by probability
Form of memoryPositional (pi,pg\mathbf{p}_i,\mathbf{p}_g)Population-based (the whole string)Almost none (only the current solution)Edge-based (pheromone τij\tau_{ij})
Whether individuals are keptKept (overwritten)Kept (generational replacement)Not keptNot kept (only pheromone remains)
Accepting worse solutionsImplicit (velocity may point to a worse region)Implicit (mutation/crossover may produce worse children)Explicit (Metropolis)Implicit (probabilistic sampling)
Continuous variablesNative supportNeeds real-valued encoding + SBXNative supportNot supported
Discrete/combinatorialWeak (needs a dedicated variant)StrongStrong (needs neighborhood design)Strong (needs a graph structure)
ParallelismHigh (particles are independent)High (evaluations are independent)Low (a single chain is serial)High (ants construct independently)
Main parametersw,c1,c2,vmax⁡,Nw,c_1,c_2,v^{\max},NN,pc,pm,ηc,ηm,kN,p_c,p_m,\eta_c,\eta_m,kT0,Tmin⁡,α,L,σT_0,T_{\min},\alpha,L,\sigmam,ατ,βτ,ρm,\alpha_{\tau},\beta_{\tau},\rho
Theoretical guaranteeStable parameter region (conditional)Schema theorem (a lower bound, not a convergence guarantee)Probability-1 convergence under logarithmic coolingConvergence under specific conditions (MMAS is bounded)
Typical failureShared direction fails in high dimensions; premature convergencePremature convergence; building blocks destroyedFreezing; large variance of a single chainPheromone lock-in; failure on non-additive objectives
Best suited toContinuous, moderate dimension, smooth multimodalDiscrete/combinatorial, fragments can be recombinedCombinatorial, clear neighborhood, single-path improvementConstruction-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 pg\mathbf{p}_g 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 pg\mathbf{p}_g 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 ”pi=pg\mathbf{p}_i=\mathbf{p}_g 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 τmin⁡>0\tau_{\min}>0), 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:

  1. Is the objective differentiable? Is the problem unimodal? Yes → use gradient, Newton, or quasi-Newton methods; do not use metaheuristics. No → continue.
  2. 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.
  3. Continuous case: how large is the dimension, how large is the budget?
    • D≤30D\le30, budget 10310^3 to 10510^5 → PSO (fastest to implement, fewest parameters).
    • D>30D>30, 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”.
  4. 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.
  5. Can the “good fragments” of the solution be defined and recombined independently?
    • Yes → GA (crossover recombination is its core advantage).
    • No → step 6.
  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 combinationWhy it is wrongCorrect 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 meaningUse ACO (constructive) or GA (OX/PMX crossover)
GA for high-dimensional continuous fine tuning (D>50D>50)Binary/real encoding suffers severe crossover disruption in high dimensions and converges far more slowly than covariance-adaptive methodsUse CMA-ES, or PSO + local search
SA for large-scale parallel optimizationA 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 signalUse 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

AlgorithmRemember it in three lines
PSOEvery particle remembers “my own best” and “the swarm’s best”; velocity = inertia + cognitive + social; parameters converge only inside 0≤w<1, 0<c1+c2<4(1+w)0\le w<1,\ 0<c_1+c_2<4(1+w).
GASelection 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.
SAImprovements are always accepted, deteriorations are accepted with probability e−Δf/Te^{-\Delta f/T}; as the temperature falls from high to low, the stationary distribution of the chain contracts from “uniform” to “global optimum”.
ACOAn 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 RLPSOGASAACO
State ssCurrent particle position xi\mathbf{x}_iOne individual (encoded string)Current solution x\mathbf{x}Current city + unvisited set
Action aaDisplacement after the velocity updateSelection/crossover/mutation operatorNeighborhood perturbation Δx\Delta\mathbf{x}Choosing the next edge (i,j)(i,j)
Policy π(a∣s)\pi(a\mid s)Velocity update rule (including random terms)Operator probabilities (pc,pmp_c,p_m)Metropolis acceptance probabilityTransition probability pijkp_{ij}^k
Reward rr−Δf-\Delta f (objective improvement)F(x)F(\mathbf{x})−Δf-\Delta f−Lk-L_k (tour length negated)
Value V/QV/Qpi,pg\mathbf{p}_i,\mathbf{p}_g (historical best positions)Population (carrier of good genes)No explicit valuePheromone τij\tau_{ij}
Exploration temperatureLarge ww, large vmax⁡v^{\max}Large pmp_m, small kkHigh TTSmall ατ\alpha_{\tau}, large ρ\rho
EpisodeOne iterationOne generationThe chain at one temperatureThe complete construction of one ant
Monte Carlo vs bootstrappingUses the true ff value (no bootstrapping)Uses the true ff valueUses the true Δf\Delta fUses the true tour length (no bootstrapping)
Experience replayNone (the historical best is the compressed experience)The population is the experience poolNoneThe pheromone table is the compressed experience
Target network / freezingNoneElite preservationNoneThe τmin⁡\tau_{\min} floor
Entropy regularizationRandom terms r1,r2r_1,r_2MutationHigh temperatureEvaporation + lower bound

From this three “cross-domain” insights can be extracted:

  1. “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.
  2. “Exploration strength” must decay over time, otherwise the algorithm does not converge. Reinforcement learning uses ϵ\epsilon decay, entropy-coefficient decay, and temperature decay; metaheuristics use ww decay, adaptive pmp_m, TT cooling, and adjustment of ρ\rho and ατ\alpha_{\tau}. “Explore first, exploit later” is a cross-domain discipline, not a trick of any single algorithm.
  3. “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

  1. 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.)
  2. 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.)
  3. 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.)
  4. 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

  1. 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.)
  2. Shi, Y., & Eberhart, R. (1998). A modified particle swarm optimizer. IEEE International Conference on Evolutionary Computation, 69–73. (Introduces the inertia weight ww; the source of the linear-decrease strategy.)
  3. 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 χ\chi and the rigorous analysis of the convergence region; the basis of Derivation 4 in this note.)
  4. 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

  1. 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.)
  2. 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 ηc\eta_c.)
  3. 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.)
  4. 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

  1. 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.)
  2. 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.)
  3. Č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.)
  4. 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

  1. 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.)
  2. 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.)
  3. 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 τmax⁡,τmin⁡\tau_{\max},\tau_{\min} and the restart mechanism, the basis of Derivation 14 in this note.)
  4. 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

  1. 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.)
  2. 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.)
  3. 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

AbbreviationFull nameExplanation
ACOAnt Colony OptimizationA population search method in which pheromone guides ants to construct paths step by step
ASAnt SystemThe most original ACO version, in which all ants deposit pheromone
ACSAnt Colony SystemAn improved ACO version with local pheromone updates and a pseudo-random proportional rule
CMA-ESCovariance Matrix Adaptation Evolution StrategyA high-dimensional continuous black-box method that learns correlations between variables
ESEvolution StrategiesA family of black-box optimization methods that use population perturbation and selection
FEFunction EvaluationAn objective function evaluation (count), the unit for measuring the search budget
GAGenetic AlgorithmA search method over an encoding space using selection, crossover and mutation
LHSLatin Hypercube SamplingA stratified sampling method that stratifies each dimension and then combines the samples
MCMCMarkov Chain Monte CarloA general framework for sampling a target distribution with a Markov chain
MMASMAX-MIN Ant SystemAn ACO variant that bounds the pheromone and lets only the best ant update it
NFLNo Free LunchThe no-free-lunch theorem, stating that no algorithm is optimal for all problems
OXOrder CrossoverAn order-preserving crossover operator designed for permutation encoding
PMXPartially Mapped CrossoverA crossover operator designed for permutation encoding
PSOParticle Swarm OptimizationA population search method in which velocity and personal/global bests guide the particles
RLReinforcement LearningA method in which an agent interacts with an environment and improves decisions from rewards
SASimulated AnnealingA single-point search method that uses a decreasing temperature to control acceptance of worse solutions
SBXSimulated Binary CrossoverA crossover operator for real-coded GA that mimics the behavior of binary crossover
TDTemporal DifferenceA method that updates values from “immediate reward + value estimate of the next state”
TSPTravelling Salesman ProblemThe problem of finding the shortest closed tour that visits every city exactly once
VRPVehicle Routing ProblemThe 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, ϕ1,ϕ2\phi_1,\phi_2 in the original PSO paper are written as c1,c2c_1,c_2, and α,β\alpha,\beta in the original ACO papers are written as ατ,βτ\alpha_{\tau},\beta_{\tau}), 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…

    ← Back to home