Algorithm Search⌘K

Algorithmcore

Wong-Liu floorplanning

Also called simulated annealing floorplanning.

Simulated annealing over normalized Polish expressions with three moves, swap operands, complement a chain and swap an operand with an operator.

Time
O(s k n^2 d) worst · averageO(s k n^2) best
Space
O(n d) extra
Where
d = the depth of the slicing tree; k = the moves per block at one temperature; n = the number of blocks; s = the number of temperatures
Properties
randomizednot exactiterative
Origin
D. F. Wong, C. L. Liu, 1986

Wong-Liu floorplanning searches for a good slicing floorplan with simulated annealing. A state is a normalized Polish expression, so every state is one slicing floorplan and no floorplan has two states. Three small moves change the word: swap two neighbouring blocks, change the direction of a run of cuts, and swap a block with a cut next to it. The cost of a word is the least area over the shapes of the blocks, found by Stockmeyer's floorplan sizing, plus a weight times the wire length. Wong and Liu published it in 1986, and it became the model for many later annealing floorplanners. It is a heuristic: what is proved is that every state is a valid floorplan and that the moves reach every slicing floorplan, not how close the result is to the optimum.

In plain words

You arrange furniture in a room by trying small changes. Swap two pieces next to each other. Turn a row of pieces into a column. Move a piece across a wall. After each change you measure the room you need. If the change helps, you keep it. If it makes things worse, you sometimes still keep it, more often at the start and less often later. This lets you leave a bad arrangement that no single small change can improve.

The arrangement is written as a word of blocks and cuts. The rules of the word make sure that every word is a real arrangement and that no arrangement has two words, so no time is lost on copies.

The problem

The input is a set of nn blocks, each with a list of allowed shapes (w,h)(w, h) (for example a rectangle and its rotation, or a staircase approximation of a soft block), a list of nets on the blocks, and a weight λ≥0\lambda \ge 0. The output is a slicing floorplan with a shape for each block. The goal is a small cost A+λLA + \lambda L, where AA is the area of the floorplan and LL is the half-perimeter wire length of the nets over the centres of the blocks. This is the slicing case of floorplanning. The method looks for a good floorplan, and it does not prove that the one it finds is optimal.

The algorithm

