Algorithm Search⌘K

Algorithmcore

Stockmeyer's floorplan sizing

Also called optimal orientation of slicing floorplans.

Finds the least area realization of a slicing floorplan with shape choices per block by merging shape lists bottom up, in O(n d) time for depth d.

Time
O(n d) worst · averageO(n) best
Space
O(n d) extra
Where
d = the depth of the slicing tree; n = the number of blocks
Properties
deterministicexactiterative
Origin
Larry Stockmeyer, 1983

Stockmeyer's floorplan sizing chooses a shape for each block of a slicing floorplan so that the area of the floorplan is the least possible. Each block has a few allowed shapes, for example a rectangle and its rotation. The algorithm goes up the slicing tree and keeps, at each node, only the width and height pairs that no other pair beats in both coordinates, the Pareto front of the node. Two fronts are merged in time linear in their lengths, so the whole run takes O(nd)O(n d) time for nn blocks and a tree of depth dd. Stockmeyer gave it in 1983 and proved in the same paper that the orientation problem is NP-complete for floorplans that are not slicing.

In plain words

You build a wall from boxes, and each box can lie flat or stand up. The plan says which boxes go side by side and which go on top of each other, but not how each box turns. You want the wall to fit in the smallest frame.

For each part of the plan, write down every useful size the part can have: a size is useful if no other size of the same part is both narrower and lower. Two parts side by side have a width that is the sum and a height that is the taller one. Go through both lists at the same time, and each time make the taller part lower. At the top of the plan you have a short list of sizes, and you take the one with the least area.

The problem

The input is a slicing tree, given as a Polish expression EE on nn blocks (see normalized Polish expression; here EE need not be normalized), and for each block ii a list SiS_i of allowed shapes (w,h)(w, h) of positive integers. A realization gives each block one shape of its list. The floorplan of a realization has the width and the height computed by the tree: a VV node adds the widths of its parts and takes the larger height, and an HH node takes the larger width and adds the heights. The output is a realization with the least area W⋅HW \cdot H, its width and height, and the front of all (W,H)(W, H) pairs.

In Stockmeyer's paper each block is a fixed rectangle that may turn by 90 degrees, so Si={(wi,hi),(hi,wi)}S_i = \{(w_i, h_i), (h_i, w_i)\}. The same algorithm works for any finite lists, which is the form used with shape functions.

The algorithm

A shape (w,h)(w, h) dominates (w′,h′)(w', h') if w≤w′w \le w', h≤h′h \le h' and the two differ. A front is a list of shapes, none of which dominates another, by increasing width. In a front the heights strictly decrease.

  1. STOCKMEYER(E, S) ▷ E: a Polish expression; S_i: the allowed shapes of block i
  2. 1for each token t of E, from left to right, with a stack do
  3. 2if t is a block i then push PARETO(S_i), the front of S_i
  4. 3else pop B, then pop A; push MERGE-V(A, B) if t = V, else MERGE-H(A, B)
  5. 4R ← the list that is left on the stack
  6. 5k ← the entry of R with the least W · H
  7. 6follow the back pointers down from entry k, and give each block its shape
  8. 7return W_k · H_k and the shapes
  9. MERGE-V(A, B) ▷ A, B: fronts, widths increasing, heights decreasing
  10. 8i ← 1, j ← 1, R ← an empty list
  11. 9loop
  12. 10append (w_A[i] + w_B[j], max(h_A[i], h_B[j])) with the back pointer (i, j) to R
  13. 11if h_A[i] > h_B[j] then (if i = |A| then return R); i ← i + 1
  14. 12else if h_B[j] > h_A[i] then (if j = |B| then return R); j ← j + 1
  15. 13else (if i = |A| or j = |B| then return R); i ← i + 1, j ← j + 1

MERGE-H is MERGE-V with the roles of width and height exchanged: it starts at the widest entry of each list and moves the pointer of the wider part. The idea of MERGE-V is in lines L11 to L13. The height of the combination is the height of the taller part, so the only way to get a lower combination is to give the taller part its next, lower shape. The other part keeps its narrowest shape that is low enough. Each entry of RR is the narrowest combination with its height.

