Algorithm Search⌘K

Algorithmcore

Simulated annealing placement

Also called TimberWolf placement.

Sechen and Sangiovanni-Vincentelli's placement by annealing over moves and swaps of cells with a cost of wire length and overlap, with a shrinking range limiter.

Solves
Placement
Time
O(L M n D + n (n + K) + K S + P) worst · averageO(L M n D + n log n + K S + P) best
Space
O(n + P + K S) extra
Where
D = the largest number of pins on the nets of one cell, plus its width; K = the number of rows; L = the number of temperatures; M = the number of moves per cell at each temperature; P = the number of pins; S = the number of sites per row; n = the number of cells
Properties
randomizednot exactrandomized
Origin
Carl Sechen, Alberto Sangiovanni Vincentelli, 1985

Simulated annealing placement solves the placement problem of standard cells by simulated annealing. It starts from a random placement and repeats small random changes: move one cell to another place, or swap two cells. A change that lowers the cost is kept. A change that raises it by Δ\Delta is kept with the probability e−Δ/Te^{-\Delta / T}, the Metropolis criterion, where the temperature TT falls slowly. The cost is the wirelength plus a penalty for overlap, so cells may overlap early and are pushed apart later. A range limiter makes the moves shorter as TT falls. Sechen and Sangiovanni-Vincentelli built this into TimberWolf in 1985. For about ten years it gave the best placements, at a high cost in run time, until analytical and min-cut placers matched its quality much faster.

In plain words

Put the parts on the board anywhere, even on top of each other. Now pick a part at random and try to move it a little, or to swap it with a nearby part. If the wires get shorter, or parts stop overlapping, keep the change. If things get worse, still keep it sometimes, by a coin toss that is generous at first and stingy later.

Early on, parts jump far and bad moves are often kept, so the placement can leave a poor arrangement. Later, parts only take short steps and almost only good ones, so the placement settles. At the end, push the parts in each row side by side so nothing overlaps.

The problem

The input is a netlist with nn cells, nets ee with weights wew_e, PP pins and fixed pads, and KK rows of height 1 with SS unit sites. Cell ii has an integer width WiW_i, sits in a row rir_i with its left edge on a site xix_i, and has its pin at its center. The output is a legal placement with a small total HPWL.

During the annealing, overlap is allowed. The cost of a placement is

C=2∑eweHPWL⁡(e)+μ⋅overlap,C = 2 \sum_e w_e \operatorname{HPWL}(e) + \mu \cdot \text{overlap},

where overlap is the sum over all sites of the number of cells on the site minus one, when that is positive. The factor 2 keeps all values integer, because the centers are at half sites. The weight μ\mu sets the price of overlap against wire.

A move is either a displacement, where one cell goes to a new row and site, or a swap, where two cells take each other's places. The range limiter keeps moves inside a window of wxw_x sites and wrw_r rows around the cell; the window shrinks with log⁡T\log T, so that late moves are short.

The algorithm

  1. SA-PLACE(netlist, pads, K rows, S sites, T₀, T_end, α, M, μ)
  2. 1put each cell at a random site of a random row; compute C and the site counts
  3. 2T ← T₀; while T > T_end
  4. 3window wx ← max(1, round(S·f)), wr ← max(1, round(K·f)) with f = log(T/T_end) / log(T₀/T_end)
  5. 4repeat M·n times
  6. 5pick a cell; propose a displacement inside the window, or a swap with a cell inside the window
  7. 6apply the move; Δ ← the change of C, from the nets of the moved cells and the sites they leave and take
  8. 7if Δ > 0 and random() ≥ e^(−Δ/T) then undo the move
  9. 8T ← α·T
  10. 9move cells out of overfull rows to the nearest row with room, pack each row in x order, and return

Line L6 does not recompute the cost from scratch. Only the nets that contain a moved cell change, and only the sites under the moved cells change their counts, so Δ\Delta costs O(D)O(D). Without a given T0T_0, the implementation sets it so that about 90 percent of the uphill moves are accepted at the start: T0=Δˉ/ln⁡(1/0.9)T_0 = \bar\Delta / \ln(1/0.9), where Δˉ\bar\Delta is the mean uphill Δ\Delta of 4n4n trial moves. Line L9 is a simple legalizer, as in placement legalization; if the cost has driven the overlap to zero and no row is overfull, it does not move any cell.

