Local search and metaheuristics
When only the final state matters, move through a landscape of candidate solutions. Study hill climbing with restarts, simulated annealing and its Metropolis foundation, tabu search, local beam and genetic algorithms, alongside honest comparison of stochastic methods.
After this lesson you can
- Model combinatorial optimization problems with suitable neighborhoods and objective functions.
- Implement hill climbing with restarts, simulated annealing and tabu search with incremental move evaluation.
- Prove fixed-temperature annealing has the Boltzmann stationary distribution.
- Design honest comparisons of stochastic metaheuristics with multiple seeds and equal budgets.
- Explain when genetic algorithms help over local search.
Before you start
When only the final state matters
The searches in previous lessons construct a path: a sequence of actions from an initial state to a goal, with cost given by the path. In many problems nobody cares about the path. The aim is a good configuration:
- Eight queens. Place eight queens on a board so none attacks another. The final board matters, not the order of placement.
- Traveling salesperson. A closed tour visiting every city once, as short as possible. With cities there are distinct tours; for , on the order of .
- Timetabling. Assign classes to rooms and time slots without teacher, group or room overlaps (hard constraints), with few idle hours and preferences respected (soft constraints).
- Circuit placement. Place thousands of cells on a chip to minimize total wiring length without overlap. This is the problem with which Kirkpatrick, Gelatt and Vecchi introduced simulated annealing in 1983.
In the state-space formulation, these problems can be posed by adding pieces one at a time, but the resulting tree is astronomical and most nodes cannot be evaluated until the end. The alternative is a complete-state formulation: each state is already an entire candidate solution (eight queens placed, a complete tour, a timetable with every class), and search gradually modifies it to improve it. This is local search territory: constant memory, no tree, and the ability to work with spaces of states because they are never enumerated. In return it gives up the completeness and optimality of BFS or A*: it offers good solutions quickly, and the interesting question becomes how good and with what probability.
Landscapes: neighborhoods, local minima, plateaus and ridges
For maximization one speaks of an objective and maxima; changing the sign makes it the same problem, so “hill climbing” and “descent” name the same algorithm. The discrete definition is analogous to continuous optimization’s local and global minima, with a fundamental difference: there, “near” comes from the topology of and minima are recognized by the gradient and critical-point classification; here you choose what “near” means by choosing , and there are no derivatives. The same state may be a local minimum under one neighborhood and not another. If for every , every local minimum is global, but each step costs as much as brute-force solution. Designing the neighborhood trades between small, cheap neighborhoods with many local minima and large, costly ones with few.
Two neighborhoods for the traveling salesperson
Represent a tour as a permutation of cities, with closing edge .
- Swap. Exchange two cities’ positions. It removes up to four edges and adds four; there are neighbors.
- 2-opt. Choose two nonadjacent edges, and with , remove them and reconnect as and . To retain a cycle, the intermediate segment must be traversed backward, so the move reverses . Excluding pairs of adjacent edges (which change nothing), there are neighbors: for .
The value of 2-opt is the cost of evaluating a neighbor. If is the distance matrix, the length change depends only on the four edges removed and added:
four table lookups, , versus to recompute the entire length. This incremental evaluation is the difference between annealing millions of moves per second and thousands, as the lab measures. A subtlety: evaluation is , but applying the move to a tour stored as an array costs because the segment must be reversed (the complementary segment can be reversed if shorter, yielding the same cycle). Since most evaluated moves are rejected, evaluation dominates; high-performance implementations also use structures such as Fredman, Johnson, McGeoch and Ostheimer’s (1995) two-level doubly linked lists, with reversals in .
2-opt also has a clean geometric property.
Proof
Let and be the edges, traversed in order , and let be the intersection of segments and . 2-opt adds and . By the triangle inequality, and , and summing,
because is on both segments. Equality would require and to be collinear, and with interior to this would align , and , which we excluded. Therefore .
∎The converse is false: a crossing-free tour may be far from optimal and still be a 2-opt local minimum. That is why this lesson’s metaheuristics are needed.
Landscape geography
Three landscape features explain almost every local-search failure:
- Local minima. No neighbor is better. In eight queens with the “move one queen within its column” neighborhood (56 neighbors), some boards have a single conflicting pair but no move removes the conflict: the cell below ends at one in 1007 of 2000 attempts.
- Plateaus. Connected regions of states with equal energy. If the objective counts things (conflicts, violated clauses), plateaus are huge: moving a queen often leaves conflict count unchanged. A search accepting only strict improvements stops at the first plateau even if it has a downhill exit.
- Ridges. Sequences of local minima where advancing requires combining two elementary moves: each separately worsens, together they improve. This is the discrete analogue of a narrow diagonal valley in which coordinate descent zigzags.
The next figure is the laboratory for the entire lesson. A one-dimensional landscape of states with many local minima, whose overall shape you control with handles, and two populations of particles moving with the same symmetric neighborhood (jumping to , or with equal probability): orange accepts only downhill moves, blue follows the Metropolis criterion defined below.
Hill climbing and its variants
The neighbor-selection rule gives variants:
- Steepest descent: evaluate all of and choose the best, breaking ties randomly. Each step costs evaluations.
- First improvement: traverse in random order and accept the first improving neighbor. Steps are cheaper and almost always more numerous; when the neighborhood is large (millions of neighbors), this is the only reasonable option.
- Stochastic: choose randomly among improving neighbors, with probability that may grow with improvement.
- Sideways moves: also accept neighbors with , limiting consecutive sideways moves to avoid wandering forever on a plateau.
- Random restarts: when stopped at a local minimum that is not a solution, start over from an independent random state.
Measurement beats opinion. This cell runs steepest hill climbing on eight queens (one queen per column, states, 56 neighbors) from random boards, without and with up to 100 consecutive sideways moves. Energy is the number of attacking queen pairs. Notice incremental evaluation: with queen counts per row and diagonal, the change in when moving a queen is calculated in .
import random
from collections import Counter
def hill_climbing(n, rng, max_laterales=0):
"""Mayor pendiente en n reinas (s[c] = fila de la reina de la columna c), con evaluación incremental."""
s = [rng.randrange(n) for _ in range(n)]
fil, d1, d2 = [0] * n, [0] * (2 * n), [0] * (2 * n) # reinas por fila y por diagonal
for c, f in enumerate(s):
fil[f] += 1; d1[f - c + n] += 1; d2[f + c] += 1
h = sum(k * (k - 1) // 2 for k in fil + d1 + d2) # pares que se atacan
pasos = laterales = 0
while h > 0:
mejor, cands = None, []
for c in range(n):
a = s[c]
quita = fil[a] + d1[a - c + n] + d2[a + c] - 3 # conflictos que desaparecen al levantar la reina
for f in range(n):
if f != a:
d = fil[f] + d1[f - c + n] + d2[f + c] - quita # cambio de h en O(1)
if mejor is None or d < mejor:
mejor, cands = d, [(c, f)]
elif d == mejor:
cands.append((c, f))
if mejor < 0 or (mejor == 0 and laterales < max_laterales):
laterales = laterales + 1 if mejor == 0 else 0
c, f = rng.choice(cands)
a = s[c]
fil[a] -= 1; d1[a - c + n] -= 1; d2[a + c] -= 1
fil[f] += 1; d1[f - c + n] += 1; d2[f + c] += 1
s[c], h, pasos = f, h + mejor, pasos + 1
else:
break
return h, pasos
rng = random.Random(0)
for max_lat, intentos in [(0, 2000), (100, 1000)]:
res = [hill_climbing(8, rng, max_lat) for _ in range(intentos)]
exitos = [p for h, p in res if h == 0]
fallos = [p for h, p in res if h > 0]
p = len(exitos) / intentos
m_e = sum(exitos) / len(exitos)
m_f = sum(fallos) / len(fallos) if fallos else 0.0
print(f"laterales <= {max_lat:3d}: {intentos} intentos, p = {p:.3f} ± {1.96 * (p * (1 - p) / intentos) ** 0.5:.3f}")
print(f" pasos medios: éxito {m_e:.1f}, fracaso {m_f:.1f}")
print(f" conflictos finales: {dict(sorted(Counter(h for h, _ in res).items()))}")
print(f" intentos esperados 1/p = {1 / p:.2f} pasos esperados hasta resolver = {m_e + (1 - p) / p * m_f:.1f}")The result reproduces Russell and Norvig’s classic figures for the same experiment: without sideways moves, hill climbing solves the problem in of attempts (the book gives 14%), after about 4 steps on success and 3 on failure. Most failures leave one or two conflicting pairs: nearly perfect local minima. Allowing up to 100 sideways moves raises the rate to , at the price of much longer attempts: 19 steps on average when successful and 55 when unsuccessful.
The arithmetic of restarts
If attempts are independent and each succeeds with probability , the number of attempts until the first success follows a geometric distribution, that of repeated Bernoulli trials:
With , attempts are needed on average, and after restarts the probability of all failures decreases exponentially. For total step cost more is needed, because failed attempts and the successful one have different lengths.
Proof
The first attempts fail and the last succeeds. Conditional on , attempts are independent and each has the distribution conditional on its outcome, so . Taking the expectation over , with , gives the formula.
∎Using the cell’s figures, steps without sideways moves and with them: sideways moves greatly change the success rate and barely change expected cost. This is the first lesson in comparing metaheuristics: one attempt’s success rate is not the measure that matters; cost to solve is.
The theorem generalizes to a common situation: an algorithm that could eventually solve the problem if left running, but with highly variable running time . If cut off and restarted every steps, each attempt costs and succeeds with probability , and the same argument gives . Restarting pays when the distribution of is heavy-tailed, meaning some runs get lost in unproductive regions for a very long time. Gomes, Selman, Crato and Kautz (2000) documented such tails in SAT and CSP backtracking procedures, which is why modern SAT solvers restart frequently (see CDCL restarts). If the distribution is unknown, Luby, Sinclair and Zuckerman’s (1993) universal strategy with cutoffs guarantees expected cost within a logarithmic factor of the best fixed-cutoff strategy. If is exponential and memoryless, restarting neither helps nor hurts.
Simulated annealing
Hill climbing never goes uphill. Escaping a local minimum requires sometimes accepting worsening moves without losing the tendency to descend. Kirkpatrick, Gelatt and Vecchi (1983), and independently Černý (1985), borrowed the idea from statistical physics: a slowly cooled solid reaches a minimum-energy state (a crystal), whereas one cooled suddenly gets trapped as glass.
Improvements are always accepted. Worsenings are accepted with probability exponentially decreasing in their size and increasing with temperature. With and , the probability is ; with , . When , the algorithm is a random walk on the neighborhood graph; when , stochastic first-improvement hill climbing that also accepts sideways moves (). The rule is due to Metropolis, Rosenbluth, Rosenbluth, Teller and Teller (1953), who designed it to sample configurations of a physical system in equilibrium, and is the same acceptance criterion as the Metropolis-Hastings algorithm in MCMC.
At fixed temperature: the Boltzmann distribution
With constant , annealing is a homogeneous Markov chain on with transition matrix
What distribution does it converge to? Consider the simplest case, two neighboring states and with , , and a symmetric proposal. The transition from to has probability , and from to probability . At equilibrium, flow from to and from to must balance: , that is, . The chain allocates its time according to energy.
The first part follows from detailed balance, , which you will prove step by step in the final guided exercise. Convergence follows from the convergence theorem for irreducible, aperiodic Markov chains on finite spaces. Aperiodicity is almost never a problem: once a state has a higher-energy neighbor, the proposal to go uphill is rejected with positive probability and there is a self-loop. It fails only when energy is constant and the graph bipartite, an uninteresting case.
Two assumptions deserve attention. Proposal symmetry is not a technicality: if you choose a neighbor uniformly and neighborhoods have different sizes, and the stationary distribution is no longer Boltzmann. The Metropolis-Hastings correction accepts with . Graph connectivity is essential too: if the neighborhood cannot reach every state from every other, annealing will never see part of the space.
The consequence justifying the method is what happens on cooling. If is the set of global minima and , for
so concentrates uniformly on : . At low temperature, the equilibrium distribution lives on global minima. The problem is reaching equilibrium.
How long equilibrium takes
The particle figure already shows it: at occupancy matches Boltzmann in a few thousand steps, but that Boltzmann spreads mass across the landscape; at Boltzmann is almost entirely at the global minimum and occupancy does not approach it. The next cell computes this exactly on a 41-state landscape with two wells: a local one at (), a barrier at (), and the global minimum at (). It builds matrix , checks is stationary and satisfies detailed balance, and measures the spectral gap controlling convergence speed: distance to decreases as , with , and in this chain the most negative eigenvalue never falls below , so dominates, very close to 1.
import numpy as np
# paisaje de 41 estados: pozo local en s = 10 (E = 0.3), barrera en s = 20 (E = 1), mínimo global en s = 30 (E = 0)
s = np.arange(41)
E = np.interp(s, [0, 10, 20, 30, 40], [0.8, 0.3, 1.0, 0.0, 0.8])
def metropolis_matriz(E, T):
"""P[i, j]: proponer i ± 1 con probabilidad 1/2 (fuera del dominio se rechaza) y aceptar con min(1, e^{-ΔE/T})."""
n = len(E)
P = np.zeros((n, n))
for i in range(n):
for j in (i - 1, i + 1):
if 0 <= j < n:
P[i, j] = 0.5 * min(1.0, np.exp(-(E[j] - E[i]) / T))
P[i, i] = 1.0 - P[i].sum()
return P
def espectro(P, pi):
"""Autovalores ordenados. Como la cadena es reversible, D^{1/2} P D^{-1/2} es simétrica y son reales."""
r = np.sqrt(pi)
S = (r[:, None] * P) / r[None, :]
return np.sort(np.linalg.eigvalsh((S + S.T) / 2))
def hueco(P, pi):
return 1 - espectro(P, pi)[-2]
print(" T |π_T P − π_T| máx |π_i P_ij − π_j P_ji| π_T(s = 30) 1 − λ₂ λ_min")
for T in [1.0, 0.3, 0.15, 0.1, 0.07, 0.05]:
P = metropolis_matriz(E, T)
pi = np.exp(-(E - E.min()) / T); pi /= pi.sum()
flujo = pi[:, None] * P # flujo de probabilidad i -> j en equilibrio
ev = espectro(P, pi)
print(f"{T:5.2f} {np.abs(pi @ P - pi).max():.1e} {np.abs(flujo - flujo.T).max():.1e}"
f" {pi[30]:.3f} {1 - ev[-2]:.2e} {ev[0]:.3f}")
# ley de Arrhenius: el hueco se cierra como exp(−profundidad / T)
for Ts in ([0.1, 0.08, 0.07, 0.06, 0.05], [0.04, 0.035, 0.03, 0.025]):
Ts = np.array(Ts)
g = []
for T in Ts:
P = metropolis_matriz(E, T)
pi = np.exp(-(E - E.min()) / T); pi /= pi.sum()
g.append(hueco(P, pi))
pend = np.polyfit(1 / Ts, -np.log(g), 1)[0]
print(f"T entre {Ts.min()} y {Ts.max()}: pendiente de −log(1 − λ₂) frente a 1/T = {pend:.3f}")
print("profundidad del pozo local: 1.0 − 0.3 = 0.7")The first two columns are machine zeros: Boltzmann is stationary and probability flow between each pair of states balances exactly, as the theorem says. The third shows concentration: mass at the global minimum changes from to to to . The fourth is the price: the spectral gap drops from to , so relaxation time increases from about 400 steps to about eleven million. The last column confirms that the most negative eigenvalue (between and ) does not compete with . The slope of against approaches as falls ( between and , between and ): the gap closes as times a prefactor only weakly dependent on . is the height needed to escape the local well, the Arrhenius law of physical chemistry: escape time grows as .
Cooling schedules and Hajek’s result
The dilemma is clear. At high the chain equilibrates quickly, but equilibrium does not favor minima; at low equilibrium is at minima, but reaching it takes exponential time. Annealing lowers gradually hoping to follow equilibrium. Common schedules are:
- Geometric: with slightly less than 1 (or constant for blocks of steps and multiplied by between blocks). This is the practical standard; to go from to in steps, use .
- Logarithmic: . This has a theoretical guarantee.
- Adaptive: adjust or block length according to observed acceptance rate or energy variance.
How long must we wait for guarantees? Hajek (1988) gave the exact answer. Define the depth of a nonglobal local minimum as the least height such that from one can reach a state of energy less than along a neighborhood-graph path where energy never exceeds . Let be the greatest depth among all nonglobal local minima.
The second part follows from the first: , and the series diverges exactly when . The intuition is the cell’s: escaping the deepest well at temperature takes on the order of attempts, and the condition requires the expected number of escapes over the whole run to be infinite.
This is a beautiful result and almost useless as a recipe. With , temperature halves when doubles, that is, when is squared: if you reach at step , you reach at step . Moreover is unknown. In practice the geometric schedule is used, without convergence guarantee, under a predetermined budget and compared with alternatives in honest experiments. The theorem does provide a qualitative lesson: temperature scale is set by landscape barriers, not absolute energy, and should be on the order of typical of worsening moves.
Tabu search
Annealing escapes local minima through randomness. The deterministic alternative is always moving to the best neighbor, even if worse, and using memory to avoid going back.
Without memory, that rule predictably fails. At a local minimum the best neighbor is the least-worsening one, say by . From , returning to improves by and is often the best available move: search oscillates between and forever. Glover’s solution, named in 1986 and developed in 1989, temporarily forbids moves undoing recent ones.
Design decisions concern attributes and tenure:
- Attributes, not states. Storing full states and forbidding revisits would be exact but expensive and, above all, too weak: a visited state’s neighbor is rarely exactly one already visited. Instead forbid an attribute: in 2-opt traveling salesperson, naturally forbid restoring edges just removed. This forbids undoing the move and many other moves reconstructing part of what was undone.
- Tenure. Too short and search can still cycle, necessarily with period greater than tenure (a removed edge cannot return before its ban expires): in the figure below, tenure 5 gives a cycle of 14 tours; too long and it forbids so many moves that search wanders without intensifying in a good region. Choose experimentally (in the lab, among 10, 30 and 60 iterations on a separate instance), and many implementations randomly draw it within a range each move to avoid cycles synchronized to it.
- Aspiration. A forbidden attribute may block a move leading to a record. Since the record has never been visited, no cycle is possible and the move is allowed.
- Long-term memory. Full versions add usage frequencies for each attribute, to diversify (penalize heavily used attributes and explore other regions) or intensify (return to best solutions and explore their surroundings more carefully).
Two interactive details matter in the lab too. Steepest hill climbing stops as soon as it reaches a local optimum and wastes the remaining budget: it should be given restarts. One tabu iteration evaluates the entire neighborhood, moves, to take one step, whereas annealing spends one evaluation per step. At equal evaluation counts, tabu takes far fewer steps. Serious implementations reduce the neighborhood using candidate lists: consider only 2-opt moves adding an edge between a city and one of its nearest neighbors, because a long edge is rarely part of a good tour.
Local beam and genetic algorithms
Local beam
This differs from parallel restarts: the states compete, and if one has much better neighbors than the others the whole beam moves to its surroundings. This concentrates effort where progress is made, but also loses diversity and crowds the beam into one region. Also, by retaining the best neighbors even if worse than current states, the beam keeps moving where hill climbing would stop. Stochastic beam search chooses successors randomly with probability increasing with quality, preserving more diversity and essentially performing natural selection.
import random
def vecinos_con_h(s, h):
"""Todos los vecinos de s (mover una reina en su columna) con su número de conflictos, en O(1) cada uno."""
n = len(s)
fil, d1, d2 = [0] * n, [0] * (2 * n), [0] * (2 * n)
for c, f in enumerate(s):
fil[f] += 1; d1[f - c + n] += 1; d2[f + c] += 1
for c in range(n):
a = s[c]
quita = fil[a] + d1[a - c + n] + d2[a + c] - 3
for f in range(n):
if f != a:
yield s[:c] + (f,) + s[c + 1:], h + fil[f] + d1[f - c + n] + d2[f + c] - quita
def conflictos(s):
n = len(s)
return sum(s[i] == s[j] or abs(s[i] - s[j]) == j - i for i in range(n) for j in range(i + 1, n))
def haz_local(n, k, rng, max_pasos=30):
"""Haz local: genera todos los sucesores de los k estados y se queda con los k mejores (distintos)."""
haz = {}
while len(haz) < k:
s = tuple(rng.randrange(n) for _ in range(n))
haz[s] = conflictos(s)
evals = 0
for _ in range(max_pasos):
if min(haz.values()) == 0:
return True, evals
suc = {}
for s, h in haz.items():
for t, ht in vecinos_con_h(s, h):
suc[t] = ht
evals += 1
orden = list(suc.items())
rng.shuffle(orden) # desempate aleatorio
orden.sort(key=lambda x: x[1])
haz = dict(orden[:k])
return min(haz.values()) == 0, evals
def reinicios(n, rng):
"""Hill climbing de mayor pendiente con reinicios aleatorios hasta resolver; devuelve evaluaciones."""
evals = 0
while True:
s = tuple(rng.randrange(n) for _ in range(n))
h = conflictos(s)
while h > 0:
vec = list(vecinos_con_h(s, h))
evals += len(vec)
hm = min(x[1] for x in vec)
if hm >= h:
break
s, h = rng.choice([x for x in vec if x[1] == hm])
if h == 0:
return evals
rng = random.Random(1)
ev_r = [reinicios(8, rng) for _ in range(300)]
print(f"reinicios independientes: evaluaciones hasta resolver, media {sum(ev_r) / len(ev_r):.0f}")
for k in (2, 5, 10):
R = [haz_local(8, k, rng) for _ in range(100)]
ok = [e for r, e in R if r]
ko = [e for r, e in R if not r]
p, c_ex = len(ok) / len(R), sum(ok) / len(ok)
c_fr = sum(ko) / len(ko) if ko else 0.0
print(f"haz local k = {k:2d}: resuelve {len(ok)} de 100, evaluaciones medias en los resueltos {c_ex:.0f}; "
f"relanzándolo hasta resolver, coste esperado {c_ex + (1 - p) / p * c_fr:.0f}")Restarts solve eight queens in about 1575 evaluations on average. A beam with solves 93 out of 100 problems in 30 steps with about 909, and with or solves all, but with more evaluations (1481 and 2167): each step costs evaluations, and beyond some the beam pays more than it gains. Honest comparison with must also charge for the 7 failures: applying the expected-cost theorem to “restart the beam until solved” raises expected cost from 909 to about 1160 evaluations, still below 1575 for restarts. This is how to compare methods with different success rates: not the average of successes, but expected cost to succeed.
Genetic algorithms
Without crossover, a genetic algorithm is a stochastic beam with mutation as neighborhood. Crossover adds the possibility of combining good parts of different solutions. Whether that works depends entirely on representation: crossover helps only if pieces copied from each parent make sense separately and continue to do so together.
The extreme example is traveling salesperson. A tour is a permutation, and one-point crossover between two permutations almost never produces one: one parent’s prefix and the other’s suffix repeat some cities and omit others. For a cut at , the child is valid if and only if the second parent’s suffix contains exactly the cities missing from the first parent’s prefix, which for random parents occurs with probability . Permutation-specific crossover is needed, such as Davis’s (1985) order crossover (OX): copy one segment from the first parent unchanged and fill remaining positions with missing cities in the order they occur in the second.
import random, math
from math import comb
import numpy as np
def un_punto(p1, p2, rng):
c = rng.randrange(1, len(p1))
return p1[:c] + p2[c:]
def ox(p1, p2, rng):
"""Cruce por orden (OX): copia un tramo de p1 y completa con el orden relativo de p2. Siempre es permutación."""
n = len(p1)
i, j = sorted(rng.sample(range(n), 2))
hijo = [None] * n
hijo[i:j + 1] = p1[i:j + 1]
usados, k = set(p1[i:j + 1]), (j + 1) % n
for c in p2[j + 1:] + p2[:j + 1]:
if c not in usados:
hijo[k] = c
k = (k + 1) % n
return hijo
rng = random.Random(0)
n = 20
pares = [(rng.sample(range(n), n), rng.sample(range(n), n)) for _ in range(20000)]
validos_1p = sum(len(set(un_punto(a, b, rng))) == n for a, b in pares) / len(pares)
validos_ox = sum(sorted(ox(a, b, rng)) == list(range(n)) for a, b in pares) / len(pares)
exacta = sum(1 / comb(n, c) for c in range(1, n)) / (n - 1)
print(f"n = {n}: hijos válidos con un punto {validos_1p:.4f} (exacta {exacta:.4f}); con OX {validos_ox:.4f}")def genetico(D, presupuesto, pob, p_mut, semilla):
"""Estado estacionario: torneo binario, OX, mutación por inversión y sustitución del peor si el hijo es mejor."""
rng = random.Random(semilla)
n = len(D)
Dl = D.tolist()
L = lambda t: sum(Dl[t[k - 1]][t[k]] for k in range(n))
P = [rng.sample(range(n), n) for _ in range(pob)]
F = [L(t) for t in P]
usados = pob
while usados < presupuesto:
a, b = rng.randrange(pob), rng.randrange(pob)
c, d = rng.randrange(pob), rng.randrange(pob)
hijo = ox(P[a if F[a] < F[b] else b], P[c if F[c] < F[d] else d], rng)
if rng.random() < p_mut:
i, j = sorted(rng.sample(range(n), 2))
hijo[i:j + 1] = hijo[i:j + 1][::-1]
f = L(hijo)
usados += 1
peor = max(range(pob), key=F.__getitem__)
if f < F[peor]:
P[peor], F[peor] = hijo, f
return min(F)
def recocido_basico(D, presupuesto, T0, T1, semilla):
"""Recocido con 2-opt uniforme y delta en O(1), para compararlo con el genético al mismo presupuesto."""
rng = random.Random(semilla)
n = len(D)
Dl = D.tolist()
t = rng.sample(range(n), n)
coste = sum(Dl[t[k - 1]][t[k]] for k in range(n))
mejor, T, alfa = coste, T0, (T1 / T0) ** (1 / presupuesto)
for _ in range(presupuesto):
i, j = sorted(rng.sample(range(n), 2))
if j - i >= 2 and not (i == 0 and j == n - 1):
a, b, c, d = t[i], t[i + 1], t[j], t[(j + 1) % n]
delta = Dl[a][c] + Dl[b][d] - Dl[a][b] - Dl[c][d]
if delta <= 0 or rng.random() < math.exp(-delta / T):
t[i + 1:j + 1] = t[j:i:-1]
coste += delta
mejor = min(mejor, coste)
T *= alfa
return mejor
Pts = np.random.default_rng(7).random((50, 2))
D = np.sqrt(((Pts[:, None] - Pts[None]) ** 2).sum(-1))
for s in range(3):
print(f"semilla {s}: genético (OX) {genetico(D, 30_000, 50, 0.9, s):.3f} recocido {recocido_basico(D, 30_000, 0.1, 0.003, s):.3f}")With 20 cities, only of one-point crossover children are tours (the exact formula, averaging across cuts, gives ; the difference lies within sampling error for 20 000 pairs), versus 100% for OX. Even with correct crossover, on 50 cities and the same budget of 30 000 evaluated tours, the genetic algorithm ends above annealing for all three seeds. This is not an accident of the experiment: competitive genetic algorithms for traveling salesperson, such as Nagata and Kobayashi’s (2013) edge assembly crossover (EAX), use crossover designed to inherit and recombine edges and, as the paper’s abstract says, localize it and incorporate local search; memetic algorithms take this further and apply local search to every child.
Reading the schema theorem carefully
Holland (1975) proposed explaining genetic algorithms with schemata. For binary strings of length , a schema is a template over , for example , representing all strings matching its fixed positions. Its order is the number of fixed positions (here 3) and its defining length the distance between first and last fixed positions (here 5). Let be the number of generation individuals belonging to , their mean fitness and the population mean.
With roulette selection, each of offspring has a parent in with probability , so selection alone produces copies on average. One-point crossover with probability can break only if the cut falls between its first and last fixed positions, with probability . Mutation at rate per position preserves the fixed positions with probability . Combining the three bounds,
This is the schema theorem. Its popular reading, that “short, low-order, above-average schemata grow exponentially,” and the building-block hypothesis based on it, do not follow:
- It is a lower bound on an expectation for one generation. It ignores that crossover also creates representatives of by combining parents that were not representatives, and says nothing about variance: in finite populations genetic drift can eliminate good schemata.
- It cannot be iterated. is the mean fitness of representatives in the current population, which changes as soon as the population changes; a schema “above average” today may not be tomorrow. Extrapolating exponential growth requires assuming constant, generally false.
- A schema’s fitness depends on the population sampling it, not on its strings, and on deceptive problems short, fit schemata point away from the optimum.
When does crossover help?
Evidence is more modest than rhetoric. Mitchell, Holland and Forrest (1993) analyzed Royal Road functions, deliberately constructed so building blocks combine well, and started from the observation that random-mutation hill climbing (RMHC) outperformed a standard genetic algorithm on them; they explained why and what features a genetic algorithm would need to win. Theoretically, Jansen and Wegener (2002) rigorously proved crossover can help: on , whose optimum lies beyond a jump of Hamming distance , a mutation-only algorithm such as (1+1) EA needs expected time , while a genetic algorithm with uniform crossover solves it in . One qualification: the result requires very small crossover probability ; Opris, Lengler and Sudholt (2024) extended it to realistic values , with populations and a tight bound .
The practical rule: a genetic algorithm helps over local search when (1) the problem decomposes into separately optimizable and combinable parts, (2) representation places those parts where crossover preserves them, and (3) population diversity is useful in itself, for example with multiple objectives (Pareto fronts) or noisy evaluations. If none holds, well-designed annealing or tabu wins at the same budget, and the best genetic algorithms are actually hybrids with local search (memetic algorithms).
Comparing metaheuristics honestly
Metaheuristics are stochastic algorithms: runs with different seeds produce different results, and quality depends on budget, instance and parameters. This makes comparing two easy to get wrong. Minimum rules:
- Several seeds and instances. One run per algorithm is a sample of size one from a distribution. With seeds on each of instances you have a real sample, and it is wise to use the same initial state (or seed) for all algorithms on each pair so the comparison is paired and instance variability does not hide differences (see paired tests).
- The same budget, in the same units. Budget in objective evaluations, evaluated moves or seconds, but the same for all and stated explicitly. The units answer different questions: evaluations compare search strategy, time compares the whole implementation. In the lab tabu, vectorized with NumPy, evaluates moves considerably faster than pure-Python annealing (about three times in the cell), so a tie in evaluations is not a tie in time.
- Tune on separate instances. Choosing or tenure by testing on the same instances later compared makes the winner partly the one given most trials. Tune on different instances with comparable tuning budgets for all.
- Distributions, not means. For decision problems (reaching a target), use the time-to-target distribution: for each run, evaluations to reach a given quality, and empirical curve . Hoos and Stützle (2004) call these runtime distributions (RTDs), and Aiex, Resende and Ribeiro (2002) showed that many GRASP-type metaheuristics fit a shifted exponential well. An RTD answers both “how long?” and “do restarts pay?” and reveals runs that never arrive, which a mean hides.
The no-free-lunch theorem
Uniformly averaged over all possible functions, no algorithm is better than another on any performance measure depending only on observed values: annealing, genetic search and random search without replacement tie (for methods revisiting points, such as annealing, count only distinct points evaluated: repeating an evaluation adds no information). Intuition: if is uniform among all functions, values at unvisited points are independent of observed values, so what was learned cannot help choose where to look.
What the theorem does not say is equally important. It does not say all algorithms are equal on problems you care about: real problems have structure (traveling-salesperson distances obey the triangle inequality, good tours share short edges) that the uniform distribution over all functions does not. Schumacher, Vose and Whitley (2001) proved the result holds for a subset of functions if and only if it is closed under permutations of the domain, and almost no subset is (Igel and Toussaint, 2003). What it does say, and what is useful: one algorithm’s advantage over another comes from problem structure it exploits, paid for by worse performance on problems without that structure. Claiming a method is “better in general” is literally false; claiming it is better for a problem class requires stating the structure it exploits and testing on that class.
Lab: annealing and tabu for traveling salesperson, from scratch
The lab implements everything above for Euclidean traveling salesperson with 200 cities uniform in the unit square and compares methods under the previous section’s rules. First, the 2-opt neighborhood with incremental evaluation, checked against complete recomputation and timed.
import numpy as np, math, time
def instancia(n, semilla):
"""n ciudades uniformes en el cuadrado unidad y su matriz de distancias euclídeas."""
P = np.random.default_rng(semilla).random((n, 2))
return P, np.sqrt(((P[:, None, :] - P[None, :, :]) ** 2).sum(-1))
def longitud(t, D):
t = np.asarray(t)
return float(D[t, np.roll(t, -1)].sum())
def delta_2opt(t, D, i, j):
"""Cambio de longitud al quitar (t[i], t[i+1]) y (t[j], t[j+1]) y poner (t[i], t[j]) y (t[i+1], t[j+1]). O(1)."""
n = len(t)
a, b, c, d = t[i], t[i + 1], t[j], t[(j + 1) % n]
return D[a][c] + D[b][d] - D[a][b] - D[c][d]
def aplica_2opt(t, i, j):
"""Invierte el tramo t[i+1..j]: cuesta O(j - i), no O(1)."""
t[i + 1:j + 1] = t[j:i:-1]
# comprobación: el delta incremental coincide con recalcular la longitud entera
P, D = instancia(200, 1)
Dl = D.tolist()
rng = np.random.default_rng(0)
t = [int(c) for c in rng.permutation(200)]
err = 0.0
for _ in range(2000):
i, j = sorted(int(x) for x in rng.choice(200, 2, replace=False))
if j - i < 2 or (i == 0 and j == 199):
continue
antes = longitud(t, D)
d = delta_2opt(t, Dl, i, j)
aplica_2opt(t, i, j)
err = max(err, abs(longitud(t, D) - antes - d))
print(f"máximo |delta incremental − recálculo| en 2000 movimientos: {err:.1e}")
# coste por evaluación: delta en O(1) frente a recalcular la longitud en O(n)
movs = [tuple(sorted(int(x) for x in rng.choice(200, 2, replace=False))) for _ in range(20000)]
movs = [(i, j) for i, j in movs if j - i >= 2 and not (i == 0 and j == 199)]
t0 = time.perf_counter()
for i, j in movs:
delta_2opt(t, Dl, i, j)
t_inc = (time.perf_counter() - t0) / len(movs)
t0 = time.perf_counter()
for i, j in movs[:2000]:
u = t[:]
aplica_2opt(u, i, j)
sum(Dl[u[k - 1]][u[k]] for k in range(200))
t_full = (time.perf_counter() - t0) / 2000
print(f"por movimiento: incremental {t_inc * 1e6:.1f} µs, recálculo completo {t_full * 1e6:.1f} µs ({t_full / t_inc:.0f} veces más)")Now annealing. Two choices distinguish it from the textbook version. The proposal uses candidate lists: choose a random position and one of cities nearest , and propose the 2-opt move creating their edge; almost no proposal is absurd. And and are chosen on a tuning instance (seed 100) not used for comparison. This proposal is not symmetric: being among the neighbors of does not imply the reverse, and the number of valid pairs changes with the tour. At fixed temperature it would not sample exact Boltzmann. For optimization under a fixed budget and geometric cooling this does not matter, because we are outside any convergence theorem’s assumptions anyway: the experiment decides.
def vecinos_cercanos(D, K):
"""Lista de candidatos: las K ciudades más próximas a cada una."""
return np.argsort(D, axis=1)[:, 1:K + 1]
def recocido(D, tour, presupuesto, T0, T1, K, semilla):
"""Recocido con 2-opt: posición i al azar y una de las K vecinas de t[i]; enfriamiento geométrico de T0 a T1."""
n = len(D)
Dl, NB = D.tolist(), vecinos_cercanos(D, K).tolist()
t = [int(c) for c in tour]
pos = [0] * n
for k, c in enumerate(t):
pos[c] = k
coste = longitud(t, D)
mejor = coste
rng = np.random.default_rng(semilla)
I = rng.integers(0, n, presupuesto).tolist()
V = rng.integers(0, K, presupuesto).tolist()
U = rng.random(presupuesto).tolist()
alfa, T = (T1 / T0) ** (1 / presupuesto), T0
for k in range(presupuesto):
i, j = I[k], pos[NB[t[I[k]]][V[k]]]
if i > j:
i, j = j, i
if j - i >= 2 and not (i == 0 and j == n - 1):
a, b, c, d = t[i], t[i + 1], t[j], t[(j + 1) % n]
delta = Dl[a][c] + Dl[b][d] - Dl[a][b] - Dl[c][d]
if delta <= 0 or U[k] < math.exp(-delta / T):
t[i + 1:j + 1] = t[j:i:-1]
for p in range(i + 1, j + 1):
pos[t[p]] = p
coste += delta
mejor = min(mejor, coste)
T *= alfa
return mejor
# sintonía en una instancia que NO se usa para comparar (semilla 100), con un presupuesto menor
_, Dsint = instancia(200, 100)
inicio = np.random.default_rng(100).permutation(200)
sintonia = {}
for T0 in (0.03, 0.1):
for T1 in (1e-3, 3e-3):
r = [recocido(Dsint, inicio, 100_000, T0, T1, 8, s) for s in range(2)]
sintonia[(T0, T1)] = np.mean(r)
print(f"T0 = {T0:<5} T1 = {T1:<6} longitudes: {r[0]:.3f}, {r[1]:.3f} media {np.mean(r):.3f}")
T0_SA, T1_SA = min(sintonia, key=sintonia.get)
print("elegidos:", T0_SA, T1_SA)With chosen parameters, the experiment: two instances (seeds 1 and 2), three seeds per instance, 300 000 evaluated moves per run, and for each pair the same random initial tour for all methods.
PRESUPUESTO = 300_000
INSTANCIAS, SEMILLAS = (1, 2), (0, 1, 2)
res = {}
t0 = time.perf_counter()
for ins in INSTANCIAS:
_, Di = instancia(200, ins)
for s in SEMILLAS:
inicio = np.random.default_rng(1000 * ins + s).permutation(200) # el mismo para todos los métodos
res[("recocido", ins, s)] = recocido(Di, inicio, PRESUPUESTO, T0_SA, T1_SA, 8, s)
print(f"instancia {ins}, semilla {s}: inicial {longitud(inicio, Di):.2f} -> recocido {res[('recocido', ins, s)]:.3f}")
print(f"{(time.perf_counter() - t0) / 6:.2f} s por ejecución de {PRESUPUESTO} propuestas")Tabu uses the same candidate lists. Each iteration evaluates all candidate moves together with NumPy, forbids restoring removed edges for the tenure, and applies aspiration. As a minimal reference, steepest hill climbing uses the same lists and random restarts until the budget is exhausted. Since tabu spends many evaluations per step, it is also run with ten times the budget to see whether its disadvantage is strategy or only budget.
def tabu(D, tour, presupuesto, tenencia, K, semilla):
"""Tabú con 2-opt y listas de candidatos. Cada iteración evalúa todos los movimientos candidatos (vectorizado),
prohíbe reponer durante `tenencia` iteraciones las aristas quitadas y admite un movimiento prohibido si mejora el
mejor recorrido conocido (aspiración). El presupuesto cuenta movimientos evaluados."""
n = len(D)
t = np.array(tour)
pos = np.empty(n, int)
pos[t] = np.arange(n)
NB = vecinos_cercanos(D, K)
hasta = np.zeros((n, n), int)
filas = np.arange(n)[:, None]
rng = np.random.default_rng(semilla)
coste = mejor = longitud(t, D)
usados = it = 0
while usados < presupuesto:
it += 1
jp = pos[NB[t]] # posición de cada candidata de t[i]
lo, hi = np.minimum(filas, jp), np.maximum(filas, jp)
ok = (hi - lo >= 2) & ~((lo == 0) & (hi == n - 1))
lo, hi = lo[ok], hi[ok]
a, b, c, d = t[lo], t[lo + 1], t[hi], t[(hi + 1) % n]
delta = D[a, c] + D[b, d] - D[a, b] - D[c, d]
usados += len(delta)
prohibido = ((hasta[a, c] > it) | (hasta[b, d] > it)) & ~(coste + delta < mejor - 1e-12)
delta = np.where(prohibido, np.inf, delta)
q = rng.choice(np.flatnonzero(delta <= delta.min() + 1e-12))
i, j = lo[q], hi[q]
for u, v in ((t[i], t[i + 1]), (t[j], t[(j + 1) % n])):
hasta[u, v] = hasta[v, u] = it + tenencia
t[i + 1:j + 1] = t[i + 1:j + 1][::-1].copy()
pos[t[i + 1:j + 1]] = np.arange(i + 1, j + 1)
coste += delta[q]
mejor = min(mejor, coste)
return mejor, it
def descenso_con_reinicios(D, presupuesto, K, semilla):
"""Hill climbing de mayor pendiente con las mismas listas de candidatos y reinicios aleatorios."""
n = len(D)
rng = np.random.default_rng(semilla)
NB, filas = vecinos_cercanos(D, K), np.arange(n)[:, None]
usados, mejor, reinicios = 0, np.inf, 0
while usados < presupuesto:
t = rng.permutation(n)
pos = np.empty(n, int)
pos[t] = np.arange(n)
coste = longitud(t, D)
reinicios += 1
while usados < presupuesto:
jp = pos[NB[t]]
lo, hi = np.minimum(filas, jp), np.maximum(filas, jp)
ok = (hi - lo >= 2) & ~((lo == 0) & (hi == n - 1))
lo, hi = lo[ok], hi[ok]
a, b, c, d = t[lo], t[lo + 1], t[hi], t[(hi + 1) % n]
delta = D[a, c] + D[b, d] - D[a, b] - D[c, d]
usados += len(delta)
q = int(np.argmin(delta))
if delta[q] >= -1e-12:
break # óptimo local de 2-opt (con candidatos)
i, j = lo[q], hi[q]
t[i + 1:j + 1] = t[i + 1:j + 1][::-1].copy()
pos[t[i + 1:j + 1]] = np.arange(i + 1, j + 1)
coste += delta[q]
mejor = min(mejor, coste)
return mejor, reinicios
# sintonía de la tenencia en la instancia de sintonía, con diez veces el presupuesto
inicio = np.random.default_rng(100).permutation(200)
ten = {tn: tabu(Dsint, inicio, 10 * PRESUPUESTO, tn, 8, 0)[0] for tn in (10, 30, 60)}
TENENCIA = min(ten, key=ten.get)
print("tenencia: " + ", ".join(f"{k} -> {v:.3f}" for k, v in ten.items()) + f" elegida {TENENCIA}")for ins in INSTANCIAS:
_, Di = instancia(200, ins)
for s in SEMILLAS:
inicio = np.random.default_rng(1000 * ins + s).permutation(200)
res[("tabú", ins, s)], it = tabu(Di, inicio, PRESUPUESTO, TENENCIA, 8, s)
res[("reinicios", ins, s)], nr = descenso_con_reinicios(Di, PRESUPUESTO, 8, s)
print(f"instancia {ins}, semilla {s}: tabú {res[('tabú', ins, s)]:.3f} ({it} iteraciones) "
f"reinicios {res[('reinicios', ins, s)]:.3f} ({nr} descensos)")def tabu_x10(ins):
_, Di = instancia(200, ins)
for s in SEMILLAS:
inicio = np.random.default_rng(1000 * ins + s).permutation(200)
t0 = time.perf_counter()
res[("tabú ×10", ins, s)], it10 = tabu(Di, inicio, 10 * PRESUPUESTO, TENENCIA, 8, s)
dt = time.perf_counter() - t0
print(f"instancia {ins}, semilla {s}: tabú ×10 {res[('tabú ×10', ins, s)]:.3f} ({it10} iteraciones)")
return Di, inicio, dt # el tiempo de la última ejecución
_ = tabu_x10(1)Di, inicio, tt10 = tabu_x10(2)
t0 = time.perf_counter(); recocido(Di, inicio, PRESUPUESTO, T0_SA, T1_SA, 8, 0); tsa = time.perf_counter() - t0
print(f"tiempo: tabú con {10 * PRESUPUESTO} evaluaciones {tt10:.2f} s; recocido con {PRESUPUESTO} {tsa:.2f} s")Finally, paired comparison. For each rival, tour-length differences from annealing on the six pairs , how often annealing wins, and the Wilcoxon signed-rank test. With six pairs the smallest possible two-sided is , achieved when one method wins them all.
from scipy.stats import wilcoxon
metodos = ["reinicios", "tabú", "recocido", "tabú ×10"]
print("método media desv. mínimo máximo")
for m in metodos:
v = np.array([res[(m, i, s)] for i in INSTANCIAS for s in SEMILLAS])
print(f"{m:12s} {v.mean():7.3f} {v.std(ddof=1):6.3f} {v.min():7.3f} {v.max():7.3f}")
pares = [(i, s) for i in INSTANCIAS for s in SEMILLAS]
for rival in ("tabú", "tabú ×10", "reinicios"):
dif = np.array([res[(rival, i, s)] - res[("recocido", i, s)] for i, s in pares])
print(f"recocido mejor que {rival:9s} en {int((dif > 0).sum())} de {len(pares)} pares; "
f"diferencia media {dif.mean():.3f}; Wilcoxon emparejado p = {wilcoxon(dif).pvalue:.3f}")The results, read using the previous section’s rules:
- Annealing wins in this design, on all six pairs: mean 10.843 versus 11.128 for tabu with ten times more evaluations, 11.663 for restarts and 11.825 for tabu at equal budget. Six of six pairs gives Wilcoxon , the smallest possible, against each rival.
- Equal-budget tabu has not finished descending. With about 1340 evaluations per iteration, 300 000 evaluations give about 224 iterations, roughly one steepest descent from a random 200-city tour: under the same budget, descent with restarts completes only one or two. Thus tabu and restarts are almost tied (11.825 versus 11.663): both spent the budget on initial descent. Comparing equal evaluation counts penalizes tabu for steepest descent, not tabu memory.
- With ten times more evaluations, tabu gets closer but does not catch up. It falls from 11.825 to 11.128 and still trails on all six pairs. In the cell those ten times more evaluations take three to four times as long as annealing because each vectorized evaluation is cheaper than pure Python: tabu does not win on wall time either. If annealing were written in C, the time comparison would change again. This is what it means for budget units to be part of the result.
- What cannot be concluded: that annealing is better than tabu for traveling salesperson generally. It is better for these implementations, this budget and these uniform 200-city instances. With combined 2-opt and Or-opt, first-improvement tabu or clustered instances, the order could change, and benchmark traveling-salesperson methods (Lin-Kernighan and successors) are neither.
The library version
networkx includes simulated_annealing_tsp. Its implementation is instructive for two reasons. First, each proposal applies the move (by default, swapping two cities) and recomputes the whole length, per proposal. Second, more subtly, the default move swap_two_nodes modifies the received list in place (its documentation warns: “The input list is changed as well as returned”), and the loop passes it without copying. If the proposal is rejected, the cycle retains the swap while stored cost remains the previous one, so the chain drifts and later comparisons use a cost no longer matching the cycle. The cell checks this by running the same annealing with the default move and with the same move applied to a copy.
The budget is not fixed directly: the outer loop stops after max_iterations consecutive passes without improvement, so we count proposals by wrapping the move. An initial tour is required, and the usual choice "greedy" is the greedy tour; default temperature 100 is intended for large integer weights and must be lowered for distances in the unit square. Fair comparison gives our annealing the same initial tour, proposals and initial and final temperatures.
import networkx as nx, random
from networkx.algorithms.approximation.traveling_salesman import swap_two_nodes
_, D1 = instancia(200, 1)
G = nx.complete_graph(200)
for u, v in G.edges:
G[u][v]["weight"] = float(D1[u, v])
voraz = nx.approximation.greedy_tsp(G) # lo que usa init_cycle="greedy"
print(f"networkx {nx.__version__}; recorrido voraz: {longitud(voraz[:-1], D1):.3f}")
c = list(voraz)
print("¿swap_two_nodes devuelve la misma lista que recibe?", swap_two_nodes(c, random.Random(0)) is c)
def contando(mover):
"""Envuelve un movimiento para contar las propuestas."""
llamadas = [0]
def mov(ciclo, seed):
llamadas[0] += 1
return mover(ciclo, seed)
return mov, llamadas
params = dict(temp=0.02, alpha=0.1, N_inner=200, max_iterations=10, seed=0)
variantes = [("movimiento por defecto, en el sitio", swap_two_nodes),
("el mismo movimiento sobre una copia", lambda ciclo, seed: swap_two_nodes(list(ciclo), seed))]
for nombre, mover in variantes:
mov, llamadas = contando(mover)
t0 = time.perf_counter()
ciclo = nx.approximation.simulated_annealing_tsp(G, voraz, move=mov, **params)
print(f"networkx, {nombre}: {longitud(ciclo[:-1], D1):.3f} con {llamadas[0]} propuestas en {time.perf_counter() - t0:.2f} s")
B = llamadas[0]
T_final = 0.02 * 0.9 ** (B // 200) # la temperatura a la que terminó networkx
t0 = time.perf_counter()
nuestro = recocido(D1, voraz[:-1], B, 0.02, T_final, 8, 0)
print(f"el nuestro, con esas {B} propuestas, la misma temperatura y el mismo inicio: {nuestro:.3f} en {time.perf_counter() - t0:.3f} s")for s in (1, 2):
mov, llamadas = contando(lambda ciclo, seed: swap_two_nodes(list(ciclo), seed))
ciclo = nx.approximation.simulated_annealing_tsp(G, voraz, move=mov, **{**params, "seed": s})
B = llamadas[0]
nuestro = recocido(D1, voraz[:-1], B, 0.02, 0.02 * 0.9 ** (B // 200), 8, s)
print(f"semilla {s}: networkx (copia) {longitud(ciclo[:-1], D1):.3f} con {B} propuestas; el nuestro, con las mismas, {nuestro:.3f}")With the default move, networkx returns exactly the greedy tour, 13.143, and stops after 2200 proposals: with the cycle drifting due to rejected swaps, no proposal improves stored cost and the no-improvement counter expires. Applying the same swap to a copy makes the algorithm behave as documented and fall to 12.528 with 12 800 proposals. Our annealing, with the same 12 800 proposals, temperature and start, reaches 11.291 in a tiny fraction of the time (over a hundred times less in the cell). The other two seeds tell the same story and add a detail: with seed 1, networkx falls to 12.381 in 9600 proposals and ours to 11.244; with seed 2, networkx does not improve greedy in its first ten passes and stops after 2200 proposals, enough for ours to reach 11.728. With a “passes without improvement” stopping criterion, actual budget is random: hence on each seed we give ours exactly the proposals networkx used. Quality difference comes from neighborhood (2-opt with candidates versus city swaps, which remove and add up to four edges and from a reasonable tour almost always worsen); time difference from incremental evaluation. You can pass networkx a custom 2-opt move via argument move (returning a new list), improving quality, but each proposal still costs . General lesson: before comparing against a library implementation, check it on a case where you know what should happen.
Continuous annealing versus scipy
In annealing works similarly with a continuous proposal: move one coordinate by a Gaussian step whose size shrinks with temperature. The classic test is the Rastrigin function in ,
with global minimum and a local minimum near each integer-coordinate point: on the order of in the domain. The experiment measures for each method the number of evaluations to reach target , which requires all coordinates in the central basin (any coordinate in another basin contributes at least ). Budget: 20 000 evaluations per run. Methods are our annealing, scipy.optimize.dual_annealing (Tsallis generalized annealing with L-BFGS-B local search after every improvement), and random restarts of L-BFGS-B, the gradient local optimizer without extra help.
import numpy as np, math, time
d, LO, HI = 10, -5.12, 5.12
OBJETIVO, PRESUP = 0.1, 20_000
def rastrigin(x):
x = np.asarray(x)
return 10 * len(x) + float(np.sum(x * x - 10 * np.cos(2 * np.pi * x)))
def recocido_continuo(presupuesto, T0, T1, sigma0, semilla):
"""Recocido en [LO, HI]^d: mueve una coordenada con un paso gaussiano que se encoge con T.
Como Rastrigin es separable, el cambio de energía de mover x_i solo depende de x_i: evaluación en O(1)."""
rng = np.random.default_rng(semilla)
x = rng.uniform(LO, HI, d).tolist()
termino = [xi * xi - 10 * math.cos(2 * math.pi * xi) for xi in x]
f = 10 * d + sum(termino)
alfa, T = (T1 / T0) ** (1 / presupuesto), T0
Z, I, U = rng.normal(size=presupuesto).tolist(), rng.integers(0, d, presupuesto).tolist(), rng.random(presupuesto).tolist()
mejor, llegada = f, None
for k in range(presupuesto):
i = I[k]
xn = min(HI, max(LO, x[i] + (sigma0 * math.sqrt(T / T0) + 0.02) * Z[k]))
tn = xn * xn - 10 * math.cos(2 * math.pi * xn)
dE = tn - termino[i]
if dE <= 0 or U[k] < math.exp(-dE / T):
x[i], termino[i], f = xn, tn, f + dE
mejor = min(mejor, f)
if llegada is None and f <= OBJETIVO:
llegada = k + 1
T *= alfa
return mejor, llegada
ttt = {}
for T0 in (3.0, 10.0):
r = [recocido_continuo(PRESUP, T0, 1e-3, 2.0, s) for s in range(20)]
ttt[f"recocido T0 = {T0:g}"] = [h for _, h in r]
exito = [h for _, h in r if h is not None]
print(f"T0 = {T0:4g}: llega a f ≤ {OBJETIVO} en {len(exito)} de 20 ejecuciones; "
f"evaluaciones hasta llegar: mediana {np.median(exito):.0f}, mín {min(exito)}, máx {max(exito)}")
print(f" valor final: mediana {np.median([m for m, _ in r]):.3f}, peor {max(m for m, _ in r):.3f}")from scipy.optimize import dual_annealing
class Contador:
"""Envuelve f: cuenta evaluaciones y anota cuándo se alcanza el objetivo por primera vez."""
def __init__(self):
self.n, self.llegada, self.mejor = 0, None, np.inf
def __call__(self, x):
self.n += 1
v = rastrigin(x)
self.mejor = min(self.mejor, v)
if self.llegada is None and v <= OBJETIVO:
self.llegada = self.n
return v
t0 = time.perf_counter()
llegadas = []
for s in range(10):
f = Contador()
dual_annealing(f, [(LO, HI)] * d, seed=s, maxfun=PRESUP,
callback=lambda x, v, ctx: f.llegada is not None) # para en cuanto ha llegado
llegadas.append(f.llegada)
ttt["dual_annealing"] = llegadas
ok = [h for h in llegadas if h is not None]
print(f"dual_annealing llega en {len(ok)} de 10; evaluaciones: mediana {np.median(ok):.0f}, mín {min(ok)}, máx {max(ok)}")from scipy.optimize import minimize
res_ms = []
for s in range(2):
f, rng, arranques = Contador(), np.random.default_rng(s), 0
while f.n < PRESUP and f.llegada is None:
minimize(f, rng.uniform(LO, HI, d), method="L-BFGS-B", bounds=[(LO, HI)] * d)
arranques += 1
res_ms.append(f.llegada)
print(f"semilla {s}: {arranques} arranques de L-BFGS-B, {f.n} evaluaciones, mejor valor {f.mejor:.3f}, llegada {f.llegada}")
ttt["reinicios de L-BFGS-B"] = res_ms
# ¿basta con arrancar dentro de la cuenca central? Arranques con |x_i| < w en todas las coordenadas
for w in (0.45, 0.1):
R = [minimize(rastrigin, np.random.default_rng(10 + k).uniform(-w, w, d), method="L-BFGS-B",
bounds=[(LO, HI)] * d) for k in range(20)]
print(f"L-BFGS-B desde |x_i| < {w}: llega a f ≤ {OBJETIVO} en {sum(r.fun <= OBJETIVO for r in R)} de 20; "
f"evaluaciones: mediana {np.median([r.nfev for r in R]):.0f}")
p1 = 1.0 / (HI - LO)
print(f"cota optimista: probabilidad de que un arranque uniforme caiga en la cuenca central ≈ (1/{HI - LO:.2f})^{d} = {p1 ** d:.1e}")import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(7, 3.2))
xs = np.arange(0, PRESUP + 1, 100)
for nombre, h in ttt.items():
h = np.array([np.inf if v is None else v for v in h])
ax.step(xs, [(h <= x).mean() for x in xs], where="post", label=f"{nombre} ({len(h)} ejec.)")
ax.set_xlabel("evaluaciones de f"); ax.set_ylabel(f"P(f ≤ {OBJETIVO} ya alcanzado)")
ax.legend(fontsize=8); plt.tight_layout(); plt.show()The four curves tell four different stories:
dual_annealingreaches the target in all 10 runs, with median 4726 evaluations (2566 to 8437). It combines long jumps from its heavy-tailed visiting distribution with L-BFGS-B local search, exploiting something our annealing does not: inside a basin, Rastrigin is smooth. A qualification measured by the restart cell: the gradient optimizer alone finishes only if it starts very near the bottom. From in all coordinates it reaches the global minimum in 19 of 20 starts, median 110 evaluations (with finite-difference gradients, each gradient costs ); from , still inside the central basin, 0 of 20.- Our annealing with reaches it in 19 of 20, but never before 9237 evaluations: its RTD is a step, not a curve. Arrival time is set by the cooling schedule, which stops jumping between basins only once has fallen enough, around halfway through the budget. Thus an annealing RTD depends on the budget used to configure it: with 40 000 evaluations the step would shift right. Fair comparison requires success rate at several budgets, not just one curve.
- With only 6 of 20 arrive. More temperature is not needed; the opposite: with the same budget, starting hotter spends more evaluations in the phase accepting everything and leaves fewer for the cold phase, making effective cooling faster where it matters.
- L-BFGS-B restarts never arrive: about a hundred starts per run and best value above 11. The cell explains two parts. A uniform start lands in the central basin with probability , so on the order of starts would be needed. Even this is optimistic: even starting inside the basin, L-BFGS-B usually leaves it, because its first gradient-direction step is long compared with basin width and line search accepts as soon as decreases, even in another basin. An optimizer’s attraction basin is not the landscape’s geometric basin.
The general lesson: the winner depends on what structure each method exploits (smoothness within basins, separability, number of basins), exactly as no free lunch predicts.
Common mistakes
Exercises
More than one answer may be correct.
More than one answer may be correct.
Step 1 of 5. Which pairs must be checked?
delta_2opt(t, D, i, j) returning the change in length of closed tour t (city list) when applying 2-opt with 0 <= i < j <= n - 1: remove edges (t[i], t[i+1]) and (t[j], t[(j+1) % n]) and add (t[i], t[j]) and (t[i+1], t[(j+1) % n]), equivalent to reversing segment t[i+1..j]. It must cost O(1): four lookups in distance matrix D (list of lists or array). Also implement aplica_2opt(t, i, j), returning the new tour without modifying t. Tests compare your delta with full recomputation over hundreds of random moves, including those touching the closing edge.def delta_2opt(t, D, i, j):
"""Cambio de longitud del movimiento 2-opt (i, j) en O(1)."""
n = len(t)
a, b = t[i], t[i + 1]
# tu código: la otra arista que se quita y las dos que se ponen
return 0.0
def aplica_2opt(t, i, j):
"""Recorrido nuevo con el tramo t[i+1..j] invertido (sin modificar t)."""
return list(t)Summary
- A local search problem is . You choose the neighborhood, which determines local minima; evaluate its delta incrementally (2-opt in ). In the Euclidean plane, 2-opt local optima have no crossings.
- Eight-queens hill climbing solves of attempts; with restarts, the number of attempts is geometric with mean and expected cost . Restarts pay for heavy tails; Luby’s strategy is universal.
- Fixed-temperature annealing with a symmetric proposal satisfies detailed balance with respect to , which concentrates on global minima as . But equilibration time grows as , so Hajek requires , that is, with : correct but impractical. In practice use geometric cooling with a fixed budget.
- Tabu search moves to the best non-forbidden neighbor even if worse; without memory it cycles, and tenure and aspiration control the tradeoff between breaking cycles and intensifying.
- Local beam shares effort among states and loses diversity; genetic algorithms add crossover, which helps only with representations closed under it and decomposable problems. The schema theorem is a one-generation bound, not a growth law.
- Comparing metaheuristics requires multiple seeds and instances, the same budget in the same units, separate tuning, paired comparison and time-to-target distributions. No free lunch reminds us every advantage comes from problem structure.