Example

The tree is E=1 2 V 3 4 V HE = 1\,2\,V\,3\,4\,V\,H: blocks 1 and 2 side by side at the bottom, blocks 3 and 4 side by side on top. The blocks are 1:2×41: 2 \times 4, 2:1×32: 1 \times 3, 3:3×23: 3 \times 2 and 4:2×24: 2 \times 2 (width by height), and each one may turn.

node front (width by height) how it is made
1 2×42 \times 4, 4×24 \times 2 the two orientations
2 1×31 \times 3, 3×13 \times 1 the two orientations
1 2 V1\,2\,V 3×43 \times 4, 5×35 \times 3, 7×27 \times 2 (2×4,1×3)(2{\times}4, 1{\times}3), then move 1, then move 2
3 2×32 \times 3, 3×23 \times 2 the two orientations
4 2×22 \times 2 a square has one shape
3 4 V3\,4\,V 4×34 \times 3, 5×25 \times 2 (2×3,2×2)(2{\times}3, 2{\times}2), then move 3; then the heights are equal and 4 is at its end
root, HH 4×74 \times 7, 5×55 \times 5, 7×47 \times 4 see below

MERGE-H at the root starts with the widest entries 7×27 \times 2 and 5×25 \times 2, which give 7×47 \times 4. The first part is wider, so it moves to 5×35 \times 3, which gives 5×55 \times 5. Now both widths are 5, so both move, to 3×43 \times 4 and 4×34 \times 3, which give 4×74 \times 7. The second part is wider and at its end, so the merge stops. The areas are 28, 25 and 28, so the least area is 25. The back pointers of 5×55 \times 5 lead to 5×35 \times 3 and 5×25 \times 2, and from there to block 1 turned to 4×24 \times 2, block 2 as 1×31 \times 3, block 3 as 3×23 \times 2 and block 4. The block area is 21, so 4 units are empty. Without any turn the floorplan is 5×6=305 \times 6 = 30.

Correctness

Two facts carry the proof. First, the width and the height of a node only grow when the width or the height of a part grows. So a part may replace a dominated shape by one that dominates it, and the front of a node is the front of the combinations of the fronts of its children. Second, MERGE-V keeps this invariant: when it writes an entry of height MM, every earlier entry of each list is taller than MM. Then the current pair is the narrowest combination of height at most MM, so it is on the front. A lower combination must lower the taller part, which is the move of lines L11 to L13, so no front pair is skipped. The area is monotone in both coordinates, so the least area is on the root front. The full proof is in the correctness proof.

Proof: Stockmeyer's sizing returns a least-area realization of a slicing floorplan in O(n d) timefull

We use the pseudocode of the page. A shape is a pair (w,h)(w, h) of positive integers. The shape (w,h)(w, h) dominates (w′,h′)(w', h') if w≤w′w \le w' and h≤h′h \le h' and the two are different. For a set PP of shapes, the front of PP is the set of shapes of PP that no shape of PP dominates. We write a front as a list by increasing width. Then the heights strictly decrease, because two shapes of a front with w≤w′w \le w' and h≤h′h \le h' would be equal or one would dominate the other.

For a node vv of the slicing tree, a realization of vv gives each block below vv one of its allowed shapes. Its width and height are computed as in EVALUATE on the page of the normalized Polish expression. Let P(v)P(v) be the set of (W,H)(W, H) pairs of all realizations of vv, and let F(v)F(v) be its front.

Lemma 1 (monotonicity). At a VV node with children aa and bb, the pair of the node is (Wa+Wb,max⁡(Ha,Hb))(W_a + W_b, \max(H_a, H_b)), and at an HH node it is (max⁡(Wa,Wb),Ha+Hb)(\max(W_a, W_b), H_a + H_b). Both maps do not decrease when any argument increases. So if a realization of aa is changed to one whose pair dominates the old pair, the pair of the node does not get larger in either coordinate.