TimberWolf itself differs in details. It also changes the orientation of cells, it adds a penalty for rows that are longer or shorter than the target, it changes α\alpha during the run, and it ends with a second stage that removes the overlap and refines the result.

Example

One row of 4 sites, three unit cells a,b,ca, b, c at sites 0, 1 and 2, a pad pp at (0,0)(0, 0), nets {a,c}\{a, c\} and {b,p}\{b, p\}, and μ=8\mu = 8. The centers are at 0.5,1.5,2.50.5, 1.5, 2.5 in xx and 0.50.5 in yy.

step placement HPWL of {a,c}\{a, c\} HPWL of {b,p}\{b, p\} overlap CC Δ\Delta
start a,b,ca, b, c at 0, 1, 2 2 1.5 + 0.5 0 8
swap aa and bb b,a,cb, a, c at 0, 1, 2 1 0.5 + 0.5 0 4 −4-4
move cc to site 3 b,a,cb, a, c at 0, 1, 3 2 1 0 6 +2+2
move cc to site 1 cc on top of aa 0 1 1 10 +4+4

The swap is always kept. The move of cc to site 3 is kept with probability e−2/Te^{-2/T}: 0.37 at T=2T = 2, but only 0.018 at T=0.5T = 0.5. The move of cc onto aa shortens the net {a,c}\{a, c\} to zero, but the overlap costs 8, so at T=0.5T = 0.5 it is kept with probability e−8≈0.0003e^{-8} \approx 0.0003. The tests check these values of Δ\Delta.

Correctness

The returned placement is legal whenever line L9 finds room for every cell from an overfull row, which always holds for unit cells that fit the chip. Each row then has at most SS sites of cells, and the packing of a row places them on distinct sites inside it. Its HPWL is therefore at least the optimum. Line L6 computes the exact change of CC, so the annealing follows the Metropolis rule for the stated cost. See the proof.

Nothing in the run proves that the result is optimal or near optimal. Hajek's theorem (convergence of simulated annealing) says that the state converges in probability to the set of global minima when Tk=c/log⁡(k+1)T_k = c / \log(k + 1) with cc at least the depth of the deepest local minimum that is not global, and only then. No placer uses such a schedule: it needs a number of moves far beyond practice. The geometric schedule T←αTT \leftarrow \alpha T of line L8, and of TimberWolf, is a heuristic.

Proof: The incremental cost change is exact, the final packing is legal, and the annealing stops after a fixed number of temperaturesfull

Let C=2∑eweHPWL⁡(e)+μ⋅overlapC = 2 \sum_e w_e \operatorname{HPWL}(e) + \mu \cdot \text{overlap}, where overlap =∑sitesmax⁡(0,os−1)= \sum_{\text{sites}} \max(0, o_s - 1) and oso_s is the number of cells on site ss.

Lemma 1 (the change of the overlap). Removing a cell from a site with count oso_s lowers the overlap by 1 if os≥2o_s \ge 2 and leaves it if os=1o_s = 1. Adding a cell to a site with count oso_s raises the overlap by 1 if os≥1o_s \ge 1 and leaves it if os=0o_s = 0.

Proof. The term of the site is max⁡(0,os−1)\max(0, o_s - 1). It changes from os−1o_s - 1 to os−2o_s - 2 when os≥2o_s \ge 2 falls by 1, and stays 0 when os=1o_s = 1 falls to 0. The case of adding is the same in reverse. □\square

Lemma 2 (line L6 is exact). For a move of a set QQ of one or two cells, the value Δ\Delta of line L6 equals CC after the move minus CC before it.

