Algorithmcore
Tetris legalization
Also called Hill legalization.
Sorts cells by x and puts each in the nearest free position of any row, greedily like Tetris, fast but with large moves in dense parts.
- Solves
- Placement legalization
- Time
- O(n log n + n K) worst · average · best
- Space
- O(n + K) extra
- Where
- K = the number of rows; n = the number of cells
- Model
- Word RAM
- Properties
- deterministicnot exactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Dwight Hill, 2002
Tetris legalization takes a global placement with overlap and moves every standard cell onto a site of a row so that no two cells overlap. It belongs to chip design (EDA): it is the simplest legalizer for the placement legalization problem, and many placers use it or a variant after global placement. It sorts the cells by their position and puts each one, for good, at the cheapest place to the right of the cells already in a row. Each row keeps only a frontier, the right end of its last cell. The method is a greedy algorithm: it runs in time for cells and rows and is always legal when it succeeds, but it can move cells far in dense areas, and it can fail while the rows still have room.
In plain words
Think of the game Tetris turned on its side. Take the parts in order from left to right. For each part, look at every row of the chip. In each row the part can go at its own spot, or just after the last part already there if that one is in the way. Choose the row where the part moves least and put it there. It never moves again.
This is fast and simple. But a part never goes back into a gap to the left of the last part in a row, and parts already placed never make room. So a crowded area pushes parts far to the right.
The problem
The rows lie at the heights , and each row has the sites of width 1. Cell has an integer width in sites and a global position of its lower left corner. A legal placement gives each cell a row and an integer with and , with no overlap in a row. The goal is a small total movement, here the Manhattan movement . (The squared movement is also common; only the cost of line L7 changes.)
The algorithm
TETRIS(cells, K rows of S sites)- 1
sort the cells by x'_i - 2
for each cell i in this order - 3
for each row r - 4
want ← the site nearest to x'_i, clamped to [0, S − W_i] - 5
pos(r) ← max(frontier(r), want) - 6
if pos(r) + W_i > S then skip r - 7
cost(r) ← |pos(r) − x'_i| + |y_r − y'_i| - 8
if no row is left, stop with failure - 9
put i at (pos(r), y_r) for the row r of least cost (the first one on a tie) - 10
frontier(r) ← pos(r) + W_i
All frontiers start at 0. Line L4 rounds to a site (a tie goes to the left) and keeps the cell inside the row. Line L5 is the best site at or after the frontier: the movement over the integers in an interval is least at the clamp of the nearest site. Line L6 skips a row whose frontier leaves no room. Lines L9 and L10 place the cell and move the frontier past it.
Example
Too much push. One row of 10 sites and three cells of width 1, all with . Tetris puts the first at 5, the second at 6 and the third at 7, a total movement of . The best legal placement is , with the movement . Tetris cannot use site 4, because the first cell was placed before it saw the others.
Failure with room. One row of 4 sites, a cell of width 1 with , and a cell of width 2 with . Tetris puts at 2, so the frontier is 3. Cell needs the sites 3 and 4, and site 4 does not exist, so Tetris fails, though the sites 0 and 1 are free and the placement at 0, at 2 is legal.
Two rows. Two rows of 6 sites at and , and six cells:
| cell | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| width | 1 | 2 | 1 | 2 | 2 | 1 |
The candidates of each step, from the implementation with Fractions (frontiers before the step):
| cell | frontiers | row 0: pos, cost | row 1: pos, cost | chosen |
|---|---|---|---|---|
| 0 | 0, 0 | 1, 0 | 1, 1 | row 0 at 1 |
| 1 | 2, 0 | 2, | 1, | row 1 at 1 |
| 2 | 2, 3 | 2, 1 | 3, 1 | row 0 at 2 (tie) |
| 3 | 3, 3 | 3, | 3, | row 1 at 3 |
| 4 | 3, 5 | 3, | no room | row 0 at 3 |
| 5 | 5, 5 | 5, | 5, | row 0 at 5 |
The result is and , with the Manhattan movement 6 and the squared movement 9. Cell 5 wants , but the frontier of row 0 is already at 5. Abacus on the same input moves cells 0 and 4 to the left and gets the Manhattan movement 5 and the squared movement 6.
Correctness
The proof shows the following.
- Frontier invariant. At each step, every cell placed in row lies in . The new cell starts at or after the frontier, so it overlaps no cell of its row, and it ends at most at by line L6. So the output is legal.
- Best in the row. Line L5 gives the least over the integer positions that start at or after the frontier and end at most at . So each step chooses the cheapest place that the frontiers allow, over all rows.
- When it fails. Tetris fails exactly when, for the current cell , every row has . The frontier counts the gaps to its left as used, so this can happen while a row has enough free width in total, as the example shows.
Proof: Tetris legalization returns a legal placement, takes the cheapest place that the frontiers allow, and runs in O(n log n + nK) timefull
Write for the frontier of row , for the number of cells and for the number of rows. All frontiers start at 0. Let , the integer nearest to with a tie to the left, and let for .
Lemma 1 (frontier invariant). Before and after each step, every cell placed in row occupies an interval with and , and the intervals of row are pairwise disjoint.
Proof. At the start no cell is placed and . Suppose it holds before cell goes into row at . Then , and by line L6. Every earlier cell of row ends at most at , so the new interval meets none of them. Line L10 sets , and every cell of row , the new one included, ends at most at the new . Other rows do not change.
Theorem 1 (legal output). If Tetris does not stop with failure, it returns a legal placement: each cell is on an integer site of a row, inside the row, and no two cells of a row overlap.
Proof. Line L4 gives an integer, and line L5 takes the maximum of two integers, so every is an integer. The rest is Lemma 1 after the last step.
Lemma 2 (the best place in a row). Let be integers. Over the integers , is least at . If , line L5 gives for and ; if , no position in row starts at or after and ends at most at , and line L6 skips the row.
Proof. The function is convex in and, over all integers, least at . A convex function on the integers decreases up to its minimum and increases after it. If , the least value on is at ; if , at ; otherwise at . This is . Line L4 computes with , and line L5 takes . If , then (because ), and the result is . If , the result is . If , then and the result is . In each case it is . If , every has , and fails line L6.
Theorem 2 (greedy choice). At each step Tetris puts cell at the place of least Manhattan movement among all positions with an integer, and , over all rows ; on a tie it takes the row of smallest index. It stops with failure exactly when no such position exists.
Proof. For a fixed row the term is a constant, so by Lemma 2 the cheapest allowed position in row is , and rows with none are skipped. Line L9 takes the least , the first on a tie. If every row is skipped, no allowed position exists, and line L8 stops; otherwise some row is left and the step succeeds.
The theorem is about the positions that the frontiers allow. A free gap to the left of is not allowed, which is why Tetris can fail while a legal placement exists.
Theorem 3 (running time). Tetris runs in time and extra space.
Proof. Line L1 is one sort of keys, . The loop of line L2 runs times. In each run, lines L3 to L7 do arithmetic per row, in total, and lines L8 to L10 cost (the least cost is kept during the loop over rows). The frontiers take space and the positions . The loop ends after the cells, or earlier at line L8.
Complexity
- Time. The sort costs . Each cell looks at each row in time, so the loop costs . In total . A bound on the number of rows tried, for example only rows within a distance of , gives for rows per cell.
- Space. The frontiers and the output: .
- The implementation uses exact Fractions for the costs, so a tie between rows is decided exactly.
Properties
What is proved. The output is legal when Tetris succeeds, each step takes the cheapest place that the current frontiers allow, and the running time is as above. Nothing bounds the movement against the least movement, and Tetris can fail when a legal placement exists. Finding the least movement is NP-hard (see placement legalization).
What is measured. Spindler, Schlichtmann and Johannes used Tetris as the baseline for Abacus and report that Tetris moves the cells clearly more on their benchmark circuits. On 200 random toy instances made with a fixed seed (4 rows of 12 sites, 18 cells of width 1 to 3, a dense case), the implementation here failed on 84 instances where Abacus did not fail. On the 116 instances where both succeeded, the mean Manhattan movement was 20.8 for Tetris and 18.9 for Abacus. These are toy numbers, not benchmark results.
- Order kept in a row. Cells of a row are in the order of their , because they are placed in that order and each goes after the frontier.
- Placed cells never move. This is what makes it fast and what makes it push.
- Stable on legal input. If the global placement is already legal and on sites, each cell finds its own position with cost 0, and nothing moves.
Variants and improvements
- Free intervals instead of a frontier. Keep the list of free intervals of each row, and let a cell go into any free gap. This removes the failure of the example and reduces the movement, at the cost of a search in the list.
- Other sort keys. Sort by the center instead of the left edge, or process from both sides toward the middle with a frontier at each end of a row.
- Squared or weighted cost. Use , or weight the movement of cells on critical nets more.
- Moving placed cells. Abacus legalization lets the cells of a row move again by merging clusters, which solves the row exactly for a fixed order.
- Window limits. Try only rows near , which is what makes the method fast for many rows.
When to use it
Use Tetris when the global placement is already spread well and speed matters most, for example when a placer legalizes many times to measure the wirelength of a legal placement. For the final legalization of a dense design, use Abacus or a flow-based legalizer, and then detailed placement. Min-cut placement does not need a legalizer of this kind, because it places cells in rows from the start.
Pitfalls
- Ignoring the frontier gaps. A row with a small total width can still be full for Tetris, because a gap to the left of the frontier is lost. Check failures against the free intervals before calling a design too dense.
- Rounding at the row ends. Clamp the nearest site to before the frontier, or a cell near the right end gets a position that runs past the row.
- Ties. With floating point costs, a tie between rows is decided by rounding errors. Use exact costs or a fixed tie rule.
- Sort order of equal . Cells with the same need a fixed second key, or the result depends on the sort.
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.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/tetris-legalization/. The authors are listed in prov/M7HMAC.jsonl.
"""Tetris legalization, the greedy method of Hill's patent in its common textbook form.
Rows r = 0 .. K-1 lie at y = r * row_height and hold the sites x = 0 .. S-1 of width 1.
Cell i has an integer width w[i] and a global position (xg[i], yg[i]) of its lower left corner.
Each row keeps a frontier: the right end of its last placed cell. A placed cell never moves.
The cost of a candidate is the Manhattan movement |x - xg| + |y - yg|, computed exactly.
"""
from fractions import Fraction
from math import floor
def nearest_site(v) -> int:
"""The site nearest to v; a tie goes to the left."""
return -floor(-Fraction(v) + Fraction(1, 2))
def tetris(xg, yg, w, num_rows: int, sites: int, row_height=1):
"""Return (x, y) with integer site positions and row heights, or raise ValueError
when some cell fits after the frontier of no row."""
n = len(xg)
frontier = [0] * num_rows
x = [0] * n
y = [0] * n
order = sorted(range(n), key=lambda i: (Fraction(xg[i]), i)) # @line L1
for i in order: # @line L2
best = None
for r in range(num_rows): # @line L3
want = min(max(nearest_site(xg[i]), 0), sites - w[i]) # @line L4
pos = max(frontier[r], want) # @line L5
if pos + w[i] > sites: # @line L6
continue
cost = abs(pos - Fraction(xg[i])) + abs(Fraction(r * row_height) - Fraction(yg[i])) # @line L7
if best is None or cost < best[0]:
best = (cost, r, pos)
if best is None:
raise ValueError(f"cell {i} fits in no row") # @line L8
_, r, pos = best
x[i], y[i] = pos, r * row_height # @line L9
frontier[r] = pos + w[i] # @line L10
return x, y
def displacement(x, y, xg, yg) -> Fraction:
"""Total Manhattan movement."""
return sum(abs(Fraction(a) - Fraction(b)) + abs(Fraction(c) - Fraction(d)) for a, b, c, d in zip(x, xg, y, yg))
test_tetris_legalization.py 95 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/tetris-legalization/. The authors are listed in prov/M7HMAC.jsonl.
import random
from fractions import Fraction
from itertools import permutations, product
import pytest
from tetris_legalization import displacement, tetris
def check_legal(x, y, w, K, S):
n = len(x)
for i in range(n):
assert isinstance(x[i], int) and 0 <= x[i] and x[i] + w[i] <= S and y[i] in range(K)
for i in range(n):
for j in range(i + 1, n):
if y[i] == y[j]:
assert x[i] + w[i] <= x[j] or x[j] + w[j] <= x[i]
def best_one_row(xg, w, S):
"""Brute force: every order of the cells, and for each order every integer placement in that order."""
n = len(xg)
best = None
for order in permutations(range(n)):
for xs in product(range(S), repeat=n):
if all(xs[k] + w[order[k]] <= xs[k + 1] for k in range(n - 1)) and xs[-1] + w[order[-1]] <= S:
c = sum(abs(xs[k] - Fraction(xg[order[k]])) for k in range(n))
if best is None or c < best:
best = c
return best
def greedy_reference(xg, yg, w, K, S):
"""The same greedy rule, with each row scanned over every site at or after its frontier."""
n = len(xg)
frontier = [0] * K
x, y = [0] * n, [0] * n
for i in sorted(range(n), key=lambda i: (Fraction(xg[i]), i)):
best = None
for r in range(K):
for pos in range(frontier[r], S - w[i] + 1):
c = abs(pos - Fraction(xg[i])) + abs(r - Fraction(yg[i]))
if best is None or c < best[0]:
best = (c, r, pos)
if best is None:
raise ValueError
_, r, pos = best
x[i], y[i] = pos, r
frontier[r] = pos + w[i]
return x, y
def test_legal_and_same_as_scanning_reference():
rng = random.Random(2002)
for _ in range(300):
K, S = rng.randint(1, 4), rng.randint(3, 12)
n = rng.randint(1, 10)
w = [rng.randint(1, 3) for _ in range(n)]
xg = [Fraction(rng.randint(-4, 4 * S), 4) for _ in range(n)]
yg = [Fraction(rng.randint(-2, 4 * K), 4) for _ in range(n)]
try:
ref = greedy_reference(xg, yg, w, K, S)
except ValueError:
with pytest.raises(ValueError):
tetris(xg, yg, w, K, S)
continue
got = tetris(xg, yg, w, K, S)
check_legal(*got, w, K, S)
assert displacement(*got, xg, yg) == displacement(*ref, xg, yg)
def test_never_better_than_the_best_one_row_placement():
rng = random.Random(5)
for _ in range(40):
n = 4
w = [rng.randint(1, 2) for _ in range(n)]
S = sum(w) + rng.randint(0, 2)
xg = [Fraction(rng.randint(0, 2 * S), 2) for _ in range(n)]
try:
x, y = tetris(xg, [0] * n, w, 1, S)
except ValueError:
continue
assert displacement(x, y, xg, [0] * n) >= best_one_row(xg, w, S)
def test_page_examples():
# three unit cells wanting x = 5: Tetris gives 5, 6, 7 (movement 3); the best is 4, 5, 6 (movement 2)
x, _ = tetris([5, 5, 5], [0, 0, 0], [1, 1, 1], 1, 10)
assert x == [5, 6, 7] and best_one_row([5, 5, 5], [1, 1, 1], 8) == 2
# the frontier hides a free gap: a fits at 2, then b of width 2 finds no room, though [0, 2) is free
with pytest.raises(ValueError):
tetris([2, Fraction(5, 2)], [0, 0], [1, 2], 1, 4)
History
The greedy rule is old: it is the same idea as list scheduling, which puts each job at the earliest free time on some machine. In placement, the name Tetris comes from Hill's US patent 6,370,673 of 2002, and the method became the standard baseline for legalization. Spindler, Schlichtmann and Johannes compared Abacus with it in 2008. Many later legalizers start from its greedy order and add ways to move cells that were placed before.
References
- Dwight Hill, Method and system for high speed detailed placement of cells within an integrated circuit design, US patent 6,370,673, 2002, the patent that the name Tetris legalization refers to (general locator)
- Peter Spindler, Ulf Schlichtmann and Frank M. Johannes, Abacus, fast legalization of standard cell circuits with minimal movement, Proceedings of the International Symposium on Physical Design (ISPD), 47 to 53, 2008, the description of Tetris as the baseline, and the comparison of its movement with Abacus
- 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 (legalization; 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 | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag M7HMAC Edit this page History Report an error Markdown