Proof. Sums and maxima of nonnegative numbers are monotone in each argument. □\square

Lemma 2. F(v)F(v) is the front of the set of pairs obtained by combining one pair of F(a)F(a) with one pair of F(b)F(b).

Proof. Let pp be a pair of F(v)F(v), from realizations of aa and bb with pairs pap_a and pbp_b. If pa∉F(a)p_a \notin F(a), some qa∈F(a)q_a \in F(a) dominates pap_a (the set is finite), and by Lemma 1 the combination of qaq_a and pbp_b is at most pp in both coordinates. It is in P(v)P(v) and pp is in the front, so it is equal to pp. Do the same for bb. So every pair of F(v)F(v) is a combination of front pairs. All combinations of front pairs are in P(v)P(v), so the front of the combinations is F(v)F(v). □\square

Lemma 3 (MERGE-V). Let AA and BB be fronts, by increasing width. MERGE-V(A,B)(A, B) returns the front of {(wA[i]+wB[j],max⁡(hA[i],hB[j]))}\{(w_A[i] + w_B[j], \max(h_A[i], h_B[j]))\}, by increasing width, with ∣R∣≤∣A∣+∣B∣−1|R| \le |A| + |B| - 1. Each entry has a back pointer (i,j)(i, j) to a pair that gives it.

Proof. Let M=max⁡(hA[i],hB[j])M = \max(h_A[i], h_B[j]) for the current (i,j)(i, j). We claim this invariant at line L10: every i′<ii' < i has hA[i′]>Mh_A[i'] > M, and every j′<jj' < j has hB[j′]>Mh_B[j'] > M. At the start there are no such indices. If line L11 moves ii to i+1i + 1, then hA[i]>hB[j]h_A[i] > h_B[j] and M=hA[i]M = h_A[i]. The new maximum M′M' is max⁡(hA[i+1],hB[j])<hA[i]\max(h_A[i+1], h_B[j]) < h_A[i], because the heights of AA decrease. Every i′≤ii' \le i has hA[i′]≥hA[i]>M′h_A[i'] \ge h_A[i] > M', and every j′<jj' < j had hB[j′]>M≥M′h_B[j'] > M \ge M'. Line L12 is the same with the roles of AA and BB exchanged. In line L13, hA[i]=hB[j]=Mh_A[i] = h_B[j] = M, both indices move, and M′<MM' < M for the same reason.

So at line L10, ii is the least index with hA[i]≤Mh_A[i] \le M and jj is the least index with hB[j]≤Mh_B[j] \le M, and the widths increase with the index. A combination with height at most MM needs hA[i′]≤Mh_A[i'] \le M and hB[j′]≤Mh_B[j'] \le M, so i′≥ii' \ge i and j′≥jj' \ge j, and its width is at least wA[i]+wB[j]w_A[i] + w_B[j]. So the entry of line L10 is the narrowest combination of height at most MM, and its height is exactly MM. Hence no combination dominates it, and it is on the front.

The values of MM strictly decrease from step to step, as shown, and the widths strictly increase, because at least one index moves. So RR lists distinct front pairs by increasing width. Write the entries as (W1,M1),…,(Wt,Mt)(W_1, M_1), \ldots, (W_t, M_t). It remains to show that every front pair (W∗,M∗)(W^*, M^*) is one of them. The first entry is the narrowest of all combinations, so M∗≤M1M^* \le M_1, or the first entry would dominate (W∗,M∗)(W^*, M^*). When the loop stops after entry tt, the index of a list that gives MtM_t is at the end of that list, so every combination has height at least MtM_t, and M∗≥MtM^* \ge M_t. Now take an entry s<ts < t and a combination (i′,j′)(i', j') of height h<Msh < M_s. Each index that moved after entry ss pointed to a part of height exactly MsM_s, and the part i′i' or j′j' of the same list has height less than MsM_s, so it lies after the moved index. So i′≥is+1i' \ge i_{s+1} and j′≥js+1j' \ge j_{s+1}, and the width of the combination is at least Ws+1W_{s+1}. If Ms+1<h<MsM_{s+1} < h < M_s, the entry s+1s + 1 dominates the combination. So no front pair has a height strictly between two consecutive entries. A front pair of height MsM_s is the narrowest combination of height at most MsM_s, so it is entry ss. Hence every front pair is listed.

