Module contents
Lesson 4 of 23Core 90 min

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 nn cities there are (n−1)!/2(n-1)!/2 distinct tours; for n=200n = 200, on the order of 1037210^{372}.
  • 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 1037210^{372} 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 Rn\R^n and minima are recognized by the gradient and critical-point classification; here you choose what “near” means by choosing NN, and there are no derivatives. The same state may be a local minimum under one neighborhood and not another. If N(s)=SN(s) = S for every ss, 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 t=(t0,t1,…,tn−1)t = (t_0, t_1, \dots, t_{n-1}) of cities, with closing edge (tn−1,t0)(t_{n-1}, t_0).

  • Swap. Exchange two cities’ positions. It removes up to four edges and adds four; there are (n2)\binom{n}{2} neighbors.
  • 2-opt. Choose two nonadjacent edges, (ti,ti+1)(t_i, t_{i+1}) and (tj,tj+1)(t_j, t_{j+1}) with i<ji < j, remove them and reconnect as (ti,tj)(t_i, t_j) and (ti+1,tj+1)(t_{i+1}, t_{j+1}). To retain a cycle, the intermediate segment must be traversed backward, so the move reverses ti+1,…,tjt_{i+1}, \dots, t_j. Excluding pairs of adjacent edges (which change nothing), there are n(n−3)/2n(n-3)/2 neighbors: 19 70019\,700 for n=200n = 200.

The value of 2-opt is the cost of evaluating a neighbor. If DD is the distance matrix, the length change depends only on the four edges removed and added:

Δij=D(ti,tj)+D(ti+1,tj+1)−D(ti,ti+1)−D(tj,tj+1),\Delta_{ij} = D(t_i, t_j) + D(t_{i+1}, t_{j+1}) - D(t_i, t_{i+1}) - D(t_j, t_{j+1}),

four table lookups, O(1)\bigO(1), versus O(n)\bigO(n) 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 O(1)\bigO(1), but applying the move to a tour stored as an array costs O(j−i)\bigO(j - i) 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 O(n)\bigO(\sqrt n).

2-opt also has a clean geometric property.

Proof

Let (a,b)(a, b) and (c,d)(c, d) be the edges, traversed in order a→b→⋯→c→da \to b \to \cdots \to c \to d, and let XX be the intersection of segments abab and cdcd. 2-opt adds (a,c)(a, c) and (b,d)(b, d). By the triangle inequality, ∣ac∣≤∣aX∣+∣Xc∣\abs{ac} \le \abs{aX} + \abs{Xc} and ∣bd∣≤∣bX∣+∣Xd∣\abs{bd} \le \abs{bX} + \abs{Xd}, and summing,

∣ac∣+∣bd∣≤(∣aX∣+∣Xb∣)+(∣cX∣+∣Xd∣)=∣ab∣+∣cd∣,\abs{ac} + \abs{bd} \le (\abs{aX} + \abs{Xb}) + (\abs{cX} + \abs{Xd}) = \abs{ab} + \abs{cd},

because XX is on both segments. Equality would require a,X,ca, X, c and b,X,db, X, d to be collinear, and with XX interior to abab this would align aa, bb and cc, which we excluded. Therefore Δ<0\Delta < 0.

∎

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 200200 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 s±1s \pm 1, s±2s \pm 2 or s±3s \pm 3 with equal probability): orange accepts only downhill moves, blue follows the Metropolis criterion defined below.

InteractiveParticles in a rugged landscape
global minimum
Mean annealing-particle occupancy since step 300 versus Boltzmann
state s = 0s = 199
  • annealing (Metropolis)
  • hill climbing (downhill only)
  • exact Boltzmann, πT(s)∝e−E(s)/T\pi_T(s) \propto e^{-E(s)/T}
  • global shape handles
