Algorithm Search⌘K

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.

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
Properties
deterministicnot exactiterative
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 xx 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 O(nlog⁡n+nK)O(n \log n + n K) time for nn cells and KK 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 r=0,…,K−1r = 0, \ldots, K - 1 lie at the heights yr=rhy_r = r h, and each row has the sites 0,1,…,S−10, 1, \ldots, S - 1 of width 1. Cell ii has an integer width Wi≥1W_i \ge 1 in sites and a global position (xi′,yi′)(x'_i, y'_i) of its lower left corner. A legal placement gives each cell a row yiy_i and an integer xix_i with 0≤xi0 \le x_i and xi+Wi≤Sx_i + W_i \le S, with no overlap in a row. The goal is a small total movement, here the Manhattan movement ∑i∣xi−xi′∣+∣yi−yi′∣\sum_i |x_i - x'_i| + |y_i - y'_i|. (The squared movement is also common; only the cost of line L7 changes.)

The algorithm

  1. TETRIS(cells, K rows of S sites)
  2. 1sort the cells by x'_i
  3. 2for each cell i in this order
  4. 3for each row r
  5. 4want ← the site nearest to x'_i, clamped to [0, S − W_i]
  6. 5pos(r) ← max(frontier(r), want)
  7. 6if pos(r) + W_i > S then skip r
  8. 7cost(r) ← |pos(r) − x'_i| + |y_r − y'_i|
  9. 8if no row is left, stop with failure
  10. 9put i at (pos(r), y_r) for the row r of least cost (the first one on a tie)
  11. 10frontier(r) ← pos(r) + W_i

All frontiers start at 0. Line L4 rounds xi′x'_i 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 ∣p−xi′∣|p - x'_i| over the integers pp 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 x′=5x' = 5. Tetris puts the first at 5, the second at 6 and the third at 7, a total movement of 0+1+2=30 + 1 + 2 = 3. The best legal placement is 4,5,64, 5, 6, with the movement 1+0+1=21 + 0 + 1 = 2. 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 aa of width 1 with x′=2x' = 2, and a cell bb of width 2 with x′=52x' = \frac52. Tetris puts aa at 2, so the frontier is 3. Cell bb 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 bb at 0, aa at 2 is legal.

Two rows. Two rows of 6 sites at y=0y = 0 and y=1y = 1, and six cells:

cell 0 1 2 3 4 5
width 1 2 1 2 2 1
(xi′,yi′)(x'_i, y'_i) (1,0)(1, 0) (32,1)(\frac32, 1) (2,1)(2, 1) (52,1)(\frac52, 1) (52,1)(\frac52, 1) (52,0)(\frac52, 0)

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, 32\frac32 1, 12\frac12 row 1 at 1
2 2, 3 2, 1 3, 1 row 0 at 2 (tie)
3 3, 3 3, 32\frac32 3, 12\frac12 row 1 at 3
4 3, 5 3, 32\frac32 no room row 0 at 3
5 5, 5 5, 52\frac52 5, 72\frac72 row 0 at 5

The result is x=(1,1,2,3,3,5)x = (1, 1, 2, 3, 3, 5) and y=(0,1,0,1,0,0)y = (0, 1, 0, 1, 0, 0), with the Manhattan movement 6 and the squared movement 9. Cell 5 wants x=52x = \frac52, 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 rr lies in [0,frontier(r))[0, \text{frontier}(r)). The new cell starts at or after the frontier, so it overlaps no cell of its row, and it ends at most at SS by line L6. So the output is legal.
  • Best in the row. Line L5 gives the least ∣p−xi′∣|p - x'_i| over the integer positions pp that start at or after the frontier and end at most at SS. 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 ii, every row has frontier(r)+Wi>S\text{frontier}(r) + W_i > S. 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 FrF_r for the frontier of row rr, nn for the number of cells and KK for the number of rows. All frontiers start at 0. Let N(v)=−⌊−v+12⌋N(v) = -\lfloor -v + \frac12 \rfloor, the integer nearest to vv with a tie to the left, and let cl(p,L,U)=min⁡(max⁡(p,L),U)\mathrm{cl}(p, L, U) = \min(\max(p, L), U) for L≤UL \le U.

Lemma 1 (frontier invariant). Before and after each step, every cell placed in row rr occupies an interval [xj,xj+Wj)[x_j, x_j + W_j) with 0≤xj0 \le x_j and xj+Wj≤Fr≤Sx_j + W_j \le F_r \le S, and the intervals of row rr are pairwise disjoint.