Each step before the last moves at least one index, and the indices can move at most ∣A∣−1|A| - 1 and ∣B∣−1|B| - 1 times. So there are at most ∣A∣+∣B∣−1|A| + |B| - 1 steps and entries. □\square

Lemma 4 (MERGE-H). MERGE-H(A,B)(A, B) returns the front of {(max⁡(wA[i],wB[j]),hA[i]+hB[j])}\{(\max(w_A[i], w_B[j]), h_A[i] + h_B[j])\} with at most ∣A∣+∣B∣−1|A| + |B| - 1 entries.

Proof. Exchange the two coordinates. A front by increasing width becomes a front by decreasing width, so reversing the lists gives inputs for MERGE-V, and the reverse of the output, with the coordinates exchanged back, is the front of the HH combinations by Lemma 3. □\square

Theorem 1 (correctness). STOCKMEYER returns the least area W⋅HW \cdot H over all realizations of the floorplan, and shapes of the blocks that reach it.

Proof. For a leaf, line L2 pushes the front of the allowed shapes. By Lemmas 2, 3 and 4 and induction on the tree, line L3 pushes F(v)F(v) for each node vv. So R=F(r)R = F(r) for the root rr. The area W⋅HW \cdot H is monotone in both coordinates, so a realization of least area can be changed to one whose pair is on the front without making the area larger. Hence the least area over F(r)F(r), taken in line L5, is the least area over all realizations. The back pointers of each entry point to entries of the children that combine to it, so line L6 reaches one shape for each leaf, and by induction the realization built from these shapes has exactly the pair of entry kk. □\square

Theorem 2 (list lengths). Let kik_i be the number of non-dominated allowed shapes of block ii. For each node vv with ℓ(v)\ell(v) leaves, ∣F(v)∣≤∑i below vki−(ℓ(v)−1)|F(v)| \le \sum_{i \text{ below } v} k_i - (\ell(v) - 1). If every block has at most two shapes, a rectangle and its rotation, then ∣F(v)∣≤ℓ(v)+1|F(v)| \le \ell(v) + 1.

Proof. By induction with Lemmas 3 and 4: ∣F(v)∣≤∣F(a)∣+∣F(b)∣−1|F(v)| \le |F(a)| + |F(b)| - 1, and ℓ(v)=ℓ(a)+ℓ(b)\ell(v) = \ell(a) + \ell(b). With ki≤2k_i \le 2 the bound is 2ℓ(v)−ℓ(v)+12\ell(v) - \ell(v) + 1. □\square

Theorem 3 (time). Let K=∑ikiK = \sum_i k_i and let dd be the depth of the tree. STOCKMEYER takes O(Kd+∑i∣Si∣log⁡∣Si∣)O(K d + \sum_i |S_i| \log |S_i|) time. For blocks with two orientations this is O(nd)O(n d), which is O(n2)O(n^2) in the worst case and O(nlog⁡n)O(n \log n) for a balanced tree.

Proof. Line L2 sorts each list. A merge at node vv takes O(∣F(a)∣+∣F(b)∣)O(|F(a)| + |F(b)|) time, which is O(K(v))O(K(v)) where K(v)K(v) is the number of shapes of the blocks below vv, by Theorem 2. The sum of K(v)K(v) over the internal nodes counts each block ii with weight kik_i one time for each proper ancestor, so it is at most KdK d. Line L6 visits each node one time. With ki≤2k_i \le 2, K≤2nK \le 2n. The depth is at most n−1n - 1, and it is O(log⁡n)O(\log n) for a balanced tree. ■\blacksquare