Mode
0.200
0.16
30
Step kk0
Current temperature0.2000
TV distance to Boltzmann (time average)0.500
In global minimum basin: annealing0 %
In global minimum basin: hill climbing0 %
Same according to Boltzmann at this TT13 %
The time average approaches Boltzmann, more slowly as TT decreases: compare the distance with that at T=0.2T = 0.2.
Orange particles perform hill climbing: they stay at the first local minimum they find, almost always the closest to where they landed. Blue particles anneal. With ‘Fixed temperature’, bars show mean blue-particle occupancy from step 300 and the stepped line is the exact Boltzmann distribution at that temperature. At T=0.2T = 0.2 total variation distance drops below 0.050.05 in a few thousand steps, but Boltzmann barely favors the global minimum; lower to T=0.03T = 0.03 and Boltzmann puts over 90% of its mass there, while occupancy remains far away. In ‘Cooling’, temperature falls geometrically from T0T_0: with a fast rate (1−α=10−11 - \alpha = 10^{-1}), blue particles end like orange ones, around 5% in the global minimum's basin; with a slow rate (10−410^{-4}), over half. The deceptive wide valley is designed so almost all orange particles fail.

Hill climbing and its variants

The neighbor-selection rule gives variants:

  • Steepest descent: evaluate all of N(s)N(s) and choose the best, breaking ties randomly. Each step costs ∣N(s)∣\abs{N(s)} evaluations.
  • First improvement: traverse N(s)N(s) 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 E(s′)=E(s)E(s') = E(s), 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, 88=16 777 2168^8 = 16\,777\,216 states, 56 neighbors) from random boards, without and with up to 100 consecutive sideways moves. Energy is the number hh of attacking queen pairs. Notice incremental evaluation: with queen counts per row and diagonal, the change in hh when moving a queen is calculated in O(1)\bigO(1).

[ ]Eight queens: hill climbing with and without sideways movesBrowser
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 13.8 %13.8\,\% 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 94 %94\,\%, 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 pp, the number KK of attempts until the first success follows a geometric distribution, that of repeated Bernoulli trials:

P(K=k)=(1−p)k−1p,P(K≤k)=1−(1−p)k,E[K]=1p.\Pr(K = k) = (1-p)^{k-1}p, \qquad \Pr(K \le k) = 1 - (1-p)^k, \qquad \E[K] = \frac{1}{p}.

With p=0.138p = 0.138, 1/p=7.251/p = 7.25 attempts are needed on average, and after kk 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 K−1K - 1 attempts fail and the last succeeds. Conditional on K=kK = k, attempts are independent and each has the distribution conditional on its outcome, so E[∑i≤KCi∣K=k]=(k−1)cfr+ceˊx\E[\sum_{i \le K} C_i \given K = k] = (k-1)c_{\text{fr}} + c_{\text{éx}}. Taking the expectation over KK, with E[K−1]=1/p−1=(1−p)/p\E[K - 1] = 1/p - 1 = (1-p)/p, gives the formula.

∎

Using the cell’s figures, 4.1+(0.862/0.138)⋅3.1≈234.1 + (0.862/0.138)\cdot 3.1 \approx 23 steps without sideways moves and 19.4+(0.06/0.94)⋅54.5≈2319.4 + (0.06/0.94)\cdot 54.5 \approx 23 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.

InteractiveThe arithmetic of restarts
Last attempt: 2 conflicts
Conflicting pairs at completion
6202621155221304
Probability of solving the problem in at most kk attempts
00.250.50.751110203040attempts k
  • geometric formula using measured p^\hat p
  • measured: runs of attempts to first success (62 runs)
  • solved attempts (0 conflicts)
  • attacked queens
500
10
Measured success rate p^\hat p12.4 % ± 2.9 %
Expected attempts 1/p^1/\hat p8.06
Mean steps: success / failure3.9 / 3.1
Expected steps to solve25.9
Success in 10 attempts: 1−(1−p^)k1 - (1 - \hat p)^k73.4 %
Success in 10 attempts: measured80.6 %
Run more attempts or change the seed: the measured rate fluctuates around a fixed value.
Each attempt is real steepest hill climbing, run in your browser from a random board. The histogram counts conflicts at the end of each attempt and the board shows the last, with attacked queens in red. Below is the probability of solving in at most kk attempts: the curve is 1−(1−p^)k1 - (1-\hat p)^k using the measured rate, and points come from splitting the actual sequence of attempts into runs ending in success. Move kk until probability exceeds 95% and enable sideways moves: how many restarts do you need now?

The theorem generalizes to a common situation: an algorithm that could eventually solve the problem if left running, but with highly variable running time TT. If cut off and restarted every tt steps, each attempt costs min⁡(T,t)\min(T, t) and succeeds with probability F(t)=P(T≤t)F(t) = \Pr(T \le t), and the same argument gives E[coste]=E[min⁡(T,t)]/F(t)\E[\text{coste}] = \E[\min(T, t)] / F(t). Restarting pays when the distribution of TT 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 1,1,2,1,1,2,4,1,1,2,…1, 1, 2, 1, 1, 2, 4, 1, 1, 2, \dots guarantees expected cost within a logarithmic factor of the best fixed-cutoff strategy. If TT 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 Δ=0.3\Delta = 0.3 and T=0.1T = 0.1, the probability is e−3≈0.05e^{-3} \approx 0.05; with T=1T = 1, e−0.3≈0.74e^{-0.3} \approx 0.74. When T→∞T \to \infty, the algorithm is a random walk on the neighborhood graph; when T→0T \to 0, stochastic first-improvement hill climbing that also accepts sideways moves (Δ=0\Delta = 0). 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 TT, annealing is a homogeneous Markov chain on SS with transition matrix

PT(s,s′)=q(s,s′) min⁡{1,e−(E(s′)−E(s))/T}(s′≠s),PT(s,s)=1−∑s′≠sPT(s,s′).P_T(s, s') = q(s, s')\,\min\{1, e^{-(E(s') - E(s))/T}\} \quad (s' \neq s), \qquad P_T(s, s) = 1 - \sum_{s' \neq s} P_T(s, s').

What distribution does it converge to? Consider the simplest case, two neighboring states aa and bb with E(b)=E(a)+ΔE(b) = E(a) + \Delta, Δ>0\Delta > 0, and a symmetric proposal. The transition from aa to bb has probability q e−Δ/Tq\,e^{-\Delta/T}, and from bb to aa probability qq. At equilibrium, flow from aa to bb and from bb to aa must balance: π(a) q e−Δ/T=π(b) q\pi(a)\,q\,e^{-\Delta/T} = \pi(b)\,q, that is, π(b)/π(a)=e−Δ/T=e−(E(b)−E(a))/T\pi(b)/\pi(a) = e^{-\Delta/T} = e^{-(E(b) - E(a))/T}. The chain allocates its time according to energy.

The first part follows from detailed balance, πT(s)PT(s,s′)=πT(s′)PT(s′,s)\pi_T(s)P_T(s, s') = \pi_T(s')P_T(s', s), 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, q(s,s′)=1/∣N(s)∣≠1/∣N(s′)∣q(s, s') = 1/\abs{N(s)} \neq 1/\abs{N(s')} and the stationary distribution is no longer Boltzmann. The Metropolis-Hastings correction accepts with min⁡{1,e−Δ/T q(s′,s)/q(s,s′)}\min\{1, e^{-\Delta/T}\,q(s', s)/q(s, s')\}. 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 S∗⊆SS^* \subseteq S is the set of global minima and E∗=min⁡EE^* = \min E, for s∉S∗s \notin S^*

πT(s)πT(s∗)=e−(E(s)−E∗)/T→T→00,\frac{\pi_T(s)}{\pi_T(s^*)} = e^{-(E(s) - E^*)/T} \xrightarrow[T \to 0]{} 0,

so πT\pi_T concentrates uniformly on S∗S^*: πT(s∗)→1/∣S∗∣\pi_T(s^*) \to 1/\abs{S^*}. 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 T=0.2T = 0.2 occupancy matches Boltzmann in a few thousand steps, but that Boltzmann spreads mass across the landscape; at T=0.03T = 0.03 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 s=10s = 10 (E=0.3E = 0.3), a barrier at s=20s = 20 (E=1E = 1), and the global minimum at s=30s = 30 (E=0E = 0). It builds matrix PTP_T, checks πT\pi_T is stationary and satisfies detailed balance, and measures the spectral gap 1−λ21 - \lambda_2 controlling convergence speed: distance to πT\pi_T decreases as λ∗k\lambda_*^k, with λ∗=max⁡(λ2,∣λmin⁡∣)\lambda_* = \max(\lambda_2, \abs{\lambda_{\min}}), and in this chain the most negative eigenvalue never falls below −0.94-0.94, so λ2\lambda_2 dominates, very close to 1.

[ ]The exact Metropolis chainBrowser
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 0.0400.040 to T=1T = 1 to 0.7070.707 to T=0.05T = 0.05. The fourth is the price: the spectral gap drops from 2.5×10−32.5 \times 10^{-3} to 8.8×10−88.8 \times 10^{-8}, so relaxation time 1/(1−λ2)1/(1-\lambda_2) increases from about 400 steps to about eleven million. The last column confirms that the most negative eigenvalue (between −0.93-0.93 and −0.27-0.27) does not compete with λ2\lambda_2. The slope of −log⁡(1−λ2)-\log(1 - \lambda_2) against 1/T1/T approaches 0.70.7 as TT falls (0.6110.611 between 0.050.05 and 0.10.1, 0.6750.675 between 0.0250.025 and 0.040.04): the gap closes as e−0.7/Te^{-0.7/T} times a prefactor only weakly dependent on TT. 0.70.7 is the height needed to escape the local well, the Arrhenius law of physical chemistry: escape time grows as eprofundidad/Te^{\text{profundidad}/T}.

Cooling schedules and Hajek’s result

The dilemma is clear. At high TT the chain equilibrates quickly, but equilibrium does not favor minima; at low TT equilibrium is at minima, but reaching it takes exponential time. Annealing lowers TT gradually hoping to follow equilibrium. Common schedules are:

  • Geometric: Tk=T0 αkT_k = T_0\,\alpha^k with α\alpha slightly less than 1 (or TT constant for blocks of LL steps and multiplied by α\alpha between blocks). This is the practical standard; to go from T0T_0 to T1T_1 in BB steps, use α=(T1/T0)1/B\alpha = (T_1/T_0)^{1/B}.
  • Logarithmic: Tk=c/log⁡(k+1)T_k = c/\log(k + 1). This has a theoretical guarantee.
  • Adaptive: adjust α\alpha 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 ss as the least height hh such that from ss one can reach a state of energy less than E(s)E(s) along a neighborhood-graph path where energy never exceeds E(s)+hE(s) + h. Let d∗d^* be the greatest depth among all nonglobal local minima.

The second part follows from the first: e−d∗log⁡(k+1)/c=(k+1)−d∗/ce^{-d^*\log(k+1)/c} = (k+1)^{-d^*/c}, and the series diverges exactly when d∗/c≤1d^*/c \le 1. The intuition is the cell’s: escaping the deepest well at temperature TT takes on the order of ed∗/Te^{d^*/T} 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 Tk=c/log⁡(k+1)T_k = c/\log(k + 1), temperature halves when log⁡(k+1)\log(k+1) doubles, that is, when k+1k + 1 is squared: if you reach T=c/10T = c/10 at step e10−1≈22 025e^{10} - 1 \approx 22\,025, you reach T=c/20T = c/20 at step e20−1≈4.9×108e^{20} - 1 \approx 4.9 \times 10^8. Moreover d∗d^* 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 T0T_0 should be on the order of typical Δ\Delta of worsening moves.

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 ss the best neighbor s′s' is the least-worsening one, say by δ>0\delta > 0. From s′s', returning to ss improves by δ\delta and is often the best available move: search oscillates between ss and s′s' 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).
Interactive2-opt live
Hill climbing (steepest)
L = 4.328 · 0 crossings · local optimum at iteration 20
Simulated annealing
L = 4.263 · 0 crossings · T₀ = 0.113
Tabu search
L = 4.328 · 0 crossings · tenure 0
  • hill climbing
  • annealing
  • tabu (tenure 0)
  • pair of crossing edges
0 iterations
120
120 / 120
0.50
0.50
Cities nn / neighborhood M=n(n−3)/2M = n(n-3)/230 / 405
Moves evaluated by each method48.6 thousand
Best length: hill climbing4.328
Best length: annealing4.263
Best length: tabu4.328
Tabu cycle at endperiod 2
Since iteration 19, tabu repeats the same 2 tours: without memory, the best move from the neighbor undoes the previous one. Increase tenure.
Three searches with the same 2-opt neighborhood, from the same random tour and the same evaluated-move budget: steepest hill climbing, annealing with geometric cooling (from T0T_0 to T0/1000T_0/1000, with T0T_0 calibrated from initial-tour worsening moves), and tabu forbidding restoration of removed edges. Red edges are crossing pairs: once the tour is a 2-opt local optimum they disappear. Initially the display shows the end of a run with tenure 0, i.e. no memory: read the period-2 cycle into which tabu fell. Raise tenure to 5: the cycle lengthens but remains; at 10 it disappears. Click panels to add cities and change map: does the same method always win?

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, M=n(n−3)/2M = n(n-3)/2 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 KK nearest neighbors, because a long edge is rarely part of a good tour.

Local beam and genetic algorithms

Local beam

This differs from kk parallel restarts: the kk 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 kk best neighbors even if worse than current states, the beam keeps moving where hill climbing would stop. Stochastic beam search chooses kk successors randomly with probability increasing with quality, preserving more diversity and essentially performing natural selection.

[ ]Local beam versus restarts on eight queensBrowser
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 k=2k = 2 solves 93 out of 100 problems in 30 steps with about 909, and with k=5k = 5 or 1010 solves all, but with more evaluations (1481 and 2167): each step costs 56k56k evaluations, and beyond some kk the beam pays more than it gains. Honest comparison with k=2k = 2 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 cc, 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 1/(nc)1/\binom{n}{c}. 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.

InteractiveCrossing two tours
Parent P1
5
6
0
10
1
9
11
7
4
2
3
8
Parent P2
7
3
9
0
6
11
10
1
5
8
4
2
Child
5
6
0
10
6
11
10
1
5
8
4
2
P101234567891011
P201234567891011
Child01234567891011
  • positions copied from P1
  • repeated city in child / missing on wheel
Crossover
4
This childnot a tour
Repeated / missing cities3 / 3
Valid children in 2000 crossovers: one point2.3 %
Valid children in 2000 crossovers: OX100.0 %
Child edges present in a parent: OX80 %
Same for a random tour33 %
One-point crossover joins the beginning of P1 to the end of P2: the result is rarely a permutation. Repairing it afterward destroys precisely what was meant to be inherited.
Two parents are 12-city tours on a wheel. With one-point crossover the child repeats cities (red cells) and omits others (red circles on the wheel), so it is not even a tour; readouts show the fraction of valid children in 2000 crosses of random parents (about 2% with one-point). Switch to OX and move the segment: the child is always a permutation, retains the segment copied from P1, and about four in five of its edges were already in a parent, versus one in three in a random tour.
[ ]Permutation crossovers and a genetic algorithm with OXBrowser
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}")
[ ]A genetic algorithm with OX versus annealingBrowser
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 0.66 %0.66\,\% of one-point crossover children are tours (the exact formula, averaging 1/(nc)1/\binom{n}{c} across cuts, gives 0.59 %0.59\,\%; 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 ℓ\ell, a schema HH is a template over {0,1,∗}\{0, 1, *\}, for example H=1∗∗0∗1H = 1{*}{*}0{*}1, representing all strings matching its fixed positions. Its order o(H)o(H) is the number of fixed positions (here 3) and its defining length δ(H)\delta(H) the distance between first and last fixed positions (here 5). Let m(H,t)m(H, t) be the number of generation tt individuals belonging to HH, f^(H,t)\hat f(H, t) their mean fitness and fˉ(t)\bar f(t) the population mean.

With roulette selection, each of PP offspring has a parent in HH with probability ∑i∈Hfi/∑jfj=m(H,t)f^(H,t)/(Pfˉ(t))\sum_{i \in H} f_i / \sum_j f_j = m(H,t)\hat f(H,t)/(P \bar f(t)), so selection alone produces m(H,t) f^(H,t)/fˉ(t)m(H,t)\,\hat f(H,t)/\bar f(t) copies on average. One-point crossover with probability pcp_c can break HH only if the cut falls between its first and last fixed positions, with probability δ(H)/(ℓ−1)\delta(H)/(\ell - 1). Mutation at rate pmp_m per position preserves the o(H)o(H) fixed positions with probability (1−pm)o(H)≥1−o(H) pm(1 - p_m)^{o(H)} \ge 1 - o(H)\,p_m. Combining the three bounds,

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

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 HH 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. f^(H,t)\hat f(H, t) is the mean fitness of HH 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 f^/fˉ\hat f / \bar f constant, generally false.
  • A schema’s fitness depends on the population sampling it, not on its 2ℓ−o(H)2^{\ell - o(H)} 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 Jumpk\mathrm{Jump}_k, whose optimum lies beyond a jump of Hamming distance kk, a mutation-only algorithm such as (1+1) EA needs expected time Θ(nk)\Theta(n^k), while a genetic algorithm (μ+1)(\mu + 1) with uniform crossover solves it in O(μn2k3+4k/pc)\bigO(\mu n^2 k^3 + 4^k/p_c). One qualification: the result requires very small crossover probability pc=O(1/(kn))p_c = \bigO(1/(kn)); Opris, Lengler and Sudholt (2024) extended it to realistic values pc=O(1/k)p_c = \bigO(1/k), with populations μ=Ω(kn)\mu = \Omega(kn) and a tight bound O(μnlog⁡k+4k/pc)\bigO(\mu n \log k + 4^k/p_c).

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:

  1. Several seeds and instances. One run per algorithm is a sample of size one from a distribution. With rr seeds on each of mm instances you have a real sample, and it is wise to use the same initial state (or seed) for all algorithms on each (instancia,semilla)(\text{instancia}, \text{semilla}) pair so the comparison is paired and instance variability does not hide differences (see paired tests).
  2. 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.
  3. Tune on separate instances. Choosing T0T_0 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.
  4. Distributions, not means. For decision problems (reaching a target), use the time-to-target distribution: for each run, evaluations TT to reach a given quality, and empirical curve P(T≤t)\Pr(T \le t). 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 ff 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.

[ ]2-opt with incremental evaluationBrowser
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 ii and one of K=8K = 8 cities nearest tit_i, and propose the 2-opt move creating their edge; almost no proposal is absurd. And T0T_0 and T1T_1 are chosen on a tuning instance (seed 100) not used for comparison. This proposal is not symmetric: tjt_j being among the KK neighbors of tit_i 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.

[ ]Simulated annealing: implementation and tuningBrowser
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.

[ ]Annealing: two instances, three seedsBrowser
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.

[ ]Tabu search and descent with restartsBrowser
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}")
[ ]Tabu and descent with restarts: two instances, three seedsBrowser
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)")
[ ]Tabu with ten times more evaluations: instance 1Browser
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)
[ ]Tabu with ten times more evaluations: instance 2Browser
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 (instancia,semilla)(\text{instancia}, \text{semilla}), how often annealing wins, and the Wilcoxon signed-rank test. With six pairs the smallest possible two-sided pp is 2/26=0.0312/2^6 = 0.031, achieved when one method wins them all.

[ ]Paired comparisonBrowser
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 p=0.031p = 0.031, 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, O(n)\bigO(n) 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.

[ ]networkx versus our implementationBrowser
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")
[ ]networkx (on a copy) versus ours: two more seedsBrowser
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 O(n)\bigO(n). General lesson: before comparing against a library implementation, check it on a case where you know what should happen.

Continuous annealing versus scipy

In Rd\R^d 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 [−5.12,5.12]10[-5.12, 5.12]^{10},

f(x)=10d+∑i=1d(xi2−10cos⁡(2πxi)),f(\vb{x}) = 10d + \sum_{i=1}^{d}\big(x_i^2 - 10\cos(2\pi x_i)\big),

with global minimum f(0)=0f(\vb{0}) = 0 and a local minimum near each integer-coordinate point: on the order of 111011^{10} in the domain. The experiment measures for each method the number of ff evaluations to reach target f≤0.1f \le 0.1, which requires all coordinates in the central basin (any coordinate in another basin contributes at least 0.990.99). 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.

[ ]Rastrigin 10D: annealing from scratchBrowser
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}")
[ ]Rastrigin 10D: scipy.optimize.dual_annealingBrowser
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)}")
[ ]Rastrigin 10D: L-BFGS-B restartsBrowser
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}")
[ ]Time-to-target distributionsBrowser
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_annealing reaches 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 ∣xi∣<0.1\abs{x_i} < 0.1 in all coordinates it reaches the global minimum in 19 of 20 starts, median 110 evaluations (with finite-difference gradients, each gradient costs d+1=11d + 1 = 11); from ∣xi∣<0.45\abs{x_i} < 0.45, still inside the central basin, 0 of 20.
  • Our annealing with T0=3T_0 = 3 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 TT 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 T0=10T_0 = 10 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 (1/10.24)10≈7.9×10−11(1/10.24)^{10} \approx 7.9 \times 10^{-11}, so on the order of 101010^{10} 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 ff 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