Proof. A net with no cell of QQ has the same pins before and after, so its HPWL does not change. Line L6 sums the doubled HPWL of all nets that contain a cell of QQ, before and after, so the difference of the sums is the change of the wire term. For the overlap, line L6 first removes every cell of QQ from the counts, then sets the new positions, then adds every cell of QQ. Each step changes the overlap as Lemma 1 says, and the implementation adds exactly those changes. Removing all cells of QQ first matters for a swap, where one cell takes sites that the other leaves. The sum of the steps is the total change of the overlap. Undoing the move applies the old positions in the same way, so it restores the counts and CC. □\square

Corollary (the acceptance rule). A move is kept with probability 1 if Δ≤0\Delta \le 0 and with probability e−Δ/Te^{-\Delta / T} if Δ>0\Delta > 0, because random() is uniform on [0,1)[0, 1) and line L7 undoes the move exactly when random() ≥e−Δ/T\ge e^{-\Delta/T}. So at each temperature the annealing is the Metropolis chain for CC restricted to the moves of the window. If TT is so small that e−Δ/T=0e^{-\Delta / T} = 0 for every Δ≥1\Delta \ge 1, no uphill move is kept, and since all values of CC are integers, CC never rises.

Lemma 3 (moving cells out of overfull rows). If line L9 returns, every row holds cells of total width at most SS.

Proof. The procedure keeps the load of each row equal to the total width of its cells. It handles the rows in order. While a row kk has load above SS, it moves one of its cells to a row qq whose load plus the width of the cell is at most SS, or it stops with an error. A row that receives a cell still has load at most SS, so a row once at most SS stays so, and each pass lowers the load of row kk. When the loop over the rows ends, every row is at most SS. □\square

When all cells have width 1 and n≤KSn \le K S, the error never happens: a row with load above SS exists only if another row has load below SS, and a unit cell fits there.

Lemma 4 (packing a row). Let cells with integer widths and total width at most SS be packed: in order of their targets, each goes to the site nearest its target, clamped to [0,S−Wi][0, S - W_i], but not left of the end of the previous cell; then, from the right, each cell is moved left to end at or before the start of the next cell, with the first limit SS. Then every cell is inside [0,S)[0, S) and no two overlap.