Complexity

Each step of a merge, except the last one, moves at least one pointer. So a merge of fronts of lengths pp and qq takes O(p+q)O(p + q) time and returns at most p+q−1p + q - 1 entries. By induction, a node with ℓ\ell blocks below it has at most ℓ+1\ell + 1 entries when each block has two orientations, and at most K−(ℓ−1)K - (\ell - 1) entries when the blocks below it have KK non-dominated shapes in total.

  • Time. The merge at a node costs O(ℓ)O(\ell), and the sum of ℓ\ell over the internal nodes counts each block one time for each ancestor. So the time is O(nd)O(n d) with two shapes for each block, and O(Kd)O(K d) for lists with KK shapes in total, plus the sorting of the input lists.
  • Worst and best. The depth is at most n−1n - 1, so the worst case is O(n2)O(n^2), for a tree that is a long chain. A balanced tree has depth O(log⁡n)O(\log n), which gives O(nlog⁡n)O(n \log n). If all fronts stay short, for example with square blocks, the time is O(n)O(n).
  • Space. The fronts of all nodes are kept for the back pointers, which is O(nd)O(n d) entries in the worst case. If only the least area is needed, the fronts of the children can be freed after the merge, and the space is O(n)O(n) at a time on the stack.

Shi gave in 1995 an algorithm that takes O(Nlog⁡N)O(N \log N) time on every tree, where NN is the total number of shapes at the leaves, and a lower bound of Ω(Nlog⁡N)\Omega(N \log N) that matches it. Stockmeyer's bound and Shi's bound agree for balanced trees.

Properties

  • Exact for a fixed tree. The algorithm finds the least area over all realizations, not over a sample. It does not change the slicing tree.
  • Returns the whole front. A floorplanner that has a limit on the width or on the aspect ratio takes the best entry of the front that obeys the limit.
  • Deterministic and integer. All values are sums and maxima of the input integers.
  • Slicing only. For a general floorplan, given by constraint graphs, Stockmeyer proved that the choice of orientations with the least area is NP-complete.

Variants and improvements

  • Soft blocks. A block of fixed area AA and variable aspect ratio has the shape curve wh=Aw h = A. A staircase approximation of it gives a finite list, and the merge is the same. For an exact solution of soft blocks with a convex model, geometric programming is used.
  • Shi's algorithm. Shi changes the way the fronts are stored and merged, so that a chain-like tree no longer costs O(N2)O(N^2). The time is O(Nlog⁡N)O(N \log N) on every tree.
  • Inside a search. Wong-Liu floorplanning calls the sizing for each new tree that the annealing visits. A move changes a small part of the tree, so only the fronts of the changed nodes and of their ancestors need a new merge.
  • Bounded fronts. If the fronts are too long, keep only a fixed number of evenly spaced entries. The result is then a heuristic.

When to use it

Use the algorithm whenever the floorplan is slicing and each block has a list of shapes: rotations, a few layouts of a macro, or a staircase approximation of a soft block. It gives the exact best sizes in near-linear time. It does not choose the slicing tree. That is the job of a search such as Wong-Liu floorplanning.

Pitfalls

  • Taking the best shape of each part. The least area of a part is not the right choice for the parent. In the example, the least area of 1 2 V1\,2\,V is 3×4=123 \times 4 = 12 and the least area of 3 4 V3\,4\,V is 5×2=105 \times 2 = 10, but together they give 5×6=305 \times 6 = 30, not 25. Keep the whole front.
  • Equal heights. When the two heights are equal, both pointers must move. If only one moves, the next entry has the same height and a larger width, and the list is no longer a front.
  • The wrong end for H. MERGE-H must start at the widest entries. Starting at the narrow end gives wrong pairs.
  • Duplicate shapes. A square block gives the same shape twice. Remove duplicates and dominated shapes before the merge, or the length bound fails.
  • Recursion depth. A chain of nn blocks has depth n−1n - 1. Use the stack of the Polish expression, not a recursive walk.

