Sub topic 13
Worked example: simulated annealing
This chapter applies the whole borrowing process to one real case. It assumes you have read the earlier chapters on source and target domains, structure mapping, inference transfer, adaptation, and evaluation. You should be able to read short Python programs. Here you follow one idea from metallurgy into optimization and note at each step what the analogy supplies and what you must supply yourself.
The target problem
Suppose you want to minimize a cost function. The function may be the length of a delivery route, the number of conflicts in a timetable, or a simple curve. You can evaluate the cost of any candidate and you can generate a slightly changed candidate (a neighbor). You cannot solve the problem directly.
The obvious method is greedy descent. Start somewhere, try a neighbor, keep it if the cost drops, and repeat. Greedy descent has a known failure: it stops in a local minimum. This is a point where every nearby candidate is worse, even though a much better solution exists elsewhere.
Restated abstractly, in the style of the earlier abstraction chapter: a searcher moves through a landscape of states, wants low cost, and gets trapped in shallow valleys because it only ever accepts downhill moves. This sentence contains no mention of routes or timetables, so it can be matched against other fields.
The source domain: annealing in metallurgy
Annealing is a heat treatment for metal. A smith heats the metal until its atoms move freely, then cools it slowly. During slow cooling the atoms have time to settle into an orderly, low-energy crystal arrangement. If the metal is cooled quickly (quenched), the atoms freeze into a disordered, higher-energy arrangement with internal stress.
The relations that matter are these:
- At high temperature, atoms often move into higher-energy arrangements, so the system explores widely.
- At low temperature, such moves become rare, so the system settles.
- Cooling slowly lets the system escape poor arrangements early and commit to a good one late.
- Cooling quickly freezes whatever arrangement the system happens to be in.
Quenching resembles greedy descent: it locks in the first valley it finds. Slow cooling is the part worth borrowing.
Building the mapping
The mapping aligns entities first, then checks that the relations between them still make sense.
| Source (cooling metal) | Target (optimization) |
|---|---|
| Arrangement of atoms | Candidate solution `x` |
| Energy of the arrangement | Cost of the candidate |
| Small random atomic movement | Neighbor move |
| Temperature | Willingness to accept a worse move |
| Cooling schedule | Rule for shrinking that willingness |
| Stable low-energy crystal | Good final solution |
The entities are only half of the mapping. The relations carry the idea: higher temperature makes uphill moves more likely, and lowering temperature gradually shifts the system from exploring to settling. A mapping that matched only the nouns (atoms to variables) would transfer nothing useful.
Transferring the inferences
Transfer means rewriting source relations in target terms and treating the results as candidate claims. Each claim still needs checking.
- Source: quenching traps the system in a poor arrangement. Candidate: a searcher that only accepts improvements will get trapped. This matches what you already observed about greedy descent, so the analogy is consistent with evidence.
- Source: high temperature allows uphill moves. Candidate: allow some worse moves in the search.
- Source: slow cooling gives a better final state. Candidate: start permissive and become strict gradually.
Claims 2 and 3 are new, and they are the payoff. They tell you to change the acceptance rule and to add a schedule. Neither follows from greedy descent alone.
Adapting the borrowed solution
The source does not tell you how to compute an acceptance probability in code. Physics offers a hint: the chance of a move that raises energy by delta at temperature T falls off like exp(-delta / T). This is the Metropolis rule. Adopting it is an adaptation decision, and it has useful properties here:
- A tiny
deltais accepted almost always, because the exponent is near zero. - A large
deltais accepted rarely. - A small
Tmakes every uphill move unlikely, so the search turns greedy as it cools.
The target also forces choices the source never faced:
- Temperature has no physical units. Its scale must match your cost differences. If typical uphill
deltais about 10, a start temperature of 0.01 will behave like greedy descent. A start of 10,000 will behave like a random walk. - The neighbor function is yours to design. In a metal, atoms move by physics. In a search you must pick a move size. Too large and the search jumps randomly. Too small and it cannot cross valleys.
- Remember the best state. A real crystal ends in whatever state it is in. A search can wander out of a good state while the temperature is still high, so the code stores the best candidate seen.
- The cooling rate is a tunable constant. Multiplying the temperature by 0.999 each step is a common geometric schedule, but nothing in metallurgy dictates it.
Running it
The program below compares greedy descent with annealing. Both use the same function. Greedy descent is simulated by a temperature so small that worse moves are never accepted, and a cooling factor of 1.0 so that it stays that way.
The cost x**4 - 8*x**2 + 3*x has two valleys. The shallow one has its minimum near x = 1.90 with cost about -10.15. The deep one has its minimum near x = -2.09 with cost about -22.2. A hill between them peaks near x = 0.19 at cost about 0.28, so a searcher in the shallow valley must climb roughly 10 cost units to escape.
import math
import random
def anneal(cost, neighbor, x, temp=10.0, cooling=0.999, steps=20000):
"""Minimize cost(x) by accepting worse moves with probability exp(-delta/temp)."""
cost_x = cost(x)
best, best_cost = x, cost_x
for _ in range(steps):
candidate = neighbor(x)
cost_c = cost(candidate)
delta = cost_c - cost_x
if delta <= 0 or random.random() < math.exp(-delta / temp):
x, cost_x = candidate, cost_c
if cost_x < best_cost:
best, best_cost = x, cost_x
temp *= cooling
return best
def cost(x):
return x**4 - 8 * x**2 + 3 * x
def neighbor(x):
return x + random.uniform(-0.5, 0.5)
random.seed(1)
start = 2.0 # inside the shallow valley
greedy = anneal(cost, neighbor, start, temp=1e-9, cooling=1.0)
annealed = anneal(cost, neighbor, start)
print("greedy x =", round(greedy, 2), "cost =", round(cost(greedy), 2))
print("annealed x =", round(annealed, 2), "cost =", round(cost(annealed), 2))The greedy run stays in the shallow valley, near x = 1.90. The annealed run usually ends in the deep valley, near x = -2.09. It is a randomized method, so a particular run can fail. Change the seed or run it repeatedly to see how often it succeeds.
The earlier, simpler form of this code minimized (x - 3) ** 2 and returned a value close to 3.0. That function has only one valley, so greedy descent would have worked just as well. A worked example only demonstrates the analogy's value when the target has the difficulty the source was borrowed to solve.
Where the analogy holds and where it breaks
Evaluating the analogy means checking each transferred relation against the target.
| Source relation | Holds in the target? | Notes |
|---|---|---|
| Quenching traps the system | Yes | Matches greedy descent getting stuck. |
| High temperature allows uphill moves | Yes | Directly implemented by the acceptance rule. |
| Slow cooling gives a better result | Mostly | Better on average, but with no guarantee in finite time. |
| The system tends toward a physical equilibrium | Partly | Theory ties equilibrium to very slow cooling. Practical schedules are much faster. |
| Energy is a physical quantity | No | Cost is whatever you define it to be, and its scale determines the right temperature. |
| The metal cannot be restarted | No | A search can run many times from different starts, which the source does not suggest. |
The last two rows show the usual pattern. Some of the source's structure is unusable, and the target offers freedoms the source lacks. Restarts, parallel runs, and reheating are extensions that the analogy did not suggest and that you can add because the target allows them.
Common mistakes
- Treating the physics as binding. Annealing the algorithm does not require the crystal to behave in any particular way. If a different acceptance rule or schedule performs better on your data, use it.
- Leaving the temperature scale unexamined. The most common failure is a start temperature unrelated to the cost differences. Sample a few random moves, look at typical
deltavalues, and set the start so that about half of the uphill moves are accepted. - Cooling too fast. A fast schedule reproduces quenching. If the result varies a lot between seeds, the schedule is a likely cause.
- Returning the final state instead of the best. The code above returns
best. Returningxcan give a worse answer. - Concluding that the analogy proves the method works. The mapping generated the idea. Only experiments on your target problem show whether it helps.
Exercise
In the program above, you change the start temperature from 10.0 to 0.05 and keep everything else. Predict what happens to the annealed result when starting at x = 2.0, and say which relation in the mapping explains it.
Show answer
The result will almost certainly stay in the shallow valley, near x = 1.90. Escaping requires climbing about 10 cost units, and at temperature 0.05 the acceptance probability for such a move is about exp(-10 / 0.05) = exp(-200), which is effectively zero. The relation at work is "low temperature makes uphill moves rare." The scale of the temperature must match the cost differences, so a temperature that is too low makes the search behave like quenching.
Exercise
Name one idea that the metallurgy analogy does not supply but that you could add to the search because the target is software, and explain why the source domain could not suggest it.
Show answer
Random restarts are an example: run the search from several different starting points and keep the best result. A physical piece of metal has one history and cannot be rerun from a fresh start, so no relation in the source corresponds to restarting. Parallel runs and reheating after stalling are other valid answers. They are adaptations that use freedoms of the target.