Algorithmadvanced
Abacus legalization
Also called Spindler Abacus.
Spindler, Schlichtmann and Johannes's legalizer that tries each cell in nearby rows and places each row by merging clusters of cells, which minimizes squared moves for a fixed order.
- Solves
- Placement legalization
- Time
- O(n log n + K n k) worstO(n log n + t n k) averageO(n log n + n) best
- Space
- O(n + K) extra
- Where
- K = the number of rows; k = the largest number of cells that one row gets; n = the number of cells; t = the number of rows that a cell tries before line L4 stops the loop
- Model
- Real RAM
- Properties
- deterministicnot exactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Peter Spindler, Ulf Schlichtmann, Frank M. Johannes, 2008
Abacus legalization takes a global placement with overlap and moves every standard cell into a row and onto a site so that no two cells overlap, with a small total squared movement. It belongs to chip design (EDA): it is the step after global placement and before detailed placement, and it solves the placement legalization problem by a heuristic. Like Tetris legalization, it takes the cells in order of their position and puts each in a nearby row. Unlike Tetris, it lets the cells that are already in a row move again: for a fixed order of the cells in a row, its procedure PlaceRow finds the exact minimum of the squared movement by merging clusters of abutting cells. This step is the pool adjacent violators algorithm of isotonic regression with two bounds. The choice of the row for each cell is greedy, so the result is legal but not optimal.
In plain words
Think of beads on the wires of an abacus. Each wire is a row of the chip. Each bead wants to be at its own spot, but beads cannot pass or sit on each other.
Take the beads from left to right. Try a new bead on the wires near its spot. On each wire, slide it in at the right end. If it hits the beads before it, they form a group that moves as one piece, to the place where the group is happiest on average. That place can make the group hit the group before it, and then the two groups join. Keep the wire where the new bead ends nearest to its spot, and go on.
The problem
The rows lie at the heights , and each row has the sites of width 1. Cell has an integer width in sites, a weight and a global position of its lower left corner. A legal placement gives each cell a row and an integer with and , and no two cells of the same row overlap. The goal is a legal placement with a small weighted squared movement
Inside PlaceRow, the row is the interval , the cells of the row are in a fixed left to right order with , and PlaceRow solves the quadratic program
with real . A cluster is a run of cells of the row that abut. It has a total weight , a total width , a position of its left edge, and the number , where is the offset of cell from the left edge of the cluster. The best position of a cluster alone is then .
The algorithm
ABACUS(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 in order of |y_r − y'_i| - 4
if some row has a cost already and (y_r − y'_i)^2 ≥ the best cost, then stop the loop over rows - 5
if the cells of r together with i are wider than S, then skip r - 6
place the cells of r followed by i with PLACEROW, as a trial - 7
cost(r) ← (x_i − x'_i)^2 + (y_r − y'_i)^2, with x_i the trial position of i - 8
append i to the row of least cost; if no row had room, stop with failure - 9
for each row: PLACEROW on its cells, round each x_c to the nearest site, and put the cells of each cluster side by side PLACEROW(cells 1 .. k of the row, in order)- 10
for j ← 1 to k - 11
if there is no cluster, or the last cluster c has x_c + W_c ≤ x'_j, then start a new empty cluster c - 12
add j to c: q_c ← q_c + e_j (x'_j − W_c); e_c ← e_c + e_j; W_c ← W_c + W_j - 13
COLLAPSE(c) COLLAPSE(c)- 14
x_c ← q_c / e_c - 15
if x_c < a then x_c ← a; if x_c > b − W_c then x_c ← b − W_c - 16
if c has a cluster c' before it with x_{c'} + W_{c'} > x_c - 17
append c to c' as in L18, remove c, and COLLAPSE(c') - 18
q_{c'} ← q_{c'} + q_c − e_c W_{c'}; e_{c'} ← e_{c'} + e_c; W_{c'} ← W_{c'} + W_c
Lines L1 to L8 are the outer loop. Rows are tried in order of their vertical distance, and line L4 stops the loop when no farther row can be better, because the cost of a row is at least . The trial cost of line L7 counts only the movement of cell ; the other cells of the row may move in the trial too, and that is not counted. Line L9 runs PlaceRow once more on each row with its final cells. Lines L10 to L18 are PlaceRow. In line L12 the new cell sits at the offset (the width before the addition) from the left edge, so its term in is . In line L18 every cell of gets the extra offset , which subtracts from its part of . Line L16 is the merge test: the two clusters overlap.
Example
One row. A row of sites gets five cells, all of weight 1, in this order:
| cell | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| width | 2 | 1 | 2 | 1 | 2 |
| global | 1 | 2 | 7 | 7 |
The clusters of PlaceRow after each cell, from the implementation with Fractions:
| after cell | clusters (cells at ) | what happens |
|---|---|---|
| 0 | at 1 | a new cluster at |
| 1 | at | cell 1 wants 2, but cell 0 ends at 3; , |
| 2 | at | , |
| 3 | at , at 7 | the first cluster ends at , so a new cluster |
| 4 | at , at 6 | , , so , but the row ends at 9 and , so |
The cells are at with the squared movement , the least for this order. Line L9 rounds to 0 and keeps 6, so the legal positions are with the squared movement .
Two rows, against Tetris. Two rows of 6 sites at and , and six cells of weight 1:
| cell | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| width | 1 | 2 | 1 | 2 | 2 | 1 |
The trials of Abacus, from the implementation:
| cell | first row tried: trial , cost | second row tried | chosen |
|---|---|---|---|
| 0 | row 0: 1, cost 0 | row 1: stopped by L4 | 0 |
| 1 | row 1: , cost 0 | row 0: stopped by L4 | 1 |
| 2 | row 1: , cost | row 0: stopped by L4 | 1 |
| 3 | row 1: , cost | row 0: stopped by L4 | 1 |
| 4 | row 1: full (width 7 > 6) | row 0: , cost 1 | 0 |
| 5 | row 0: , cost | row 1: 5, cost | 0 |
At the end row 0 holds the cluster at and row 1 the cluster at . After rounding, and . The squared movement is 6 and the Manhattan movement is 5. Tetris on the same input gives and , with the squared movement 9 and the Manhattan movement 6: cell 5 must go to , because Tetris cannot push cells 0 and 4 to the left.
Correctness
The proof shows the following.
- The substitution. With and , the row problem becomes: minimize subject to . That is isotonic regression with a lower and an upper bound. A cluster is a block of equal , its position is the weighted mean of over the block, and the merge test of line L16 is the test of a violated order between two blocks.
- PlaceRow is exact. After each cell , the clusters are the unique minimum of the problem on the cells . The proof keeps an invariant on the prefix and suffix means of each cluster and checks the KKT conditions with explicit multipliers.
- Legal output. Rounding with keeps the clusters apart and inside the row, because it is nondecreasing and commutes with adding an integer. So line L9 gives a legal placement whenever no failure was reported.
- Failure. Abacus stops with failure only when cell is wider than the free width of every row. Inside a row it never fails, because it can move all the cells of the row.
- The stop of line L4 is safe. Each later row has a cost of at least its , so it cannot be strictly better.
Proof: PlaceRow finds the exact least squared movement of a row with a fixed order, and Abacus returns a legal placementfull
Fix one row and its cells in the given order, with integer widths , weights , targets , and . Write for the width of the cells before (so ), and
Then , because each . For a set of consecutive cells, write , (the weighted mean of on ) and . If is split into a prefix and a suffix , then .
Lemma 1 (the substitution). Let be the problem: minimize subject to . The map is a bijection from the positions of cells with , and , onto the feasible set of , and it keeps the objective .
Proof. is , and , so it is . is . is . Finally .
Lemma 2 (clusters in the new coordinates). Let be a cluster of the cells in PlaceRow. Then , , and with (the common value of on the cluster):
- line L14 sets ;
- line L15 clamps to ;
- the test of line L16 for the cluster just before is .
Proof. The offset of cell in the cluster is . Line L12 adds cell with the offset , and line L18 adds to each cell of the offset , the width before it. By induction on these two lines, . So . The clamp is , and is . If has the cells , then , which is more than exactly when .
The plain run. In the plain run, cell always starts a new cluster . The current (last) cluster gets the value if it is the first cluster of the row, and otherwise. While a cluster comes just before with , the two merge into the current cluster , which gets its value in the same way.
Lemma 3. PlaceRow (lines L10 to L18) makes the same clusters with the same values as the plain run.
Proof. By induction on the steps. All stored values are at least : the first cluster is clamped to from below, and every other cluster stays only if its value is at least that of the cluster before it. Two things differ. (i) Line L11 adds to the last cluster when (Lemma 2 with ). In the plain run, gets a value at most , so it merges with at once, and line L18 for the one-cell cluster with makes the same change as line L12. Both then collapse the merged cluster. (ii) A cluster that is not the first is clamped from below to by line L15, and not in the plain run. If , the clamp does nothing. If , PlaceRow gives and the plain run gives . Both are less than the value of the cluster before it, which is at least , so both runs merge, and the merged value is computed again from and .
Good blocks. Call a block balanced if every proper prefix has . Because for the complementary suffix , this is the same as: every proper suffix has . Call high at if every proper prefix has , and low at if every proper suffix has . A block of one cell is all of these. A balanced block is high at every and low at every .
Invariant (J) after cell . The clusters have values , with and , and each is in one of three states:
- free: and is balanced;
- low: , , and is low at ;
- high: , , and is high at .
Lemma 4 (optimality). If (J) holds after cell , the values of the clusters, copied to their cells, are the unique minimum of .
Proof. Let for . It is feasible by (J). If , the feasible set is the single point , and we are done. Let , so no cluster is both low and high. The objective is strictly convex because every , and the constraints are linear, so a feasible point that meets the KKT conditions is the unique minimum (see KKT conditions). With half the objective, multipliers for , for (), and for , the stationarity condition for is . So set
Stationarity holds by construction. It remains to show that every , with complementary slackness. Note , since a low block has .
At the end of a cluster. The sum over a cluster is . It is 0 for a free cluster, for the low cluster, and for the high cluster. So at the last cell of each with : the low part cancels , and the high cluster can only be the last. At , if is high, and then ; otherwise . Also only if is low, and then . So slackness holds for the bounds and for the constraints between clusters.
Inside a cluster with the cells , for , let and . Then , so slackness holds, and , where for and for . If is free, since it is balanced, so . If is high, and since . If is low, since .
Lemma 5 (one step keeps (J)). If (J) holds after cell (or ), it holds after cell in the plain run.
Proof. Write , and if . Note . During the collapse of step we keep this claim (K): the clusters before the current cluster are in the states of (J) for with the bound , a high cluster among them can only be the one just before , and then ; the current cluster is either balanced with , or high at with , or (only if it is the first cluster) low at with .
At the start is one cell, so it is in the state that its value gives, and (K) holds. Now let be the cluster before with , and let , a weighted mean of and . The prefixes of are the proper prefixes of , itself, and with a proper prefix of ; the suffixes are similar.
- free and balanced. Then , so . A proper prefix of has , and . For with a proper prefix of , the rest is a proper suffix of with , so . So is balanced, and its new value puts it in the free, high or low state.
- free and high. Then and , so and the new value is . A proper prefix of has mean at least ; has ; and has . So is high at .
- low (so it is the first cluster, ). Then is not first and , so and is balanced. Then , and the new value of the first cluster is . A proper suffix of has mean at most ; has ; and for a proper suffix of has . So is low at .
- high at . By (K), , with , and . Every proper prefix of has mean at least , and . Let be the new value. If , then , so every proper prefix of (those of , and ) has mean more than : is high at , which is the high state for and the balanced (free) state for . If , then is first and . Since , also , so the suffix is fine. For with a proper suffix of and the rest of , , because and . So is low at .
The case low and high would need , which is false, and the case high with is excluded by (K). So (K) holds after each merge. When the collapse stops, either is first or for the cluster before it. A high cluster at cannot be before , since would force a merge. So the earlier clusters are free or low, and their conditions do not depend on the bound. Their values are ordered, the last of them is at most , and the first is at least . If is not first, , so is free or high. This is (J) after cell .
Theorem 1 (PlaceRow is exact). For the cells of a row in a fixed order with , PlaceRow returns the unique positions with , and that minimize .
Proof. By Lemmas 3 and 5, (J) holds after cell . By Lemma 4 the values solve uniquely, and by Lemmas 1 and 2 the cluster positions give the cells the positions , the unique minimum of the row problem.
Theorem 2 (legal output). If Abacus does not stop with failure, line L9 returns a legal placement, and each cell is within of its position in the exact row minimum.
Proof. Line L5 keeps the total width of each row at most , so Theorem 1 applies with . The clusters of the minimum satisfy , and . Let . It is nondecreasing, and for every integer . So , , and . The cells of a cluster are put side by side from the integer , so they lie on sites, they do not overlap each other, and they do not overlap the next cluster. Each cell moves by .
Theorem 3 (failure and the stop of line L4). Abacus stops with failure only if cell is wider than the free width of every row. The stop of line L4 does not change the chosen row.
Proof. A row with room for cell passes line L5, gets a trial and a cost, so the failure of line L8 happens only when every row failed line L5. Rows are tried in order of , and the cost of row is at least . When this is at least the best cost so far, every later row also has a cost at least the best, and line L8 takes a strictly smaller cost or the earlier row on a tie, so no later row would be chosen.
Theorem 4 (running time). PlaceRow on cells makes at most clusters and at most merges, so it runs in time when a cluster stores its first and last cell. Abacus runs in time, where is the largest number of cells of a row.
Proof. Each step of the loop L10 starts at most one cluster, and each merge of line L17 removes one, so the number of merges is at most the number of clusters made, at most . Each call of COLLAPSE does work besides a merge, and there is one call per step plus one per merge. Lines L12 and L18 cost when a cluster keeps its totals and the range of its cells (the cells of a cluster are consecutive in the order of the row). Line L9 then writes positions. The sort of line L1 costs ; each of the cells makes at most trials, each one PlaceRow on at most cells, and line L9 costs over all rows.
Complexity
- PlaceRow. Each cell starts at most one cluster, and each merge removes one, so a run on cells does at most merges and work, if a cluster stores its first and last cell instead of a list (the cells of a cluster are consecutive in the row order).
- The outer loop. Each cell tries at most rows, and each trial is one PlaceRow on at most cells. With the sort, the worst case is , and .
- In practice. Line L4 stops after rows on average, and is small when the global placement is good. An implementation can keep the clusters of each row and only add cell to the end and collapse, because PlaceRow on the cells of followed by makes the same clusters for the cells of before it reaches . With this, a trial costs the number of merges it does. The best case, where every trial is a new cluster with no merge and only one row is tried, is .
- Space. The clusters and the rows: .
- The implementation uses exact Fractions and runs PlaceRow from the start for each trial, which is simple and in the worst case above.
Properties
What is proved. For a fixed assignment of cells to rows and a fixed order in each row, PlaceRow gives the exact minimum of the squared movement with real positions. Line L9 makes it legal, with each cell at most from that minimum. No bound relates the result of Abacus to the least movement over all row assignments and orders. The full legalization problem is NP-hard (see placement legalization).
What is measured. Spindler, Schlichtmann and Johannes report that Abacus moves the cells much less than Tetris (about 30 percent less total movement on their benchmark circuits), with a small extra run time. On 200 random toy instances made with a fixed seed (4 rows of 12 sites, 18 cells of width 1 to 3), the implementations here gave the following. Tetris failed on 84 instances, Abacus on none. On the 116 instances where both succeeded, the mean Manhattan movement was 20.8 for Tetris and 18.9 for Abacus, and the mean squared movement was 24.9 and 18.8. These are toy numbers, not benchmark results.
- Order kept. The cells of a row keep the order of their , because they are added in that order and clusters never pass each other.
- Stability. If the global placement is already legal and on sites, every cell gets a new cluster at its own position, and nothing moves.
- Rows do not interact. A trial in row changes only row .
Variants and improvements
- Linear movement. With the cost instead of the square, the one-row problem with a fixed order is the one-machine scheduling problem with symmetric earliness and tardiness penalties, which Garey, Tarjan and Wilfong solved in time in 1988. The clusters then sit at a weighted median instead of a weighted mean.
- Cost of the whole row. The trial cost of line L7 can count the change of movement of all cells of the row instead of cell alone. This is more exact and slower.
- Several sites per cell and mixed heights. Multi-row cells must take the same in several rows; extensions of Abacus handle them by placing them first or by coupling the rows.
- Fixed blocks. Macros and blockages split a row into segments, and PlaceRow runs on each segment with its own .
- Use in a placer. Placers such as SimPL and its successors call a legalizer of this kind at the end of global placement and before detailed placement.
When to use it
Use Abacus when the global placement is good and the legalizer must not destroy it: it moves cells less than Tetris and almost never fails while there is room. It needs a fixed order of the cells in each row, which it takes from the global ; a legalizer that can swap cells, or the assignment problem inside detailed placement, is needed to change that order. If speed is the only goal and the placement is sparse, Tetris legalization is simpler.
Pitfalls
- The order of the offset update. In line L12 the term uses before the new width is added, and in line L18 it uses before the merge. Updating the width first gives the wrong cluster position.
- Clamping before the merge test. The clamp of line L15 must come before the overlap test of line L16, or a cluster can leave the row.
- Rounding each cell alone. Rounding the cells of a cluster one by one can make neighbors overlap when the widths are not integers. Round the cluster, then place the cells side by side.
- Counting only the cell. The trial cost of line L7 ignores the movement of the other cells of the row. A row can look cheap for cell while it pushes many other cells. Count the whole row when quality matters more than time.
- Full rows. Line L5 checks only the total width. If the row has blockages, check the free width of each segment.
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/abacus-legalization/. The authors are listed in prov/4DKME3.jsonl.
"""Abacus legalization (Spindler, Schlichtmann and Johannes, ISPD 2008).
Rows r = 0 .. K-1 lie at y = r * row_height and span the sites x = 0 .. S-1 of width 1.
Cell i has an integer width w[i] (in sites), a weight e[i] > 0 and a global position
(xg[i], yg[i]) of its lower left corner. All arithmetic is exact (Fraction).
"""
from fractions import Fraction
from math import floor
from typing import Sequence
class Cluster:
__slots__ = ("cells", "e", "w", "q", "x")
def __init__(self):
self.cells: list[int] = []
self.e = Fraction(0) # total weight
self.w = 0 # total width
self.q = Fraction(0) # sum of e_i (xg_i - offset of i in the cluster)
self.x = Fraction(0) # position of the left edge
def add_cell(c: Cluster, i: int, xg, w, e) -> None:
c.cells.append(i)
c.q += e[i] * (Fraction(xg[i]) - c.w) # @line L12
c.e += e[i]
c.w += w[i]
def add_cluster(c: Cluster, d: Cluster) -> None:
"""Append cluster d to the right end of cluster c."""
c.cells += d.cells
c.q += d.q - d.e * c.w # @line L18
c.e += d.e
c.w += d.w
def collapse(clusters: list, xmin: int, xmax: int) -> None:
while True:
c = clusters[-1]
c.x = c.q / c.e # @line L14
if c.x < xmin: # @line L15
c.x = Fraction(xmin)
if c.x > xmax - c.w:
c.x = Fraction(xmax - c.w)
if len(clusters) >= 2 and clusters[-2].x + clusters[-2].w > c.x: # @line L16
prev = clusters[-2]
add_cluster(prev, c) # @line L17
clusters.pop()
continue
return
def place_row(order: Sequence[int], xg, w, e, xmin: int, xmax: int) -> list:
"""PlaceRow: the cells in the given left-to-right order, each pulled to xg with weight e.
Returns the clusters; together they minimize sum e_i (x_i - xg_i)^2 with no overlap,
keeping the order, inside [xmin, xmax]. The total width must fit."""
clusters: list = []
for i in order: # @line L10
last = clusters[-1] if clusters else None
if last is None or last.x + last.w <= xg[i]: # @line L11
last = Cluster()
clusters.append(last)
add_cell(last, i, xg, w, e)
collapse(clusters, xmin, xmax) # @line L13
return clusters
def cell_positions(clusters, w) -> dict:
"""Exact positions of the cells of the clusters: each cluster is a block of abutting cells."""
out = {}
for c in clusters:
off = 0
for i in c.cells:
out[i] = c.x + off
off += w[i]
return out
def abacus(xg, yg, w, num_rows: int, sites: int, row_height=1, e=None):
"""Return (x, y): integer site positions and row heights for all cells, or raise ValueError
if a cell fits in no row. Cells are taken in order of xg; each is tried in the rows in order
of vertical distance, and the trial cost is the squared movement of that cell."""
n = len(xg)
if e is None:
e = [Fraction(1)] * n
e = [Fraction(v) for v in e]
rows: list[list[int]] = [[] for _ in range(num_rows)]
used = [0] * num_rows
order = sorted(range(n), key=lambda i: (Fraction(xg[i]), i)) # @line L1
for i in order: # @line L2
best, best_row = None, None
by_dist = sorted(range(num_rows), key=lambda r: (abs(Fraction(r * row_height) - Fraction(yg[i])), r))
for r in by_dist: # @line L3
dy2 = (Fraction(r * row_height) - Fraction(yg[i])) ** 2
if best is not None and dy2 >= best: # @line L4
break
if used[r] + w[i] > sites: # @line L5
continue
trial = place_row(rows[r] + [i], xg, w, e, 0, sites) # @line L6
xi = cell_positions(trial[-1:], w)[i]
cost = (xi - Fraction(xg[i])) ** 2 + dy2 # @line L7
if best is None or cost < best:
best, best_row = cost, r
if best_row is None:
raise ValueError(f"cell {i} fits in no row")
rows[best_row].append(i) # @line L8
used[best_row] += w[i]
x = [0] * n
y = [0] * n
for r in range(num_rows): # @line L9
for c in place_row(rows[r], xg, w, e, 0, sites):
left = floor(c.x + Fraction(1, 2)) # round to a site; clusters stay apart
off = 0
for i in c.cells:
x[i] = left + off
y[i] = r * row_height
off += w[i]
return x, y
def movement(x, y, xg, yg, e=None) -> Fraction:
"""Total weighted squared movement."""
n = len(x)
e = [1] * n if e is None else e
return sum(Fraction(e[i]) * ((Fraction(x[i]) - Fraction(xg[i])) ** 2 + (Fraction(y[i]) - Fraction(yg[i])) ** 2) for i in range(n))
test_abacus_legalization.py 148 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/abacus-legalization/. The authors are listed in prov/4DKME3.jsonl.
import random
from fractions import Fraction
from itertools import product
import pytest
from abacus_legalization import abacus, cell_positions, movement, place_row
def qp_brute_force(order, xg, w, e, S):
"""Exact optimum of min sum e_i (x_i - xg_i)^2 with the order kept, no overlap, inside [0, S].
The optimum is the minimizer for its own set of tight constraints, so enumerate all of them:
every split of the order into blocks of abutting cells, and a pin of the first block to 0
and of the last block to S. Keep the best feasible candidate."""
n = len(order)
best = None
for cuts in product([0, 1], repeat=n - 1):
blocks, cur = [], [order[0]]
for k in range(1, n):
if cuts[k - 1]:
blocks.append(cur)
cur = [order[k]]
else:
cur.append(order[k])
blocks.append(cur)
for pin_left, pin_right in product([False, True], repeat=2):
xs = {}
ok = True
for b_idx, blk in enumerate(blocks):
width = sum(w[i] for i in blk)
off, offs = 0, []
for i in blk:
offs.append(off)
off += w[i]
left = pin_left and b_idx == 0
right = pin_right and b_idx == len(blocks) - 1
if left and right and width != S:
ok = False
break
if left:
X = Fraction(0)
elif right:
X = Fraction(S - width)
else:
X = sum(e[i] * (Fraction(xg[i]) - o) for i, o in zip(blk, offs)) / sum(e[i] for i in blk)
for i, o in zip(blk, offs):
xs[i] = X + o
if not ok:
continue
feasible = all(xs[order[k]] + w[order[k]] <= xs[order[k + 1]] for k in range(n - 1))
feasible = feasible and xs[order[0]] >= 0 and xs[order[-1]] + w[order[-1]] <= S
if feasible:
cost = sum(e[i] * (xs[i] - xg[i]) ** 2 for i in order)
if best is None or cost < best[0]:
best = (cost, xs)
return best
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
assert 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 test_place_row_is_the_exact_qp_optimum_for_5_cells():
rng = random.Random(2008)
for _ in range(400):
n = 5
w = [rng.randint(1, 3) for _ in range(n)]
S = sum(w) + rng.randint(0, 6)
xg = [Fraction(rng.randint(-4, 4 * S), 4) for _ in range(n)]
e = [Fraction(rng.randint(1, 4)) for _ in range(n)]
order = list(range(n)) if rng.random() < 0.5 else sorted(range(n), key=lambda i: xg[i])
clusters = place_row(order, xg, w, e, 0, S)
xs = cell_positions(clusters, w)
cost = sum(e[i] * (xs[i] - xg[i]) ** 2 for i in order)
bcost, bxs = qp_brute_force(order, xg, w, e, S)
assert cost == bcost
assert xs == bxs # unique, since the objective is strictly convex
def test_page_example_row():
w = [2, 1, 2, 1, 2]
xg = [1, 2, Fraction(5, 2), 7, 7]
e = [1] * 5
clusters = place_row(range(5), xg, w, e, 0, 9)
xs = cell_positions(clusters, w)
assert [xs[i] for i in range(5)] == [Fraction(1, 6), Fraction(13, 6), Fraction(19, 6), 6, 7]
assert [c.cells for c in clusters] == [[0, 1, 2], [3, 4]]
assert sum((xs[i] - xg[i]) ** 2 for i in range(5)) == Fraction(13, 6)
x, y = abacus(xg, [0] * 5, w, 1, 9)
assert x == [0, 2, 3, 6, 7] and movement(x, y, xg, [0] * 5) == Fraction(9, 4)
def test_abacus_is_legal_and_keeps_order():
rng = random.Random(4)
for _ in range(150):
K = rng.randint(1, 4)
S = rng.randint(4, 12)
n = rng.randint(1, K * S // 2)
w = [rng.randint(1, 3) for _ in range(n)]
while sum(w) > K * S - 3 * K and n > 1:
w.pop()
n -= 1
xg = [Fraction(rng.randint(-8, 4 * S + 8), 4) for _ in range(n)]
yg = [Fraction(rng.randint(-2, 4 * K + 2), 4) for _ in range(n)]
try:
x, y = abacus(xg, yg, w, K, S)
except ValueError:
continue # no row had room for some cell
check_legal(x, y, w, K, S)
for r in range(K):
row = [i for i in range(n) if y[i] == r]
assert sorted(row, key=lambda i: (xg[i], i)) == sorted(row, key=lambda i: x[i])
def test_one_row_rounding_close_to_integer_optimum():
# the rounded result is legal and its cost is at least the best integer placement in the same order
rng = random.Random(9)
for _ in range(100):
n = 4
w = [rng.randint(1, 2) for _ in range(n)]
S = sum(w) + rng.randint(0, 3)
xg = [Fraction(rng.randint(0, 4 * S), 4) for _ in range(n)]
x, y = abacus(xg, [0] * n, w, 1, S)
check_legal(x, y, w, 1, S)
order = sorted(range(n), key=lambda i: (xg[i], i))
best = None
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((xs[k] - xg[order[k]]) ** 2 for k in range(n))
best = c if best is None or c < best else best
assert movement(x, y, xg, [0] * n) >= best
cont = qp_brute_force(order, xg, w, [1] * n, S)[0]
assert best >= cont
def test_no_room():
with pytest.raises(ValueError):
abacus([0, 0, 0], [0, 0, 0], [2, 2, 2], 1, 5)
History
Tetris legalization (Hill, US patent 6,370,673, 2002) puts each cell at the nearest free place and never moves it again. Spindler, Schlichtmann and Johannes presented Abacus at ISPD 2008; the same group made the Kraftwerk2 placer in the same year. Its name comes from the beads of an abacus, which slide on a wire and push each other. The idea of merging adjacent blocks whose order is violated is older: it is the pool adjacent violators algorithm of isotonic regression (Ayer, Brunk, Ewing, Reid and Silverman, 1955). The linear cost version of the one-row problem was solved as a scheduling problem by Garey, Tarjan and Wilfong in 1988.
References
- 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 algorithm, the procedures PlaceRow, AddCell, AddCluster and Collapse, and the comparison of the movement with Tetris on benchmark circuits
- Michael R. Garey, Robert E. Tarjan and Gordon T. Wilfong, One-processor scheduling with symmetric earliness and tardiness penalties, Mathematics of Operations Research 13(2), 330 to 348, 1988, the same one-row problem with a fixed order and the linear (not squared) cost, solved in O(n log n) time
- 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)
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 4DKME3 Edit this page History Report an error Markdown