Implementations

The Python module takes a Polish expression and a list of shapes for each block. It builds the fronts with a stack, merges with MERGE-V and with MERGE-H by exchanging the coordinates, and follows the back pointers to the chosen shapes. The tests check the example, and compare the least area and the whole root front with all 2n2^n orientations of 600 random trees of up to 8 blocks, and with all choices of 300 random trees of up to 6 blocks with up to 3 shapes each. They also check the length bounds of the fronts.

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.

stockmeyer_floorplan_sizing.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/stockmeyer-floorplan-sizing/. The authors are listed in prov/RH6JHQ.jsonl.

"""Stockmeyer's sizing of a slicing floorplan (1983).

The floorplan is a Polish expression: blocks are ints, "V" puts the first part
to the left of the second (widths add), "H" puts the first part below the
second (heights add). Each block has a list of allowed shapes (w, h), for
example a rectangle and its rotation. The algorithm computes, bottom up, the
list of non-dominated (width, height) pairs of each subtree, and returns a
choice of shapes with the least area of the whole floorplan.
"""

Shape = tuple[int, int]
# An entry of a shape list: (width, height, back pointer). For a leaf the back
# pointer is the index of the shape in the input list; for a node it is the
# pair of indices into the lists of the two children.
Entry = tuple[int, int, object]


def pareto(shapes: list[Shape]) -> list[Entry]:
    """Return the non-dominated shapes, by increasing width and decreasing height."""
    order = sorted(range(len(shapes)), key=lambda k: (shapes[k][0], shapes[k][1]))
    out: list[Entry] = []
    for k in order:
        w, h = shapes[k]
        if out and h >= out[-1][1]:
            continue  # not lower than a narrower (or equal) shape
        if out and w == out[-1][0]:
            out.pop()
        out.append((w, h, k))
    return out


def merge_v(a: list[Entry], b: list[Entry]) -> list[Entry]:
    """Non-dominated shapes of a beside b: widths add, the height is the larger one."""
    i = j = 0  # @line L8
    out: list[Entry] = []
    while True:  # @line L9
        out.append((a[i][0] + b[j][0], max(a[i][1], b[j][1]), (i, j)))  # @line L10
        if a[i][1] > b[j][1]:  # @line L11
            if i == len(a) - 1:
                return out
            i += 1
        elif b[j][1] > a[i][1]:  # @line L12
            if j == len(b) - 1:
                return out
            j += 1
        else:  # @line L13
            if i == len(a) - 1 or j == len(b) - 1:
                return out
            i += 1
            j += 1


def merge_h(a: list[Entry], b: list[Entry]) -> list[Entry]:
    """Non-dominated shapes of a below b: heights add, the width is the larger one.

    This is merge_v with widths and heights exchanged. In exchanged
    coordinates the lists run in the opposite order, so they are reversed.
    """
    ta = [(h, w, k) for (w, h, k) in reversed(a)]
    tb = [(h, w, k) for (w, h, k) in reversed(b)]
    na, nb = len(a), len(b)
    res = merge_v(ta, tb)
    return [(w, h, (na - 1 - i, nb - 1 - j)) for (h, w, (i, j)) in reversed(res)]


def shape_lists(tokens: list, shapes: dict[int, list[Shape]]) -> list:
    """Build the tree of the Polish expression with the shape list of each node.

    A leaf is [block, list]; a node is [op, list, left, right].
    """
    stack: list = []
    for t in tokens:  # @line L1
        if t != "H" and t != "V":  # @line L2
            stack.append([t, pareto(shapes[t])])
        else:  # @line L3
            if len(stack) < 2:
                raise ValueError("not a Polish expression")
            b = stack.pop()
            a = stack.pop()
            merged = merge_v(a[1], b[1]) if t == "V" else merge_h(a[1], b[1])
            stack.append([t, merged, a, b])
    if len(stack) != 1:
        raise ValueError("not a Polish expression")
    return stack[0]