Proof. At the start no cell is placed and Fr=0F_r = 0. Suppose it holds before cell ii goes into row rr at p=max⁡(Fr,want)p = \max(F_r, \text{want}). Then p≥Fr≥0p \ge F_r \ge 0, and p+Wi≤Sp + W_i \le S by line L6. Every earlier cell of row rr ends at most at Fr≤pF_r \le p, so the new interval [p,p+Wi)[p, p + W_i) meets none of them. Line L10 sets Fr=p+Wi≤SF_r = p + W_i \le S, and every cell of row rr, the new one included, ends at most at the new FrF_r. Other rows do not change. □\square

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 xix_i is an integer. The rest is Lemma 1 after the last step. ■\blacksquare

Lemma 2 (the best place in a row). Let 0≤L≤U0 \le L \le U be integers. Over the integers p∈[L,U]p \in [L, U], ∣p−v∣|p - v| is least at p∗=cl(N(v),L,U)p^\ast = \mathrm{cl}(N(v), L, U). If Fr≤S−WiF_r \le S - W_i, line L5 gives p∗p^\ast for L=FrL = F_r and U=S−WiU = S - W_i; if Fr>S−WiF_r > S - W_i, no position in row rr starts at or after FrF_r and ends at most at SS, and line L6 skips the row.

Proof. The function g(p)=∣p−v∣g(p) = |p - v| is convex in pp and, over all integers, least at N(v)N(v). A convex function on the integers decreases up to its minimum and increases after it. If N(v)<LN(v) < L, the least value on [L,U][L, U] is at LL; if N(v)>UN(v) > U, at UU; otherwise at N(v)N(v). This is cl(N(v),L,U)\mathrm{cl}(N(v), L, U). Line L4 computes want=cl(N(v),0,U)\text{want} = \mathrm{cl}(N(v), 0, U) with v=xi′v = x'_i, and line L5 takes max⁡(L,want)\max(L, \text{want}). If N(v)≤LN(v) \le L, then want≤L\text{want} \le L (because L≤UL \le U), and the result is LL. If L<N(v)≤UL < N(v) \le U, the result is N(v)N(v). If N(v)>UN(v) > U, then want=U≥L\text{want} = U \ge L and the result is UU. In each case it is p∗p^\ast. If Fr>S−WiF_r > S - W_i, every p≥Frp \ge F_r has p+Wi>Sp + W_i > S, and p=max⁡(Fr,⋅)≥Frp = \max(F_r, \cdot) \ge F_r fails line L6. □\square

Theorem 2 (greedy choice). At each step Tetris puts cell ii at the place of least Manhattan movement among all positions (p,yr)(p, y_r) with pp an integer, p≥Frp \ge F_r and p+Wi≤Sp + W_i \le S, over all rows rr; 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 ∣yr−yi′∣|y_r - y'_i| is a constant, so by Lemma 2 the cheapest allowed position in row rr is pos(r)\text{pos}(r), and rows with none are skipped. Line L9 takes the least cost(r)\text{cost}(r), 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. ■\blacksquare

The theorem is about the positions that the frontiers allow. A free gap to the left of FrF_r is not allowed, which is why Tetris can fail while a legal placement exists.

Theorem 3 (running time). Tetris runs in O(nlog⁡n+nK)O(n \log n + n K) time and O(n+K)O(n + K) extra space.

Proof. Line L1 is one sort of nn keys, O(nlog⁡n)O(n \log n). The loop of line L2 runs nn times. In each run, lines L3 to L7 do O(1)O(1) arithmetic per row, O(K)O(K) in total, and lines L8 to L10 cost O(1)O(1) (the least cost is kept during the loop over rows). The frontiers take O(K)O(K) space and the positions O(n)O(n). The loop ends after the nn cells, or earlier at line L8. ■\blacksquare

Complexity

  • Time. The sort costs O(nlog⁡n)O(n \log n). Each cell looks at each row in O(1)O(1) time, so the loop costs O(nK)O(n K). In total O(nlog⁡n+nK)O(n \log n + n K). A bound on the number of rows tried, for example only rows within a distance of yi′y'_i, gives O(nlog⁡n+nt)O(n \log n + n t) for tt rows per cell.
  • Space. The frontiers and the output: O(n+K)O(n + K).
  • 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 x′x', 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 xi′+Wi/2x'_i + W_i / 2 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 (x−xi′)2+(y−yi′)2(x - x'_i)^2 + (y - y'_i)^2, 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 yi′y'_i, 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 [0,S−Wi][0, S - W_i] 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 x′x'. Cells with the same x′x' 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.

tetris_legalization.pyI0RawGitHub
# 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

  1. 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)
  2. 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
  3. 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.

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