NumericExpected attempts
Each independent random-restart hill-climbing attempt solves the problem with probability p=0.14p = 0.14. What is the expected number of attempts until solved, including the successful one?
NumericTwenty restarts
With the same p=0.14p = 0.14 per attempt, what is the probability of solving within 20 attempts?
NumericAn accepted uphill move
Annealing is at temperature T=0.1T = 0.1 and proposes a move worsening energy by Δ=0.3\Delta = 0.3. With what probability is it accepted?
NumericSteps of geometric cooling
Annealing starts at T0=10T_0 = 10 and multiplies temperature by α=0.999\alpha = 0.999 at each step. What is the smallest number of steps kk with Tk≤0.01T_k \le 0.01?
NumericThe slow logarithmic schedule
With schedule Tk=c/log⁡(1+k)T_k = c/\log(1 + k) (natural logarithm), temperature is c/10c/10 at step k10=e10−1k_{10} = e^{10} - 1. At what step is it c/20c/20? Give scientific notation (for example, 4.85e8).
QuizEnergy and neighborhood for a timetable
You will use annealing to solve a timetable problem: 300 classes, each in a time slot and room. Hard constraints: no teacher, group or room can have two classes simultaneously. Soft constraints: minimize group idle hours (cost 1 each) and honor teachers’ time preferences (cost 1 per violation; total soft cost at most 2000). Which design is correct?
QuizWhat no free lunch does and does not say
Which statements correctly follow from Wolpert and Macready’s no-free-lunch theorem?