def stockmeyer_sizing(
    tokens: list, shapes: dict[int, list[Shape]]
) -> tuple[int, int, int, dict[int, int], list[Shape]]:
    """Return (area, W, H, choice, front) for a slicing floorplan.

    choice[b] is the index in shapes[b] of the shape given to block b, front is
    the list of non-dominated (W, H) pairs of the whole floorplan, by
    increasing width. Among the shapes of least area, the narrowest is chosen.
    """
    root = shape_lists(tokens, shapes)
    front = root[1]  # @line L4
    best = min(range(len(front)), key=lambda k: (front[k][0] * front[k][1], front[k][0]))  # @line L5
    choice: dict[int, int] = {}
    todo = [(root, best)]  # @line L6
    while todo:
        node, k = todo.pop()
        entry = node[1][k]
        if len(node) == 2:
            choice[node[0]] = entry[2]
        else:
            i, j = entry[2]
            todo.append((node[2], i))
            todo.append((node[3], j))
    w, h = front[best][0], front[best][1]
    return w * h, w, h, choice, [(e[0], e[1]) for e in front]  # @line L7
test_stockmeyer_floorplan_sizing.py 102 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/stockmeyer-floorplan-sizing/. The authors are listed in prov/RH6JHQ.jsonl.

import itertools
import random

from stockmeyer_floorplan_sizing import merge_h, merge_v, pareto, shape_lists, stockmeyer_sizing


def evaluate(tokens: list, size: dict) -> tuple[int, int]:
    """Width and height of a Polish expression with one fixed shape per block."""
    st: list = []
    for t in tokens:
        if t == "V":
            b, a = st.pop(), st.pop()
            st.append((a[0] + b[0], max(a[1], b[1])))
        elif t == "H":
            b, a = st.pop(), st.pop()
            st.append((max(a[0], b[0]), a[1] + b[1]))
        else:
            st.append(size[t])
    return st[0]


def brute(tokens: list, shapes: dict) -> tuple[int, list]:
    """Least area and the non-dominated (W, H) pairs over all shape choices."""
    blocks = sorted(shapes)
    seen = set()
    for pick in itertools.product(*(range(len(shapes[b])) for b in blocks)):
        size = {b: shapes[b][k] for b, k in zip(blocks, pick)}
        seen.add(evaluate(tokens, size))
    front = sorted(p for p in seen if not any(q != p and q[0] <= p[0] and q[1] <= p[1] for q in seen))
    return min(w * h for w, h in seen), front


def random_tokens(rng: random.Random, leaves: list[int]) -> list:
    if len(leaves) == 1:
        return [leaves[0]]
    k = rng.randint(1, len(leaves) - 1)
    return random_tokens(rng, leaves[:k]) + random_tokens(rng, leaves[k:]) + [rng.choice("HV")]


def test_example() -> None:
    tokens = [1, 2, "V", 3, 4, "V", "H"]
    shapes = {1: [(2, 4), (4, 2)], 2: [(1, 3), (3, 1)], 3: [(3, 2), (2, 3)], 4: [(2, 2)]}
    root = shape_lists(tokens, shapes)
    assert [(e[0], e[1]) for e in root[2][1]] == [(3, 4), (5, 3), (7, 2)]
    assert [(e[0], e[1]) for e in root[3][1]] == [(4, 3), (5, 2)]
    area, w, h, choice, front = stockmeyer_sizing(tokens, shapes)
    assert front == [(4, 7), (5, 5), (7, 4)]
    assert (area, w, h) == (25, 5, 5)
    assert choice == {1: 1, 2: 0, 3: 0, 4: 0}
    assert evaluate(tokens, {1: (2, 4), 2: (1, 3), 3: (3, 2), 4: (2, 2)}) == (5, 6)