The tokens are blocks and the operators VV (E1E2VE_1 E_2 V puts E1E_1 to the left of E2E_2) and HH (E1E_1 below E2E_2). A chain is a maximal run of operators in the word. The three moves are:

  • M1. Swap two operands that are next to each other in the order of the operands. Operators between them stay in place.
  • M2. Complement a chain: each HH in it becomes VV, and each VV becomes HH.
  • M3. Swap an operand and an operator that are next to each other, only if the result is still normalized.
  1. WONG-LIU(blocks, S, nets, λ, r, k, ε) ▷ cost(E) = least area of E over S, plus λ · HPWL
  2. 1E ← 1 2 V 3 V ... n V; best ← E
  3. 2T ← T_0, so that an average uphill move is accepted with probability P_0
  4. 3repeat
  5. 4tries ← 0; uphill ← 0; rejects ← 0
  6. 5repeat
  7. 6E' ← M1, M2 or M3, chosen at random, applied to E
  8. 7tries ← tries + 1; Δ ← cost(E') − cost(E)
  9. 8if Δ ≤ 0 or random() < e^(−Δ / T) then
  10. 9if Δ > 0 then uphill ← uphill + 1
  11. 10E ← E'; if cost(E) < cost(best) then best ← E
  12. 11else rejects ← rejects + 1
  13. 12until uphill > N or tries > 2N ▷ N = k · n
  14. 13T ← r · T
  15. 14until rejects / tries > 0.95 or T < ε
  16. 15return best

Line L8 is the Metropolis rule, and lines L13 and L14 are a geometric cooling schedule. One temperature ends when the search has made NN uphill moves or tried 2N2N moves. The search stops when almost every move is rejected or the temperature is very low. The code uses r=0.85r = 0.85 by default, and it also has a limit on the number of temperatures.

M3 is the only move that can break the normal form. If the operand eie_i moves right past the operator ei+1e_{i+1}, the prefix of length ii gets one more operator, and the balloting property needs 2(Ni−1+1)<i2 (N_{i-1} + 1) < i, where NkN_k is the number of operators in e1⋯eke_1 \cdots e_k. The operator also gets a new left neighbour ei−1e_{i-1}, which must not be the same operator. If the operator moves right past an operand, only its new right neighbour must differ from it. With the prefix counts both tests take O(1)O(1) time.

Example

Take five blocks, each of which may turn: 1:2×31: 2 \times 3, 2:3×22: 3 \times 2, 3:4×13: 4 \times 1, 4:2×24: 2 \times 2 and 5:1×35: 1 \times 3 (width by height). The block area is 6+6+4+4+3=236 + 6 + 4 + 4 + 3 = 23. Some moves from the start word, each with the least area of the new word:

step word move least area
0 1 2 V 3 V 4 V 5 V1\,2\,V\,3\,V\,4\,V\,5\,V the start: a row 30, a 15×215 \times 2 row
1 1 3 V 2 V 4 V 5 V1\,3\,V\,2\,V\,4\,V\,5\,V M1 on blocks 2 and 3 30
2 1 2 V 3 V 4 H 5 V1\,2\,V\,3\,V\,4\,H\,5\,V M2 on the chain after block 4 36
3 1 2 V 3 4 V H 5 V1\,2\,V\,3\,4\,V\,H\,5\,V M3 on the operator before block 4 28
4 1 2 V 3 4 H V 5 V1\,2\,V\,3\,4\,H\,V\,5\,V M2 on the chain V HV\,H 27

Step 2 to step 3 swaps the operator VV at position 5 with the operand 4 after it. Its new right neighbour is HH, so the word stays normalized. The same swap on the start word would give 1 2 V 3 4 V V 5 V1\,2\,V\,3\,4\,V\,V\,5\,V with two VV in a row, so M3 refuses it there. Step 1 to step 2 is an uphill move by 6, which the search accepts with probability e−6/Te^{-6/T}.

Five runs of the annealing with k=10k = 10 and the seeds 0 to 4 all end at area 24. One of the results is 5 3 H 1 V 4 V 2 V5\,3\,H\,1\,V\,4\,V\,2\,V: block 5 as 3×13 \times 1 under block 3 as 4×14 \times 1, and then blocks 1, 4 and 2 in a row, in a 12×212 \times 2 rectangle with one empty unit. A full search over all 5!⋅90=108005! \cdot 90 = 10800 normalized words with Stockmeyer's sizing confirms that 24 is the least area of a slicing floorplan of these blocks.

Correctness

Each move keeps the word normalized. M1 does not change the positions and the values of the operators. M2 changes a run of operators that alternate into a run that still alternates, with operands on both sides. M3 is applied only after the balloting test and the neighbour test above. So every state is a normalized Polish expression, which is one slicing floorplan, and its cost is computed exactly by Stockmeyer's sizing. The returned word is the best state visited. So its area is at least the least area of a slicing floorplan, which is at least the total block area. The inner loop stops after at most 2N+12N + 1 tries, and the temperature falls by the factor rr, so the search stops. Wong and Liu also prove that the three moves connect all normalized words, so every slicing floorplan can be reached. The full proof is in the correctness proof.

What is not proved is the quality of the result. The geometric schedule gives no bound on the gap to the optimum. In the measurement above, on 20 random instances of 5 blocks with rotation, 19 runs with k=10k = 10 reached the least area of an exhaustive search. That is a measurement on toy instances, not a guarantee.

Proof: The moves of Wong-Liu floorplanning keep the word normalized, and the search returns a valid slicing floorplanfull

We use the pseudocode and the conventions of the page. Let E=e1⋯e2n−1E = e_1 \cdots e_{2n-1} be a normalized Polish expression: each block occurs one time, every prefix has more operands than operators (the balloting property), and no two equal operators are next to each other. By the normalized Polish expression page, these three conditions are exactly the words of the skewed slicing trees. Let NkN_k be the number of operators in e1⋯eke_1 \cdots e_k.

Lemma 1 (M1). Swapping two operands that are next to each other in the operand order gives a normalized expression.

Proof. The positions of the operators and the operators themselves do not change. So the number of operators in each prefix, the number of operands in each prefix and every pair of neighbouring operators stay the same. The set of operands stays the same. □\square

Lemma 2 (M2). Complementing one chain, a maximal run es⋯ete_s \cdots e_t of operators, gives a normalized expression.

Proof. The token types at each position do not change, so the balloting property holds. Inside the chain the operators alternate, because EE is normalized, and they still alternate after each one is complemented. The tokens just before ese_s and just after ete_t are operands or the ends of the word, by maximality, so no new pair of neighbouring operators appears. □\square

Lemma 3 (M3). Let eie_i and ei+1e_{i+1} be an operand and an operator, in either order, and let E′E' be EE with the two swapped. Then E′E' is normalized if and only if:

  • if eie_i is the operand: 2(Ni−1+1)<i2 (N_{i-1} + 1) < i and ei−1≠ei+1e_{i-1} \ne e_{i+1} (when i>1i > 1);
  • if eie_i is the operator: ei+2≠eie_{i+2} \ne e_i (when i+2≤2n−1i + 2 \le 2n - 1).

The implementation tests this in O(1)O(1) time with the prefix counts, with indices from 0.

Proof. Only the prefix of length ii changes its counts. In the first case, the prefix e1′⋯ei′e'_1 \cdots e'_i has Ni−1+1N_{i-1} + 1 operators and i−Ni−1−1i - N_{i-1} - 1 operands, and the balloting property for it is i−Ni−1−1>Ni−1+1i - N_{i-1} - 1 > N_{i-1} + 1, which is the condition. The operator now has the neighbours ei−1e_{i-1} and the operand eie_i, so the only new pair of operators that can appear is ei−1ei+1e_{i-1} e_{i+1}. In the second case the prefix of length ii gains an operand and loses an operator, so the balloting property can only get easier. The operator now has the neighbours ei+1e_{i+1}, an operand, and ei+2e_{i+2}, so the only new pair is eiei+2e_i e_{i+2}. All other prefixes have the same counts, and all other neighbours are the same. □\square

Theorem 1 (every state is a slicing floorplan). Every word that the search visits is a normalized Polish expression of the nn blocks. Its cost is computed exactly, and the returned word is a visited word of least cost. If the cost is the area, the returned area is at least the least area of a slicing floorplan of the blocks, which is at least the sum of the block areas.

Proof. Line L1 starts with 1 2 V 3 V⋯n V1\,2\,V\,3\,V \cdots n\,V, which is normalized: every operator follows an operand, and the prefix counts are 1,2,1,2,1,…1, 2, 1, 2, 1, \ldots. Line L6 applies M1, M2 or a checked M3, so by Lemmas 1 to 3 and induction every visited word is normalized. The cost of a word is the least area over the allowed shapes of the blocks, computed by Stockmeyer's floorplan sizing, which is exact, plus λ\lambda times the wire length of the placement that the sizing returns, computed with fractions. Line L10 keeps the best word seen. Each visited word is a slicing floorplan of the blocks, so its area is at least the least area of all slicing floorplans. The blocks do not overlap in a realization (see the normalized Polish expression page), so the area of the floorplan is at least the sum of the block areas. □\square

Theorem 2 (termination). The search stops after at most min⁡(smax⁡,sε)⋅(2N+1)\min(s_{\max}, s_\varepsilon) \cdot (2N + 1) moves, where N=knN = k n, smax⁡s_{\max} is the limit on the number of temperatures, and sε=⌈log⁡(ε/T0)/log⁡r⌉+1s_\varepsilon = \lceil \log(\varepsilon / T_0) / \log r \rceil + 1 for 0<r<10 < r < 1 and T0>εT_0 > \varepsilon.

Proof. The inner loop of lines L5 to L12 counts its tries and stops when tries>2Ntries > 2N, so it runs at most 2N+12N + 1 times. Line L13 multiplies TT by rr, so after ss temperatures T=rsT0T = r^s T_0, which is below ε\varepsilon once s≥log⁡(ε/T0)/log⁡rs \ge \log(\varepsilon / T_0) / \log r, and line L14 then stops the outer loop. The implementation also stops after smax⁡s_{\max} temperatures. □\square

What is not proved here. Wong and Liu prove that the three moves connect all normalized Polish expressions of nn blocks, so the search can reach the optimum slicing floorplan from any start. The tests check this by a breadth-first search over all normalized words for n≤5n \le 5. The search is a heuristic with the geometric schedule: there is no bound on the gap between the returned cost and the optimum. The convergence theorems for simulated annealing need a logarithmic schedule that is far too slow for practice. ■\blacksquare

Complexity

A move copies the word in O(n)O(n) time. The cost of the new word takes O(nd)O(n d) time for blocks with two shapes, where dd is the depth of its slicing tree, because Stockmeyer's merge is linear in the lengths of the fronts. The wire length takes O(P)O(P) time for PP pins. One temperature makes at most 2N+1=O(kn)2N + 1 = O(k n) moves. So the time is O(s⋅kn⋅(nd+P))O(s \cdot k n \cdot (n d + P)) for ss temperatures. With T0T_0, rr and ε\varepsilon fixed, s=O(log⁡(T0/ε))s = O(\log(T_0 / \varepsilon)). The space is O(nd)O(n d) for the fronts of one evaluation.

The evaluation can be incremental: a move changes a few nodes of the tree, and only their fronts and the fronts of their ancestors need new merges. The implementation evaluates each word from scratch.

Properties

  • No duplicate states. Each slicing floorplan has exactly one normalized word, so the search does not count a floorplan twice. This is the main reason for the normal form.
  • Every state is legal. There is no penalty for overlap, because no state has overlap.
  • Randomized. The result depends on the seed. With a fixed seed it is the same each run.
  • Slicing only. The search cannot reach a non-slicing floorplan such as a pinwheel of five blocks.

Variants and improvements

  • L-shaped blocks. The journal version adds operators for L-shaped blocks and a modified sizing.
  • Fixed outline. For a fixed chip outline, the cost adds a penalty for the part of the floorplan outside the outline, as in the work of Adya and Markov on sequence pairs.
  • Other representations. The same annealing runs over sequence pairs, B*-trees and O-trees, which also reach non-slicing packings.
  • Other moves. Later floorplanners rotate single blocks as a move, or change the aspect ratio of a soft block, instead of a full sizing for each word.
  • Placement. The same annealing scheme for cells is simulated annealing placement.

When to use it

Use the method for a slicing floorplan of tens to a few hundred blocks, when the design flow prefers slicing structures (for example for routing channels or for hierarchical design), and when blocks have rotations or soft shapes, because the sizing then finds the best shapes for each tree. For packings that need not be slicing, an annealing over a B*-tree or a sequence pair can reach smaller areas.

Pitfalls

  • M3 without the balloting test. Swapping an operand to the right of an operator can leave a prefix with as many operators as operands. The word is then not a Polish expression, and the stack evaluation fails.
  • M3 without the neighbour test. The swap can put two equal operators side by side. The word is then a valid Polish expression, but not a normalized one, and the search has two words for one floorplan.
  • A wrong start temperature. With T0T_0 too low the search is only a local search. With T0T_0 too high it wastes time. Estimate it from a short random walk, as in line L2.
  • The cost of one part only. Choosing the best shape of each subtree for its own area is wrong; use the whole front at each node, as Stockmeyer's sizing does.
  • Comparing floats for equality. The code keeps areas and wire lengths as exact fractions, and uses floats only for the acceptance probability.

Implementations

The Python module implements the three moves with the O(1)O(1) test for M3, the cost with Stockmeyer's merge and an exact wire length, and the annealing loop of the pseudocode. A random generator with a fixed seed is passed in. The tests check that the M3 test agrees with a full check of the normal form at every position, that the moves reach all normalized words for n≤5n \le 5 by breadth-first search, that 600 random walks of moves keep the normal form, that the realized blocks never overlap, and that the annealing returns a normalized word whose area is at least the exhaustive optimum and at least the block area, the same for the same seed.

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.

wong_liu_floorplanning.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/wong-liu-floorplanning/. The authors are listed in prov/0Y56MN.jsonl.

"""Wong and Liu's floorplanning by annealing over normalized Polish expressions.

Tokens are block ids (ints) and the operators "V" (first part to the left of
the second) and "H" (first part below the second). The cost of a word is
area + lam * HPWL, where the area is the least area over the allowed shapes of
the blocks (computed with Stockmeyer's merge of shape fronts) and HPWL is the
half-perimeter wire length of the nets over the centres of the blocks.
"""

import math
import random
from fractions import Fraction
from typing import Callable, Optional


def is_op(t) -> bool:
    """Return True for the operators "H" and "V"."""
    return t == "H" or t == "V"


def is_normalized(e: list) -> bool:
    """Return True if e is a normalized Polish expression."""
    c = 0
    for k, t in enumerate(e):
        if is_op(t):
            c -= 1
            if c < 1 or e[k - 1] == t:
                return False
        else:
            c += 1
    ops = [t for t in e if not is_op(t)]
    return c == 1 and len(set(ops)) == len(ops)


# ----------------------------------------------------------------- the moves


def move_m1(e: list, rng: random.Random) -> list:
    """M1: swap two operands that are next to each other in the operand order."""
    pos = [k for k, t in enumerate(e) if not is_op(t)]
    if len(pos) < 2:
        return list(e)
    a = rng.randrange(len(pos) - 1)
    f = list(e)
    i, j = pos[a], pos[a + 1]
    f[i], f[j] = f[j], f[i]
    return f


def chains(e: list) -> list[tuple[int, int]]:
    """Return the maximal runs of operators as half-open index ranges."""
    out = []
    k = 0
    while k < len(e):
        if is_op(e[k]):
            s = k
            while k < len(e) and is_op(e[k]):
                k += 1
            out.append((s, k))
        else:
            k += 1
    return out


def move_m2(e: list, rng: random.Random) -> list:
    """M2: complement one chain of operators (H becomes V and V becomes H)."""
    cs = chains(e)
    if not cs:
        return list(e)
    s, t = cs[rng.randrange(len(cs))]
    f = list(e)
    for k in range(s, t):
        f[k] = "V" if f[k] == "H" else "H"
    return f


def m3_ok(e: list, i: int, prefix_ops: list[int]) -> bool:
    """Tell whether swapping e[i] and e[i + 1] (an operand and an operator) keeps e normalized.

    prefix_ops[k] is the number of operators in e[0 .. k - 1]. The test takes
    O(1) time.
    """
    a, b = e[i], e[i + 1]
    if is_op(a) == is_op(b):
        return False
    if not is_op(a):
        # The operand moves right, the operator b moves to position i. The
        # prefix e[0 .. i] then has prefix_ops[i] + 1 operators and i - prefix_ops[i]
        # operands; balloting needs more operands than operators.
        if 2 * (prefix_ops[i] + 1) >= i + 1:
            return False
        return i == 0 or e[i - 1] != b
    # The operator a moves right, to position i + 1; its new right neighbour is e[i + 2].
    return i + 2 >= len(e) or e[i + 2] != a


def move_m3(e: list, rng: random.Random, tries: int = 50) -> list:
    """M3: swap a neighbouring operand and operator if the word stays normalized."""
    if len(e) < 3:
        return list(e)
    prefix = [0]
    for t in e:
        prefix.append(prefix[-1] + (1 if is_op(t) else 0))
    for _ in range(tries):
        i = rng.randrange(len(e) - 1)
        if m3_ok(e, i, prefix):
            f = list(e)
            f[i], f[i + 1] = f[i + 1], f[i]
            return f
    return list(e)


# ------------------------------------------------------------------ the cost


def _front(shapes: list[tuple[int, int]]) -> list:
    out: list = []
    for k in sorted(range(len(shapes)), key=lambda q: shapes[q]):
        w, h = shapes[k]
        if not out or h < out[-1][1]:
            out.append((w, h, k))
    return out


def _merge(a: list, b: list, vertical: bool) -> list:
    if not vertical:  # exchange the coordinates and use the vertical merge
        ta = [(h, w, k) for (w, h, k) in reversed(a)]
        tb = [(h, w, k) for (w, h, k) in reversed(b)]
        res = _merge(ta, tb, True)
        na, nb = len(a), len(b)
        return [(w, h, (na - 1 - i, nb - 1 - j)) for (h, w, (i, j)) in reversed(res)]
    i = j = 0
    out = []
    while True:
        out.append((a[i][0] + b[j][0], max(a[i][1], b[j][1]), (i, j)))
        if a[i][1] > b[j][1]:
            if i == len(a) - 1:
                return out
            i += 1
        elif b[j][1] > a[i][1]:
            if j == len(b) - 1:
                return out
            j += 1
        else:
            if i == len(a) - 1 or j == len(b) - 1:
                return out
            i, j = i + 1, j + 1


def realize(e: list, shapes: dict) -> tuple[int, dict]:
    """Return the least area of e over the allowed shapes and a placement that reaches it.

    The placement maps each block to (x, y, w, h).
    """
    st: list = []
    for t in e:
        if is_op(t):
            b, a = st.pop(), st.pop()
            st.append([t, _merge(a[1], b[1], t == "V"), a, b])
        else:
            st.append([t, _front(shapes[t])])
    root = st[0]
    fr = root[1]
    best = min(range(len(fr)), key=lambda k: (fr[k][0] * fr[k][1], fr[k][0]))
    place: dict = {}
    todo = [(root, best, 0, 0)]
    while todo:
        node, k, x, y = todo.pop()
        w, h, back = node[1][k]
        if len(node) == 2:
            place[node[0]] = (x, y, w, h)
            continue
        i, j = back
        a, b = node[2], node[3]
        todo.append((a, i, x, y))
        if node[0] == "V":
            todo.append((b, j, x + a[1][i][0], y))
        else:
            todo.append((b, j, x, y + a[1][i][1]))
    return fr[best][0] * fr[best][1], place


def cost(e: list, shapes: dict, nets: list, lam: Fraction) -> Fraction:
    """Return area + lam * HPWL over the block centres, as an exact fraction."""
    area, place = realize(e, shapes)
    if not nets or lam == 0:
        return Fraction(area)
    wl2 = 0  # twice the HPWL, so that the centres are integers
    for net in nets:
        xs = [2 * place[b][0] + place[b][2] for b in net]
        ys = [2 * place[b][1] + place[b][3] for b in net]
        wl2 += max(xs) - min(xs) + max(ys) - min(ys)
    return Fraction(area) + lam * Fraction(wl2, 2)


# ------------------------------------------------------------- the annealing


def wong_liu_floorplan(
    shapes: dict[int, list[tuple[int, int]]],
    rng: random.Random,
    nets: Optional[list[list[int]]] = None,
    lam: Fraction = Fraction(0),
    r: float = 0.85,
    k: int = 10,
    p0: float = 0.9,
    eps: float = 1e-3,
    max_temps: int = 200,
    on_state: Optional[Callable[[list], None]] = None,
) -> tuple[list, Fraction]:
    """Anneal over normalized Polish expressions and return (best word, its cost).

    r is the cooling ratio, N = k n is the number of uphill moves per
    temperature, p0 is the probability to accept an average uphill move at the
    start. on_state, if given, is called with each word the search moves to.
    """
    nets = nets or []
    blocks = sorted(shapes)
    n = len(blocks)
    e = [blocks[0]]  # @line L1
    for b in blocks[1:]:
        e += [b, "V"]
    cur = cost(e, shapes, nets, lam)
    best, best_cost = list(e), cur
    if n == 1:
        return best, best_cost
    moves = (move_m1, move_m2, move_m3)
    ups = []  # @line L2
    for _ in range(4 * n):
        d = cost(rng.choice(moves)(e, rng), shapes, nets, lam) - cur
        if d > 0:
            ups.append(d)
    t = float(sum(ups) / len(ups)) / -math.log(p0) if ups else 1.0
    big_n = k * n
    for _ in range(max_temps):  # @line L3
        tries = uphill = rejects = 0  # @line L4
        while True:  # @line L5
            f = rng.choice(moves)(e, rng)  # @line L6
            tries += 1  # @line L7
            fc = cost(f, shapes, nets, lam)
            d = fc - cur
            if d <= 0 or rng.random() < math.exp(-float(d) / t):  # @line L8
                if d > 0:  # @line L9
                    uphill += 1
                e, cur = f, fc  # @line L10
                if on_state is not None:
                    on_state(e)
                if cur < best_cost:
                    best, best_cost = list(e), cur
            else:  # @line L11
                rejects += 1
            if uphill > big_n or tries > 2 * big_n:  # @line L12
                break
        t *= r  # @line L13
        if rejects / tries > 0.95 or t < eps:  # @line L14
            break
    return best, best_cost  # @line L15
test_wong_liu_floorplanning.py 169 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/wong-liu-floorplanning/. The authors are listed in prov/0Y56MN.jsonl.

import itertools
import random
from collections import deque
from fractions import Fraction

from wong_liu_floorplanning import (
    chains,
    cost,
    is_normalized,
    m3_ok,
    move_m1,
    move_m2,
    move_m3,
    realize,
    wong_liu_floorplan,
)


def all_npe(n: int) -> list[tuple]:
    """All normalized Polish expressions on blocks 0..n-1, by brute force over words."""
    out = []
    for opos in itertools.combinations(range(2 * n - 1), n - 1):
        for perm in itertools.permutations(range(n)):
            for ops in itertools.product("HV", repeat=n - 1):
                w: list = [None] * (2 * n - 1)
                for p, o in zip(opos, ops):
                    w[p] = o
                it = iter(perm)
                for i in range(2 * n - 1):
                    if w[i] is None:
                        w[i] = next(it)
                if is_normalized(w):
                    out.append(tuple(w))
    return out


def neighbours(e: tuple) -> set[tuple]:
    """All words one move M1, M2 or M3 away from e."""
    out = set()
    pos = [k for k, t in enumerate(e) if t not in ("H", "V")]
    for a in range(len(pos) - 1):
        f = list(e)
        f[pos[a]], f[pos[a + 1]] = f[pos[a + 1]], f[pos[a]]
        out.add(tuple(f))
    for s, t in chains(list(e)):
        f = list(e)
        for k in range(s, t):
            f[k] = "V" if f[k] == "H" else "H"
        out.add(tuple(f))
    prefix = [0]
    for t in e:
        prefix.append(prefix[-1] + (t in ("H", "V")))
    for i in range(len(e) - 1):
        f = list(e)
        f[i], f[i + 1] = f[i + 1], f[i]
        assert m3_ok(list(e), i, prefix) == (
            (e[i] in ("H", "V")) != (e[i + 1] in ("H", "V")) and is_normalized(f)
        )
        if m3_ok(list(e), i, prefix):
            out.add(tuple(f))
    return out


def overlap(p, q) -> bool:
    return p[0] < q[0] + q[2] and q[0] < p[0] + p[2] and p[1] < q[1] + q[3] and q[1] < p[1] + p[3]


def test_moves_on_example() -> None:
    e = [0, 1, "V", 2, "H", 3, "V"]
    assert chains(e) == [(2, 3), (4, 5), (6, 7)]
    prefix = [0, 0, 0, 1, 1, 2, 2, 3]
    assert [i for i in range(6) if m3_ok(e, i, prefix)] == [2, 4]
    assert not m3_ok(e, 3, prefix)  # 0 1 V H 2 3 V breaks the balloting property
    assert chains([0, 1, "V", 2, 3, "H", "V"]) == [(2, 3), (5, 7)]
    rng = random.Random(0)
    assert move_m2([0, 1, "V", 2, 3, "H", "V"], random.Random(1)) in (
        [0, 1, "H", 2, 3, "H", "V"],
        [0, 1, "V", 2, 3, "V", "H"],
    )
    assert sorted(t for t in move_m1(e, rng) if t not in ("H", "V")) == [0, 1, 2, 3]


def test_m3_check_and_connectivity() -> None:
    for n in range(1, 6):
        words = all_npe(n)
        start = [0]
        for b in range(1, n):
            start += [b, "V"]
        seen = {tuple(start)}
        queue = deque([tuple(start)])
        while queue:
            e = queue.popleft()
            for f in neighbours(e):
                assert is_normalized(list(f))
                if f not in seen:
                    seen.add(f)
                    queue.append(f)
        assert seen == set(words)


def test_random_moves_keep_normal_form() -> None:
    rng = random.Random(3)
    for _ in range(600):
        n = rng.randint(1, 12)
        e = [0]
        for b in range(1, n):
            e += [b, "V"]
        for _ in range(20):
            e = rng.choice((move_m1, move_m2, move_m3))(e, rng)
            assert is_normalized(e)
            assert sorted(t for t in e if t not in ("H", "V")) == list(range(n))


def test_realize_no_overlap() -> None:
    rng = random.Random(4)
    for _ in range(300):
        n = rng.randint(1, 10)
        shapes = {}
        for b in range(n):
            w, h = rng.randint(1, 9), rng.randint(1, 9)
            shapes[b] = [(w, h), (h, w)]
        e = [0]
        for b in range(1, n):
            e += [b, "V"]
        for _ in range(10):
            e = rng.choice((move_m1, move_m2, move_m3))(e, rng)
        area, place = realize(e, shapes)
        rects = list(place.values())
        assert area >= sum(w * h for w, h in (s[0] for s in shapes.values()))
        for i in range(n):
            assert (rects[i][2], rects[i][3]) in shapes[list(place)[i]]
            for j in range(i + 1, n):
                assert not overlap(rects[i], rects[j])


def test_annealing_fixed_seed() -> None:
    rng = random.Random(5)
    for trial in range(6):
        n = 4 + trial % 2
        shapes = {}
        for b in range(n):
            w, h = rng.randint(1, 6), rng.randint(1, 6)
            shapes[b] = [(w, h), (h, w)]
        opt = min(cost(list(e), shapes, [], Fraction(0)) for e in all_npe(n))
        visited = []

        def check(e: list) -> None:
            assert is_normalized(e)
            visited.append(cost(e, shapes, [], Fraction(0)))

        best, c = wong_liu_floorplan(shapes, random.Random(100 + trial), k=5, on_state=check)
        assert is_normalized(best)
        assert c == cost(best, shapes, [], Fraction(0))
        assert c >= opt >= sum(s[0][0] * s[0][1] for s in shapes.values())
        assert visited and c == min(visited + [c])
        again, c2 = wong_liu_floorplan(shapes, random.Random(100 + trial), k=5)
        assert (again, c2) == (best, c)


def test_wirelength_term() -> None:
    shapes = {0: [(2, 2)], 1: [(2, 2)], 2: [(2, 2)], 3: [(2, 2)]}
    nets = [[0, 3]]
    e = [0, 1, "V", 2, "V", 3, "V"]
    assert cost(e, shapes, nets, Fraction(1)) == 16 + 6
    best, c = wong_liu_floorplan(shapes, random.Random(9), nets=nets, lam=Fraction(1), k=5)
    assert c == 16 + 2  # a 4 by 4 square with blocks 0 and 3 side by side

History

Kirkpatrick, Gelatt and Vecchi proposed simulated annealing for placement and other problems in 1983. Otten had described slicing structures in 1982, and Stockmeyer had given the exact sizing of a slicing tree in 1983. Wong and Liu combined these in 1986: annealing over normalized Polish expressions, three moves, and a cost of area plus wire length. The journal version of 1989 added L-shaped blocks. Later floorplanners replaced the word by representations of non-slicing packings, the sequence pair in 1995 and the B*-tree in 2000, but kept the annealing scheme.

References

  1. D. F. Wong and C. L. Liu, A new algorithm for floorplan design, Proceedings of the 23rd ACM/IEEE Design Automation Conference, 101 to 107, 1986, the moves M1, M2 and M3, the proof that they connect all normalized Polish expressions, the cost of area plus weighted wire length, and the cooling schedule
  2. D. F. Wong and C. L. Liu, Floorplan design of VLSI circuits, Algorithmica 4, 263 to 291, 1989, the journal version, with L-shaped blocks
  3. S. Kirkpatrick, C. D. Gelatt Jr. and M. P. Vecchi, Optimization by simulated annealing, Science 220(4598), 671 to 680, 1983, simulated annealing with the Metropolis rule and a geometric schedule
  4. Larry Stockmeyer, Optimal orientations of cells in slicing floorplan designs, Information and Control 57(2-3), 91 to 101, 1983, the shape list merge that gives the cost of a slicing tree
  5. Bruce Hajek, Cooling schedules for optimal annealing, Mathematics of Operations Research 13(2), 311 to 329, 1988, the logarithmic schedule under which annealing converges to an optimum
  6. 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 3, Chip Planning (floorplanning by simulated annealing over Polish expressions; general locator)

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