Proof. Number the cells 1,…,m1, \ldots, m in the order. After the first pass, pj≥pj−1+Wj−1p_j \ge p_{j-1} + W_{j-1}, so pj≥∑l<jWlp_j \ge \sum_{l < j} W_l. The second pass sets pm′=min⁡(pm,S−Wm)p'_m = \min(p_m, S - W_m) and pj′=min⁡(pj,pj+1′−Wj)p'_j = \min(p_j, p'_{j+1} - W_j). By induction from j=mj = m down, pj′≥∑l<jWlp'_j \ge \sum_{l < j} W_l: the first term of each minimum satisfies it, S−Wm≥∑l<mWlS - W_m \ge \sum_{l < m} W_l because the cells fit, and pj+1′−Wj≥∑l≤jWl−Wjp'_{j+1} - W_j \ge \sum_{l \le j} W_l - W_j. So every pj′≥0p'_j \ge 0, and the second pass gives pj′+Wj≤pj+1′p'_j + W_j \le p'_{j+1} and pm′+Wm≤Sp'_m + W_m \le S. All values are integers, so the cells are on sites. □\square

Theorem 1 (legality). If SA-PLACE returns, its placement is legal, and its HPWL is at least the optimum of the placement problem.

Proof. By Lemma 3 every row holds at most SS sites of cells, and by Lemma 4 each row is packed legally. Cells of different rows do not overlap. A legal placement is feasible for the placement problem, so its HPWL is at least the least HPWL of all legal placements. ■\blacksquare

Theorem 2 (termination and running time). With 0<α<10 < \alpha < 1 and T0,Tend>0T_0, T_{\text{end}} > 0, the loop of line L2 runs L=max⁡(0,⌈log⁡(Tend/T0)/log⁡α⌉)L = \max(0, \lceil \log(T_{\text{end}} / T_0) / \log \alpha \rceil) times, and SA-PLACE runs in O(LMnD+n(n+K)+KS+P)O(L M n D + n (n + K) + K S + P) time, where DD bounds the pins on the nets of a cell plus its width.

Proof. After jj temperatures T=αjT0T = \alpha^j T_0, which is at most TendT_{\text{end}} exactly when j≥log⁡(Tend/T0)/log⁡αj \ge \log(T_{\text{end}} / T_0) / \log \alpha. Each temperature makes MnM n proposals. A proposal costs O(1)O(1); line L6 scans the nets of at most two cells and the sites under them, O(D)O(D); line L7 costs the same to undo. Line L1 costs O(KS+nWmax⁡+P)O(K S + n W_{\max} + P). In line L9, each cell leaves an overfull row at most once, since it never moves to a row above SS, and each such step scans the cells and rows, O(n+K)O(n + K); the sorts of the packing cost O(nlog⁡n)O(n \log n). ■\blacksquare

Complexity

  • Set up. The random start, the site counts and the first cost cost O(nWmax⁡+KS+P)O(n W_{\max} + K S + P).
  • Annealing. There are L=⌈log⁡(Tend/T0)/log⁡α⌉L = \lceil \log(T_{\text{end}} / T_0) / \log \alpha \rceil temperatures and MnM n moves at each. A move costs O(D)O(D): it rescans the nets of at most two cells and updates the sites under them.
  • Packing. Each cell leaves an overfull row at most once, and finding it and a row with room costs O(n+K)O(n + K); packing the rows costs O(nlog⁡n)O(n \log n).

So the time is O(LMnD+n(n+K)+KS+P)O(L M n D + n (n + K) + K S + P), and the space is O(n+P+KS)O(n + P + K S). The annealing term dominates in practice, because LML M is large: with α=0.9\alpha = 0.9 and M=20M = 20, a fall of TT by a factor of 1000 takes 66 temperatures and 1320 moves per cell.

Properties

What is proved.

  • The incremental Δ\Delta of line L6 equals the change of CC computed from scratch.
  • At TT close to 0 no uphill move is kept, so the cost never rises.
  • When line L9 returns, the placement is legal and its HPWL is at least the optimum.
  • With a logarithmic schedule and a large enough constant, annealing converges in probability to an optimum (Hajek); the schedule of line L8 does not have this guarantee.

What is measured. The numbers come from the implementation of this page on toy inputs, not from benchmarks. On 20 random netlists of 6 unit cells in 2 rows of 4 sites (seed 10), the result equals the exhaustive optimum on 16 and is on average 1.013 times the optimum. On 10 random netlists of 30 cells of width 1 or 2 in 6 rows of 10 sites (seed 11, α=0.9\alpha = 0.9, M=20M = 20, μ=8\mu = 8), the mean HPWL is 120.35 for annealing, 130.6 for the same code at temperature near 0 (a greedy descent), and 281.35 for a random start packed into rows. With μ=4\mu = 4 the mean is 139.45: overlap costs only as much as two units of wire, so the annealing ends with overlap, and the packing of line L9 makes the wires longer.

Variants and improvements

  • Other schedules. Adaptive schedules set α\alpha and the number of moves from the spread of the cost at each temperature; TimberWolf used a fixed table of α\alpha values. See cooling schedules.
  • TimberWolfSC versions. Later versions by Sechen and his students added better net models, hierarchical annealing on clusters of cells, and faster schedules.
  • Annealing inside other placers. Some placers use annealing only as a final step on small windows, or on the clusters of a min-cut placer, where the moves are few and the gain is local.
  • Detailed placement. At low temperature with only swaps, annealing becomes a randomized detailed placer; deterministic moves such as independent set matching are faster for that job.
  • Floorplanning. Annealing over a representation of block positions is still a common method for floorplans of a few hundred blocks.

When to use it

Use annealing placement for small or medium instances, for unusual costs that are hard to make smooth, such as costs with many hard rules, or as a reference of quality when run time does not matter. For large standard-cell designs, use an analytical placer such as quadratic placement or electrostatics-based placement, then legalization and detailed placement; they reach similar or better wirelength in a small part of the time.

Pitfalls

  • An overlap weight that is too small. If overlap is cheap, the annealing keeps it, and the final packing destroys the wirelength. The measurement above shows this.
  • Recomputing the full cost per move. That costs O(P)O(P) per move instead of O(D)O(D) and makes the method far slower.
  • A start temperature that is too low or too high. Too low, and the run is a greedy descent; too high, and many temperatures are a random walk. Set T0T_0 from the uphill Δ\Delta of trial moves.
  • Swaps of cells of different width. A swap must clamp each cell inside its new row, and the overlap it makes must enter Δ\Delta.
  • Expecting the theory to hold. The convergence theorem needs a logarithmic schedule; a geometric schedule gives no guarantee.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

simulated_annealing_placement.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/simulated-annealing-placement/. The authors are listed in prov/ZEMFMQ.jsonl.
"""Simulated annealing placement in the style of TimberWolf.

Cells have integer widths W[i] and sit on K rows of S unit sites; row r has height 1.
A cell is given by its row r[i] and its left site x[i]; its pin is at its center.
Pads are fixed points; pin index n + j is pad j. During the annealing cells may overlap.
All costs are kept in doubled integer units so that the deltas are exact:
cost = 2 HPWL + mu * overlap, where overlap counts the sites held by more than one cell.
"""

import math
import random


def pin2(p, x, r, W, n, pads):
    """The doubled coordinates of pin p."""
    if p < n:
        return 2 * x[p] + W[p], 2 * r[p] + 1
    return 2 * pads[p - n][0], 2 * pads[p - n][1]


def net_cost2(e, x, r, W, n, pads):
    """Twice the HPWL of the net e."""
    xs, ys = zip(*(pin2(p, x, r, W, n, pads) for p in e))
    return max(xs) - min(xs) + max(ys) - min(ys)


def overlap(x, r, W, K, S):
    """The number of extra cells over all sites: sum of max(0, occupancy - 1)."""
    occ = [[0] * S for _ in range(K)]
    for i in range(len(x)):
        for s in range(x[i], x[i] + W[i]):
            occ[r[i]][s] += 1
    return sum(max(0, c - 1) for row in occ for c in row)


def full_cost(x, r, W, nets, pads, K, S, mu):
    n = len(x)
    return sum(net_cost2(e, x, r, W, n, pads) for e in nets) + mu * overlap(x, r, W, K, S)


class State:
    """A placement with its occupancy, its overlap and its cost, updated by moves."""

    def __init__(self, x, r, W, nets, pads, K, S, mu):
        self.x, self.r, self.W = list(x), list(r), W
        self.nets, self.pads, self.K, self.S, self.mu = nets, pads, K, S, mu
        self.n = len(x)
        self.cell_nets = [[] for _ in range(self.n)]
        for k, e in enumerate(nets):
            for p in set(e):
                if p < self.n:
                    self.cell_nets[p].append(k)
        self.occ = [[0] * S for _ in range(K)]
        self.over = 0
        for i in range(self.n):
            self._add(i)
        self.cost = sum(net_cost2(e, self.x, self.r, W, self.n, pads) for e in nets) + mu * self.over

    def _add(self, i):
        row = self.occ[self.r[i]]
        for s in range(self.x[i], self.x[i] + self.W[i]):
            if row[s] >= 1:
                self.over += 1
            row[s] += 1

    def _remove(self, i):
        row = self.occ[self.r[i]]
        for s in range(self.x[i], self.x[i] + self.W[i]):
            row[s] -= 1
            if row[s] >= 1:
                self.over -= 1

    def apply(self, moves):
        """Apply moves [(cell, new x, new row), ...] and return (delta, the reverse moves)."""
        cells = [c for c, _, _ in moves]
        touched = {k for c in cells for k in self.cell_nets[c]}
        before = sum(net_cost2(self.nets[k], self.x, self.r, self.W, self.n, self.pads) for k in touched)
        over0 = self.over
        back = [(c, self.x[c], self.r[c]) for c in cells]
        for c in cells:
            self._remove(c)
        for c, nx, nr in moves:
            self.x[c], self.r[c] = nx, nr
        for c in cells:
            self._add(c)
        after = sum(net_cost2(self.nets[k], self.x, self.r, self.W, self.n, self.pads) for k in touched)
        delta = after - before + self.mu * (self.over - over0)
        self.cost += delta
        return delta, back


def propose(st, rng, wx, wr, p_swap):
    """A displacement or a swap inside the range limiter window, or None."""
    i = rng.randrange(st.n)
    if rng.random() < p_swap and st.n > 1:
        j = rng.randrange(st.n - 1)
        j += j >= i
        if abs(st.x[j] - st.x[i]) > wx or abs(st.r[j] - st.r[i]) > wr:
            return None
        return [(i, min(st.x[j], st.S - st.W[i]), st.r[j]), (j, min(st.x[i], st.S - st.W[j]), st.r[i])]
    nx = min(max(st.x[i] + rng.randint(-wx, wx), 0), st.S - st.W[i])
    nr = min(max(st.r[i] + rng.randint(-wr, wr), 0), st.K - 1)
    if (nx, nr) == (st.x[i], st.r[i]):
        return None
    return [(i, nx, nr)]


def pack_row(cells, tx, W, S):
    """Left sites for the cells of one row of S sites whose widths fit: in the order of
    their targets, each goes to the site nearest its target but right of the previous cell;
    then a pass from the right pulls the cells back inside the row."""
    order = sorted(cells, key=lambda i: (tx[i], i))
    pos, end = {}, 0
    for i in order:
        want = int(round(tx[i] - W[i] / 2))
        pos[i] = max(end, min(max(want, 0), S - W[i]))
        end = pos[i] + W[i]
    limit = S
    for i in reversed(order):
        pos[i] = min(pos[i], limit - W[i])
        limit = pos[i]
    return pos


def pack_rows(x, r, W, K, S):
    """Move cells out of overfull rows to the nearest row with room, then pack each row."""
    r = list(r)
    load = [0] * K
    for i in range(len(x)):
        load[r[i]] += W[i]
    for k in range(K):
        while load[k] > S:
            i = min((c for c in range(len(x)) if r[c] == k), key=lambda c: (W[c], c))
            room = [q for q in range(K) if load[q] + W[i] <= S]
            if not room:
                raise ValueError("no row has room for a cell of an overfull row")
            q = min(room, key=lambda q: (abs(q - k), q))
            load[k] -= W[i]
            load[q] += W[i]
            r[i] = q
    tx = [x[i] + W[i] / 2 for i in range(len(x))]
    nx = list(x)
    for k in range(K):
        for i, p in pack_row([c for c in range(len(x)) if r[c] == k], tx, W, S).items():
            nx[i] = p
    return nx, r


def anneal(n, nets, pads, W, K, S, seed=0, T0=None, T_end=0.05, alpha=0.9,
           moves_per_cell=20, mu=8, p_swap=0.5, trace=None):
    """Anneal a placement and return a legal one as (x, r)."""
    rng = random.Random(seed)
    st = State([rng.randint(0, S - W[i]) for i in range(n)], [rng.randrange(K) for _ in range(n)],
               W, nets, pads, K, S, mu)  # @line L1
    if T0 is None:  # a start temperature that accepts about 90% of the uphill moves
        ups = []
        for _ in range(4 * n):
            mv = propose(st, rng, S, K, p_swap)
            if mv:
                d, back = st.apply(mv)
                st.apply(back)
                if d > 0:
                    ups.append(d)
        T0 = (sum(ups) / len(ups) if ups else 1) / math.log(1 / 0.9)
    T = T0
    while T > T_end:  # @line L2
        frac = math.log(T / T_end) / math.log(T0 / T_end) if T0 > T_end else 0
        wx, wr = max(1, round(S * frac)), max(1, round(K * frac))  # @line L3
        for _ in range(moves_per_cell * n):  # @line L4
            mv = propose(st, rng, wx, wr, p_swap)  # @line L5
            if mv is None:
                continue
            d, back = st.apply(mv)  # @line L6
            if d > 0 and rng.random() >= math.exp(-d / T):  # @line L7
                st.apply(back)
        if trace is not None:
            trace.append((T, st.cost))
        T *= alpha  # @line L8
    return pack_rows(st.x, st.r, W, K, S)  # @line L9
test_simulated_annealing_placement.py 151 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/simulated-annealing-placement/. The authors are listed in prov/ZEMFMQ.jsonl.

import random
from fractions import Fraction
from itertools import permutations

from simulated_annealing_placement import (
    State,
    anneal,
    full_cost,
    overlap,
    pack_rows,
    propose,
)


def instance(rng, n, K, S, q=4):
    pads = [(0, rng.randint(0, K)), (S, rng.randint(0, K)), (rng.randint(0, S), 0), (rng.randint(0, S), K)][:q]
    nets = []
    for i in range(n):  # every cell is on a net to a pad or to an earlier cell
        nets.append([i, n + rng.randrange(q)] if i == 0 or rng.random() < 0.3 else [i, rng.randrange(i)])
    for _ in range(n // 2):
        nets.append(rng.sample(range(n + q), rng.randint(2, 3)))
    return nets, pads


def legal(x, r, W, K, S):
    used = set()
    for i in range(len(x)):
        if not (0 <= r[i] < K and 0 <= x[i] and x[i] + W[i] <= S):
            return False
        for s in range(x[i], x[i] + W[i]):
            if (r[i], s) in used:
                return False
            used.add((r[i], s))
    return True


def direct_hpwl(x, r, W, nets, pads):
    """HPWL from scratch with exact fractions: the pin of cell i is at (x + W/2, r + 1/2)."""
    n = len(x)
    total = Fraction(0)
    for e in nets:
        pts = [(x[p] + Fraction(W[p], 2), r[p] + Fraction(1, 2)) if p < n else tuple(map(Fraction, pads[p - n]))
               for p in e]
        xs, ys = zip(*pts)
        total += max(xs) - min(xs) + max(ys) - min(ys)
    return total


def exhaustive_optimum(n, nets, pads, K, S):
    """The least HPWL over all placements of n unit cells on distinct sites, from doubled integers."""
    sites = [(2 * s + 1, 2 * r + 1) for r in range(K) for s in range(S)]
    pad2 = [(2 * a, 2 * b) for a, b in pads]
    best = None
    for perm in permutations(sites, n):
        pts = list(perm) + pad2
        total = 0
        for e in nets:
            xs = [pts[p][0] for p in e]
            ys = [pts[p][1] for p in e]
            total += max(xs) - min(xs) + max(ys) - min(ys)
        if best is None or total < best:
            best = total
    return Fraction(best, 2)


def test_incremental_delta_equals_full_recomputation():
    rng = random.Random(1)
    for _ in range(30):
        n, K, S = rng.randint(2, 10), rng.randint(1, 4), rng.randint(3, 8)
        W = [rng.choice([1, 1, 2, 3]) for _ in range(n)]
        nets, pads = instance(rng, n, K, S)
        mu = rng.randint(1, 5)
        st = State([rng.randint(0, S - w) for w in W], [rng.randrange(K) for _ in range(n)], W, nets, pads, K, S, mu)
        assert st.cost == full_cost(st.x, st.r, W, nets, pads, K, S, mu)
        for _ in range(100):
            mv = propose(st, rng, rng.randint(1, S), rng.randint(1, K), 0.5)
            if mv is None:
                continue
            before = st.cost
            d, back = st.apply(mv)
            assert st.cost == full_cost(st.x, st.r, W, nets, pads, K, S, mu) == before + d
            assert st.over == overlap(st.x, st.r, W, K, S)
            if rng.random() < 0.5:
                st.apply(back)
                assert st.cost == before


def test_page_example_of_one_swap_and_one_displacement():
    # One row of 4 sites; cells a, b, c at sites 0, 1, 2; nets {a, c} and {b, pad at (0, 0)}.
    W, K, S = [1, 1, 1], 1, 4
    nets = [[0, 2], [1, 3]]
    pads = [(0, 0)]
    st = State([0, 1, 2], [0, 0, 0], W, nets, pads, K, S, 8)
    assert st.cost == 8  # HPWL 4: {a, c} spans 2, {b, pad} spans 1.5 in x and 0.5 in y
    d, _ = st.apply([(0, 1, 0), (1, 0, 0)])  # swap a and b
    assert d == -4  # HPWL falls by 2
    d, _ = st.apply([(2, 3, 0)])  # move c one site right
    assert d == 2  # HPWL rises by 1
    d, _ = st.apply([(2, 1, 0)])  # move c onto a
    assert d == -2 * 2 + 8 * 1 == 4  # HPWL falls by 2, one site is now shared


def test_zero_temperature_never_raises_the_cost():
    rng = random.Random(4)
    for seed in range(5):
        n, K, S = 12, 3, 6
        nets, pads = instance(rng, n, K, S)
        trace = []
        anneal(n, nets, pads, [1] * n, K, S, seed=seed, T0=1e-6, T_end=1e-9, alpha=0.5, trace=trace)
        costs = [c for _, c in trace]
        assert all(b <= a for a, b in zip(costs, costs[1:]))


def test_pack_rows_is_legal():
    rng = random.Random(5)
    for _ in range(300):
        K, S = rng.randint(1, 5), rng.randint(3, 10)
        W = []
        while sum(W) < 0.8 * K * S - 2:
            W.append(rng.choice([1, 1, 1, 2]))
        x = [rng.randint(0, S - w) for w in W]
        r = [rng.randrange(K) for _ in W]
        try:
            nx, nr = pack_rows(x, r, W, K, S)
        except ValueError:
            continue
        assert legal(nx, nr, W, K, S)


def test_anneal_is_legal_and_its_cost_matches_a_direct_sum():
    rng = random.Random(11)
    for seed in range(2):
        n, K, S = 30, 6, 10
        W = [rng.choice([1, 1, 2]) for _ in range(n)]
        nets, pads = instance(rng, n, K, S)
        x, r = anneal(n, nets, pads, W, K, S, seed=seed, moves_per_cell=8)
        assert legal(x, r, W, K, S)
        assert 2 * direct_hpwl(x, r, W, nets, pads) == full_cost(x, r, W, nets, pads, K, S, 0)


def test_anneal_never_beats_the_exhaustive_optimum_on_6_cells():
    rng = random.Random(10)
    for seed in range(3):
        n, K, S = 6, 2, 4
        nets, pads = instance(rng, n, K, S)
        x, r = anneal(n, nets, pads, [1] * n, K, S, seed=seed)
        assert legal(x, r, [1] * n, K, S)
        assert direct_hpwl(x, r, [1] * n, nets, pads) >= exhaustive_optimum(n, nets, pads, K, S)

History

Kirkpatrick, Gelatt and Vecchi introduced simulated annealing in 1983 and used placement and wiring of circuits as an example. Sechen and Sangiovanni-Vincentelli built TimberWolf on it in 1985, with an overlap penalty, a range limiter and a tuned schedule, and it gave the best standard-cell placements for about a decade. Hajek proved in 1988 when logarithmic schedules converge. From the late 1990s, multilevel min-cut placers and then analytical placers matched annealing's wirelength at a small part of its run time, and annealing moved to floorplanning and to small local steps.

References

  1. Carl Sechen and Alberto Sangiovanni-Vincentelli, The TimberWolf placement and routing package, IEEE Journal of Solid-State Circuits SC-20(2), 510 to 522, 1985, the cost function with an overlap penalty, the displacement and exchange moves, the range limiter, and the cooling schedule
  2. Scott Kirkpatrick, C. Daniel Gelatt and Mario P. Vecchi, Optimization by simulated annealing, Science 220(4598), 671 to 680, 1983, the annealing method and its first use on placement and wiring
  3. Bruce Hajek, Cooling schedules for optimal annealing, Mathematics of Operations Research 13(2), 311 to 329, 1988, the main theorem on logarithmic cooling schedules
  4. Andrew B. Kahng, Jens Lienig, Igor L. Markov and Jin Hu, VLSI Physical Design, From Graph Partitioning to Timing Closure, second edition, Springer, 2022, Chapter 4, Global and Detailed Placement (simulated annealing placement; general locator)

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example