def test_merge_small() -> None:
    a = pareto([(1, 5), (2, 3), (4, 1)])
    b = pareto([(2, 4), (3, 2)])
    assert [(e[0], e[1]) for e in merge_v(a, b)] == [(3, 5), (4, 4), (5, 3), (7, 2)]
    pts = {(max(p[0], q[0]), p[1] + q[1]) for p in [(1, 5), (2, 3), (4, 1)] for q in [(2, 4), (3, 2)]}
    front = sorted(p for p in pts if not any(q != p and q[0] <= p[0] and q[1] <= p[1] for q in pts))
    assert [(e[0], e[1]) for e in merge_h(a, b)] == front


def test_single_block_and_squares() -> None:
    assert stockmeyer_sizing([5], {5: [(3, 2), (2, 3)]})[:3] == (6, 2, 3)
    area, w, h, choice, front = stockmeyer_sizing([1, 2, "V"], {1: [(2, 2)], 2: [(2, 2), (2, 2)]})
    assert (area, w, h) == (8, 4, 2) and front == [(4, 2)]


def test_orientations_against_all_choices() -> None:
    rng = random.Random(7)
    for trial in range(600):
        n = rng.randint(1, 8)
        leaves = list(range(n))
        rng.shuffle(leaves)
        tokens = random_tokens(rng, leaves)
        shapes = {}
        for b in leaves:
            w, h = rng.randint(1, 9), rng.randint(1, 9)
            shapes[b] = [(w, h), (h, w)]
        area, w, h, choice, front = stockmeyer_sizing(tokens, shapes)
        best, bfront = brute(tokens, shapes)
        assert area == best
        assert front == bfront
        assert len(front) <= n + 1
        assert evaluate(tokens, {b: shapes[b][choice[b]] for b in leaves}) == (w, h)


def test_general_shape_lists() -> None:
    rng = random.Random(8)
    for trial in range(300):
        n = rng.randint(1, 6)
        leaves = list(range(n))
        tokens = random_tokens(rng, leaves)
        shapes = {b: [(rng.randint(1, 9), rng.randint(1, 9)) for _ in range(rng.randint(1, 3))] for b in leaves}
        area, w, h, choice, front = stockmeyer_sizing(tokens, shapes)
        best, bfront = brute(tokens, shapes)
        assert (area, front) == (best, bfront)
        k = sum(len(pareto(shapes[b])) for b in leaves)
        assert len(front) <= k - (n - 1)
        assert evaluate(tokens, {b: shapes[b][choice[b]] for b in leaves}) == (w, h)

History

Otten introduced shape functions for slicing floorplans in 1982 and 1983, and added them at each cut. Stockmeyer gave the merge of non-dominated shape lists with the O(nd)O(n d) bound in 1983, in Information and Control, and proved that the orientation problem is NP-complete for general floorplans. Wong and Liu used the same combination of shapes inside their annealing floorplanner in 1986. Shi gave an algorithm with an optimal O(Nlog⁡N)O(N \log N) time in 1995.

References

  1. Larry Stockmeyer, Optimal orientations of cells in slicing floorplan designs, Information and Control 57(2-3), 91 to 101, 1983, the bottom-up merge of the lists of non-dominated shapes, the O(n d) time bound, and the NP-completeness of the orientation problem for general floorplans
  2. Ralph H. J. M. Otten, Efficient floorplan optimization, Proceedings of the IEEE International Conference on Computer Design (ICCD), 499 to 502, 1983, shape functions of slicing floorplans and their addition at the cuts
  3. Weiping Shi, An optimal algorithm for area minimization of slicing floorplans, Proceedings of the IEEE/ACM International Conference on Computer-Aided Design, 480 to 484, 1995, the O(n log n) algorithm in the number of realizations, the lower bound, and the statement that Stockmeyer's algorithm takes O(n^2) time in the worst case
  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 3, Chip Planning (floorplan sizing with shape functions; 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 proofH2 full proof
  • correctness: no review record reviews/RH6JHQ/proof-correctness.yaml
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