More than one answer may be correct.

QuizA paper comparing metaheuristics
A paper presents a new traveling-salesperson algorithm X and compares it with annealing. Which details by themselves invalidate the conclusion “X is better than annealing”?

More than one answer may be correct.

QuizIs a genetic algorithm worthwhile?
On which problem is crossover in a genetic algorithm most plausibly helpful over good annealing at the same budget?
ProofFixed-temperature annealing and Boltzmann
Prove: Let SS be finite, T>0T > 0 and qq a symmetric proposal, q(s,s′)=q(s′,s)q(s, s') = q(s', s). The fixed-temperature annealing chain, PT(s,s′)=q(s,s′)min⁡{1,e−(E(s′)−E(s))/T}P_T(s, s') = q(s, s')\min\{1, e^{-(E(s') - E(s))/T}\} for s′≠ss' \neq s, satisfies detailed balance with respect to πT(s)=e−E(s)/T/ZT\pi_T(s) = e^{-E(s)/T}/Z_T, so πT\pi_T is stationary.
0
Prove that πT(s)PT(s,s′)=πT(s′)PT(s′,s)\pi_T(s)P_T(s, s') = \pi_T(s')P_T(s', s) for every pair s,s′s, s', and deduce that πTPT=πT\pi_T P_T = \pi_T.

Step 1 of 5. Which pairs must be checked?

CodeThe 2-opt delta and its test
Implement 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)
Shift+Enter to run

Summary

Key idea
When only the final state matters, local search traverses a landscape defined by a neighborhood and energy: hill climbing descends to the first local minimum, annealing accepts uphill moves with probability e−Δ/Te^{-\Delta/T} and at fixed temperature samples Boltzmann, tabu moves uphill with memory to prevent backtracking, and genetic algorithms only win when crossover combines parts meaningful on their own.
  • A local search problem is (S,N,E)(S, N, E). You choose the neighborhood, which determines local minima; evaluate its delta incrementally (2-opt in O(1)\bigO(1)). In the Euclidean plane, 2-opt local optima have no crossings.
  • Eight-queens hill climbing solves 13.8 %13.8\,\% of attempts; with restarts, the number of attempts is geometric with mean 1/p1/p and expected cost ceˊx+1−ppcfrc_{\text{éx}} + \frac{1-p}{p}c_{\text{fr}}. Restarts pay for heavy tails; Luby’s strategy is universal.
  • Fixed-temperature annealing with a symmetric proposal satisfies detailed balance with respect to πT∝e−E/T\pi_T \propto e^{-E/T}, which concentrates on global minima as T→0T \to 0. But equilibration time grows as eprofundidad/Te^{\text{profundidad}/T}, so Hajek requires ∑ke−d∗/Tk=∞\sum_k e^{-d^*/T_k} = \infty, that is, Tk=c/log⁡(k+1)T_k = c/\log(k+1) with c≥d∗c \ge d^*: 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 kk 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.