TExcelTAD
Home › Optimization › Simulated Annealing

Simulated Annealing

Local methods get stuck in the nearest valley. Simulated annealing escapes by sometimes accepting uphill moves, with a probability that shrinks over time. The idea comes from metallurgy: cooling a metal slowly lets its atoms settle into a low-energy crystal instead of a brittle glass. It is simple, works on discrete and continuous problems, and needs only function values.

The algorithm

From the current state x\mathbf{x}, propose a random neighbour y\mathbf{y}. With Δ=f(y)−f(x)\Delta = f(\mathbf{y}) - f(\mathbf{x}), accept it with the Metropolis probability

P(accept)={1Δ≤0e−Δ/TΔ>0P(\text{accept}) = \begin{cases} 1 & \Delta \le 0 \\ e^{-\Delta/T} & \Delta > 0 \end{cases}

where the temperature TT decreases according to a cooling schedule, e.g. geometric Tk+1=αTkT_{k+1} = \alpha T_k with α\alpha slightly below 1. At high TT almost everything is accepted (exploration); at low TT only improvements are (exploitation).

python · try it yourself
import numpy as np

T_values = (10.0, 1.0, 0.1)
for delta in (0.5, 2.0, 5.0):
    print(f"uphill by {delta}: accept with prob", [round(float(np.exp(-delta / T)), 4) for T in T_values], "at T =", T_values)
uphill by 0.5: accept with prob [0.9512, 0.6065, 0.0067] at T = (10.0, 1.0, 0.1)
uphill by 2.0: accept with prob [0.8187, 0.1353, 0.0] at T = (10.0, 1.0, 0.1)
uphill by 5.0: accept with prob [0.6065, 0.0067, 0.0] at T = (10.0, 1.0, 0.1)

A multimodal function

The Rastrigin function f(x)=10n+∑i(xi2−10cos⁡(2πxi))f(\mathbf{x}) = 10n + \sum_i\left(x_i^2 - 10\cos(2\pi x_i)\right) has a local minimum near every integer point and its global minimum 0 at the origin. Gradient methods stop in whichever valley they start; annealing hops between them:

python · try it yourself
import numpy as np
from scipy.optimize import minimize

f = lambda x: 10 * len(x) + np.sum(x**2 - 10 * np.cos(2 * np.pi * x))
rng = np.random.default_rng(0)
x0 = np.array([3.3, -2.7])
print("BFGS from x0:", np.round(minimize(f, x0, method="BFGS").x, 3), " f =", round(float(minimize(f, x0, method="BFGS").fun), 4))

x, fx = x0.copy(), f(x0); best = (fx, x.copy())
T = 10.0
for k in range(20000):
    y = x + rng.normal(scale=0.5, size=2)
    fy = f(y)
    if fy <= fx or rng.uniform() < np.exp(-(fy - fx) / T):
        x, fx = y, fy
        if fx < best[0]:
            best = (fx, x.copy())
    T *= 0.9995
print("annealing best:", np.round(best[1], 3), " f =", round(float(best[0]), 4), " final T =", f"{T:.1e}")
BFGS from x0: [ 2.985 -2.985]  f = 17.9092
annealing best: [-0.003  0.002]  f = 0.0027  final T = 4.5e-04

A combinatorial problem: the travelling salesman

For discrete problems, a neighbour is a small change of the solution. For a TSP tour, the classic move is 2-opt: reverse a segment of the tour.

python · try it yourself
import numpy as np

rng = np.random.default_rng(1)
n = 30
cities = rng.uniform(0, 100, size=(n, 2))
D = np.linalg.norm(cities[:, None] - cities[None], axis=2)
length = lambda t: D[t, np.roll(t, -1)].sum()

tour = np.arange(n); L = length(tour); start = L
T = 50.0
for k in range(60000):
    i, j = sorted(rng.choice(n, 2, replace=False))
    new = np.r_[tour[:i], tour[i:j + 1][::-1], tour[j + 1:]]       # 2-opt move
    Ln = length(new)
    if Ln <= L or rng.uniform() < np.exp(-(Ln - L) / T):
        tour, L = new, Ln
    T *= 0.9998
print(f"initial tour length {start:.1f}, after annealing {L:.1f}")
initial tour length 1621.6, after annealing 413.5

Tuning

Choice Guidance
initial temperature accept most uphill moves at the start (e.g. 80%)
cooling geometric with α∈[0.95,0.9999]\alpha \in [0.95, 0.9999] per step or per batch of steps
neighbourhood small enough to be local, large enough to move; adapt the step size to keep a target acceptance rate
stopping when TT is tiny or no improvement for a long time; restart from the best point

With a logarithmic schedule Tk=c/log⁡kT_k = c/\log k annealing provably finds a global minimum with probability 1, but that schedule is far too slow; practical schedules give good, not guaranteed, solutions.

In software

  • scipy.optimize.dual_annealing (generalized annealing plus local search), simanneal; annealing heuristics are common in VLSI placement, timetabling and routing.
  • Quantum annealers (D-Wave) apply the same idea to Ising-model formulations of combinatorial problems.

Exercises

Exercise 1: Acceptance probability

At T=2T = 2, what is the probability of accepting a move that increases ff by 1?

Answer

e−0.5≈0.607e^{-0.5} \approx 0.607.

Solution

e−Δ/T=e−1/2e^{-\Delta/T} = e^{-1/2}.

Exercise 2: Cooling time

With T0=10T_0 = 10 and α=0.999\alpha = 0.999, after how many steps is TT below 0.01?

Answer

About 6905.

Solution

10⋅0.999k<0.0110 \cdot 0.999^k < 0.01 gives k>ln⁡0.001ln⁡0.999≈6904.3k > \frac{\ln 0.001}{\ln 0.999} \approx 6904.3.

Exercise 3: SciPy's dual annealing (code)

Minimize the 2D Rastrigin function with scipy.optimize.dual_annealing on [−5,5]2[-5, 5]^2.

Answer

It finds the global minimum at the origin.

Solution
python · try it yourself
import numpy as np
from scipy.optimize import dual_annealing
f = lambda x: 10 * len(x) + np.sum(x**2 - 10 * np.cos(2 * np.pi * x))
r = dual_annealing(f, bounds=[(-5, 5)] * 2, seed=0)
print(np.round(r.x, 6) + 0, round(r.fun, 8) + 0)
[0. 0.] 0.0

Test yourself

In simulated annealing, an uphill move by Δ>0\Delta > 0 is accepted with probability…

  1. 0
  2. 1
  3. e−Δ/Te^{-\Delta/T}
  4. Δ/T\Delta/T

As the temperature decreases, the algorithm…

  1. accepts more uphill moves
  2. accepts fewer uphill moves and behaves like local search
  3. stops evaluating ff
  4. becomes gradient descent with exact steps

A standard neighbourhood move for TSP tours is…

  1. 2-opt: reversing a segment of the tour
  2. adding a city
  3. sorting the cities
  4. a gradient step