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.
- Solves
- Floorplanning
- 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
- Model
- Word RAM
- Properties
- deterministicexactiterative
- Evidence
- Full proofCode in 1 languages
- 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 time for blocks and a tree of depth . 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 on blocks (see normalized Polish expression; here need not be normalized), and for each block a list of allowed shapes 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 node adds the widths of its parts and takes the larger height, and an node takes the larger width and adds the heights. The output is a realization with the least area , its width and height, and the front of all pairs.
In Stockmeyer's paper each block is a fixed rectangle that may turn by 90 degrees, so . The same algorithm works for any finite lists, which is the form used with shape functions.
The algorithm
A shape dominates if , 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.
STOCKMEYER(E, S) ▷ E: a Polish expression; S_i: the allowed shapes of block i- 1
for each token t of E, from left to right, with a stack do - 2
if t is a block i then push PARETO(S_i), the front of S_i - 3
else pop B, then pop A; push MERGE-V(A, B) if t = V, else MERGE-H(A, B) - 4
R ← the list that is left on the stack - 5
k ← the entry of R with the least W · H - 6
follow the back pointers down from entry k, and give each block its shape - 7
return W_k · H_k and the shapes MERGE-V(A, B) ▷ A, B: fronts, widths increasing, heights decreasing- 8
i ← 1, j ← 1, R ← an empty list - 9
loop - 10
append (w_A[i] + w_B[j], max(h_A[i], h_B[j])) with the back pointer (i, j) to R - 11
if h_A[i] > h_B[j] then (if i = |A| then return R); i ← i + 1 - 12
else if h_B[j] > h_A[i] then (if j = |B| then return R); j ← j + 1 - 13
else (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 is the narrowest combination with its height.
Example
The tree is : blocks 1 and 2 side by side at the bottom, blocks 3 and 4 side by side on top. The blocks are , , and (width by height), and each one may turn.
| node | front (width by height) | how it is made |
|---|---|---|
| 1 | , | the two orientations |
| 2 | , | the two orientations |
| , , | , then move 1, then move 2 | |
| 3 | , | the two orientations |
| 4 | a square has one shape | |
| , | , then move 3; then the heights are equal and 4 is at its end | |
| root, | , , | see below |
MERGE-H at the root starts with the widest entries and , which give . The first part is wider, so it moves to , which gives . Now both widths are 5, so both move, to and , which give . 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 lead to and , and from there to block 1 turned to , block 2 as , block 3 as and block 4. The block area is 21, so 4 units are empty. Without any turn the floorplan is .
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 , every earlier entry of each list is taller than . Then the current pair is the narrowest combination of height at most , 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 of positive integers. The shape dominates if and and the two are different. For a set of shapes, the front of is the set of shapes of that no shape of dominates. We write a front as a list by increasing width. Then the heights strictly decrease, because two shapes of a front with and would be equal or one would dominate the other.
For a node of the slicing tree, a realization of gives each block below one of its allowed shapes. Its width and height are computed as in EVALUATE on the page of the normalized Polish expression. Let be the set of pairs of all realizations of , and let be its front.
Lemma 1 (monotonicity). At a node with children and , the pair of the node is , and at an node it is . Both maps do not decrease when any argument increases. So if a realization of 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.
Lemma 2. is the front of the set of pairs obtained by combining one pair of with one pair of .
Proof. Let be a pair of , from realizations of and with pairs and . If , some dominates (the set is finite), and by Lemma 1 the combination of and is at most in both coordinates. It is in and is in the front, so it is equal to . Do the same for . So every pair of is a combination of front pairs. All combinations of front pairs are in , so the front of the combinations is .
Lemma 3 (MERGE-V). Let and be fronts, by increasing width. MERGE-V returns the front of , by increasing width, with . Each entry has a back pointer to a pair that gives it.
Proof. Let for the current . We claim this invariant at line L10: every has , and every has . At the start there are no such indices. If line L11 moves to , then and . The new maximum is , because the heights of decrease. Every has , and every had . Line L12 is the same with the roles of and exchanged. In line L13, , both indices move, and for the same reason.
So at line L10, is the least index with and is the least index with , and the widths increase with the index. A combination with height at most needs and , so and , and its width is at least . So the entry of line L10 is the narrowest combination of height at most , and its height is exactly . Hence no combination dominates it, and it is on the front.
The values of strictly decrease from step to step, as shown, and the widths strictly increase, because at least one index moves. So lists distinct front pairs by increasing width. Write the entries as . It remains to show that every front pair is one of them. The first entry is the narrowest of all combinations, so , or the first entry would dominate . When the loop stops after entry , the index of a list that gives is at the end of that list, so every combination has height at least , and . Now take an entry and a combination of height . Each index that moved after entry pointed to a part of height exactly , and the part or of the same list has height less than , so it lies after the moved index. So and , and the width of the combination is at least . If , the entry dominates the combination. So no front pair has a height strictly between two consecutive entries. A front pair of height is the narrowest combination of height at most , so it is entry . Hence every front pair is listed.
Each step before the last moves at least one index, and the indices can move at most and times. So there are at most steps and entries.
Lemma 4 (MERGE-H). MERGE-H returns the front of with at most 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 combinations by Lemma 3.
Theorem 1 (correctness). STOCKMEYER returns the least area 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 for each node . So for the root . The area 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 , 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 .
Theorem 2 (list lengths). Let be the number of non-dominated allowed shapes of block . For each node with leaves, . If every block has at most two shapes, a rectangle and its rotation, then .
Proof. By induction with Lemmas 3 and 4: , and . With the bound is .
Theorem 3 (time). Let and let be the depth of the tree. STOCKMEYER takes time. For blocks with two orientations this is , which is in the worst case and for a balanced tree.
Proof. Line L2 sorts each list. A merge at node takes time, which is where is the number of shapes of the blocks below , by Theorem 2. The sum of over the internal nodes counts each block with weight one time for each proper ancestor, so it is at most . Line L6 visits each node one time. With , . The depth is at most , and it is for a balanced tree.
Complexity
Each step of a merge, except the last one, moves at least one pointer. So a merge of fronts of lengths and takes time and returns at most entries. By induction, a node with blocks below it has at most entries when each block has two orientations, and at most entries when the blocks below it have non-dominated shapes in total.
- Time. The merge at a node costs , and the sum of over the internal nodes counts each block one time for each ancestor. So the time is with two shapes for each block, and for lists with shapes in total, plus the sorting of the input lists.
- Worst and best. The depth is at most , so the worst case is , for a tree that is a long chain. A balanced tree has depth , which gives . If all fronts stay short, for example with square blocks, the time is .
- Space. The fronts of all nodes are kept for the back pointers, which is 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 at a time on the stack.
Shi gave in 1995 an algorithm that takes time on every tree, where is the total number of shapes at the leaves, and a lower bound of 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 and variable aspect ratio has the shape curve . 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 . The time is 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 is and the least area of is , but together they give , 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 blocks has depth . 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 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.
# 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 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 time in 1995.
References
- 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H2 full proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag RH6JHQ Edit this page History Report an error Markdown