Algorithm Search⌘K

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.

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
Properties
deterministicnot exactiterative
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 xx 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 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, a weight ei>0e_i > 0 and a global position (xi′,yi′)(x'_i, y'_i) of its lower left corner. A legal placement gives each cell a row yi∈{y0,…,yK−1}y_i \in \{y_0, \ldots, y_{K-1}\} and an integer xix_i with 0≤xi0 \le x_i and xi+Wi≤Sx_i + W_i \le S, and no two cells of the same row overlap. The goal is a legal placement with a small weighted squared movement

∑iei((xi−xi′)2+(yi−yi′)2).\sum_i e_i \left( (x_i - x'_i)^2 + (y_i - y'_i)^2 \right).

Inside PlaceRow, the row is the interval [a,b]=[0,S][a, b] = [0, S], the cells of the row are 1,…,k1, \ldots, k in a fixed left to right order with ∑Wj≤b−a\sum W_j \le b - a, and PlaceRow solves the quadratic program

min⁡∑j=1kej(xj−xj′)2subject tox1≥a,xj+Wj≤xj+1,xk+Wk≤b,\min \sum_{j=1}^{k} e_j (x_j - x'_j)^2 \quad \text{subject to} \quad x_1 \ge a, \quad x_j + W_j \le x_{j+1}, \quad x_k + W_k \le b,

with real xjx_j. A cluster is a run of cells of the row that abut. It has a total weight ece_c, a total width WcW_c, a position xcx_c of its left edge, and the number qc=∑ej(xj′−dj)q_c = \sum e_j (x'_j - d_j), where djd_j is the offset of cell jj from the left edge of the cluster. The best position of a cluster alone is then qc/ecq_c / e_c.

The algorithm

  1. ABACUS(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 in order of |y_r − y'_i|
  5. 4if some row has a cost already and (y_r − y'_i)^2 ≥ the best cost, then stop the loop over rows
  6. 5if the cells of r together with i are wider than S, then skip r
  7. 6place the cells of r followed by i with PLACEROW, as a trial
  8. 7cost(r) ← (x_i − x'_i)^2 + (y_r − y'_i)^2, with x_i the trial position of i
  9. 8append i to the row of least cost; if no row had room, stop with failure
  10. 9for each row: PLACEROW on its cells, round each x_c to the nearest site, and put the cells of each cluster side by side
  11. PLACEROW(cells 1 .. k of the row, in order)
  12. 10for j ← 1 to k
  13. 11if there is no cluster, or the last cluster c has x_c + W_c ≤ x'_j, then start a new empty cluster c
  14. 12add 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
  15. 13COLLAPSE(c)
  16. COLLAPSE(c)
  17. 14x_c ← q_c / e_c
  18. 15if x_c < a then x_c ← a; if x_c > b − W_c then x_c ← b − W_c
  19. 16if c has a cluster c' before it with x_{c'} + W_{c'} > x_c
  20. 17append c to c' as in L18, remove c, and COLLAPSE(c')
  21. 18q_{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 (yr−yi′)2(y_r - y'_i)^2. The trial cost of line L7 counts only the movement of cell ii; 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 WcW_c (the width before the addition) from the left edge, so its term in qcq_c is ej(xj′−Wc)e_j (x'_j - W_c). In line L18 every cell of cc gets the extra offset Wc′W_{c'}, which subtracts ecWc′e_c W_{c'} from its part of qq. Line L16 is the merge test: the two clusters overlap.

Example

One row. A row of S=9S = 9 sites gets five cells, all of weight 1, in this order:

cell 0 1 2 3 4
width WjW_j 2 1 2 1 2
global xj′x'_j 1 2 52\frac52 7 7

The clusters of PlaceRow after each cell, from the implementation with Fractions:

after cell clusters (cells at xcx_c) what happens
0 {0}\{0\} at 1 a new cluster at x0′x'_0
1 {0,1}\{0, 1\} at 12\frac12 cell 1 wants 2, but cell 0 ends at 3; q=1+0q = 1 + 0, e=2e = 2
2 {0,1,2}\{0, 1, 2\} at 16\frac16 q=1+(52−3)=12q = 1 + (\frac52 - 3) = \frac12, e=3e = 3
3 {0,1,2}\{0, 1, 2\} at 16\frac16, {3}\{3\} at 7 the first cluster ends at 316≤7\frac{31}{6} \le 7, so a new cluster
4 {0,1,2}\{0, 1, 2\} at 16\frac16, {3,4}\{3, 4\} at 6 q=7+(7−1)=13q = 7 + (7 - 1) = 13, e=2e = 2, so xc=132x_c = \frac{13}{2}, but the row ends at 9 and Wc=3W_c = 3, so xc=6x_c = 6

The cells are at 16,136,196,6,7\frac16, \frac{13}{6}, \frac{19}{6}, 6, 7 with the squared movement 136\frac{13}{6}, the least for this order. Line L9 rounds 16\frac16 to 0 and keeps 6, so the legal positions are 0,2,3,6,70, 2, 3, 6, 7 with the squared movement 94\frac94.

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

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 trials of Abacus, from the implementation:

cell first row tried: trial xix_i, cost second row tried chosen
0 row 0: 1, cost 0 row 1: stopped by L4 0
1 row 1: 32\frac32, cost 0 row 0: stopped by L4 1
2 row 1: 114\frac{11}{4}, cost 916\frac{9}{16} row 0: stopped by L4 1
3 row 1: 103\frac{10}{3}, cost 2536\frac{25}{36} row 0: stopped by L4 1
4 row 1: full (width 7 > 6) row 0: 52\frac52, cost 1 0
5 row 0: 113\frac{11}{3}, cost 4936\frac{49}{36} row 1: 5, cost 294\frac{29}{4} 0

At the end row 0 holds the cluster {0,4,5}\{0, 4, 5\} at 23\frac23 and row 1 the cluster {1,2,3}\{1, 2, 3\} at 13\frac13. After rounding, x=(1,0,2,3,2,4)x = (1, 0, 2, 3, 2, 4) and y=(0,1,1,1,0,0)y = (0, 1, 1, 1, 0, 0). The squared movement is 6 and the Manhattan movement is 5. Tetris on the same input gives 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 squared movement 9 and the Manhattan movement 6: cell 5 must go to x=5x = 5, because Tetris cannot push cells 0 and 4 to the left.

Correctness

The proof shows the following.

  • The substitution. With uj=xj−∑l<jWlu_j = x_j - \sum_{l < j} W_l and tj=xj′−∑l<jWlt_j = x'_j - \sum_{l < j} W_l, the row problem becomes: minimize ∑ej(uj−tj)2\sum e_j (u_j - t_j)^2 subject to a≤u1≤u2≤⋯≤uk≤b−∑lWla \le u_1 \le u_2 \le \cdots \le u_k \le b - \sum_l W_l. That is isotonic regression with a lower and an upper bound. A cluster is a block of equal uu, its position qc/ecq_c / e_c is the weighted mean of tt 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 jj, the clusters are the unique minimum of the problem on the cells 1,…,j1, \ldots, j. 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 ⌊x+12⌋\lfloor x + \frac12 \rfloor 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 ii 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 (yr−yi′)2(y_r - y'_i)^2, 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 [a,b][a, b] and its cells 1,…,k1, \ldots, k in the given order, with integer widths Wi≥1W_i \ge 1, weights ei>0e_i > 0, targets xi′x'_i, and ∑iWi≤b−a\sum_i W_i \le b - a. Write ωi=∑l<iWl\omega_i = \sum_{l < i} W_l for the width of the cells before ii (so ω1=0\omega_1 = 0), and

ti=xi′−ωi,Bj=b−ωj+1(1≤j≤k).t_i = x'_i - \omega_i, \qquad B_j = b - \omega_{j+1} \quad (1 \le j \le k).

Then B1>B2>⋯>Bk=b−∑iWi≥aB_1 > B_2 > \cdots > B_k = b - \sum_i W_i \ge a, because each Wi≥1W_i \ge 1. For a set β\beta of consecutive cells, write Eβ=∑i∈βeiE_\beta = \sum_{i \in \beta} e_i, mβ=∑i∈βeiti/Eβm_\beta = \sum_{i \in \beta} e_i t_i / E_\beta (the weighted mean of tt on β\beta) and fβ(v)=∑i∈βei(ti−v)=Eβ(mβ−v)f_\beta(v) = \sum_{i \in \beta} e_i (t_i - v) = E_\beta (m_\beta - v). If β\beta is split into a prefix π\pi and a suffix σ\sigma, then fβ=fπ+fσf_\beta = f_\pi + f_\sigma.

Lemma 1 (the substitution). Let RjR_j be the problem: minimize ∑i≤jei(ui−ti)2\sum_{i \le j} e_i (u_i - t_i)^2 subject to a≤u1≤u2≤⋯≤uj≤Bja \le u_1 \le u_2 \le \cdots \le u_j \le B_j. The map ui=xi−ωiu_i = x_i - \omega_i is a bijection from the positions xx of cells 1,…,j1, \ldots, j with x1≥ax_1 \ge a, xi+Wi≤xi+1x_i + W_i \le x_{i+1} and xj+Wj≤bx_j + W_j \le b, onto the feasible set of RjR_j, and it keeps the objective ∑ei(xi−xi′)2\sum e_i (x_i - x'_i)^2.

Proof. xi+Wi≤xi+1x_i + W_i \le x_{i+1} is ui+ωi+Wi≤ui+1+ωi+1u_i + \omega_i + W_i \le u_{i+1} + \omega_{i+1}, and ωi+1=ωi+Wi\omega_{i+1} = \omega_i + W_i, so it is ui≤ui+1u_i \le u_{i+1}. x1≥ax_1 \ge a is u1≥au_1 \ge a. xj+Wj≤bx_j + W_j \le b is uj≤b−ωj+1=Bju_j \le b - \omega_{j+1} = B_j. Finally xi−xi′=ui−tix_i - x'_i = u_i - t_i. □\square

Lemma 2 (clusters in the new coordinates). Let cc be a cluster of the cells l,…,rl, \ldots, r in PlaceRow. Then Wc=ωr+1−ωlW_c = \omega_{r+1} - \omega_l, qc=Ec(mc+ωl)q_c = E_c (m_c + \omega_l), and with uc=xc−ωlu_c = x_c - \omega_l (the common value of uu on the cluster):

  1. line L14 sets uc=mcu_c = m_c;
  2. line L15 clamps ucu_c to [a−ωl,Br][a - \omega_l, B_r];
  3. the test of line L16 for the cluster c′c' just before cc is uc′>ucu_{c'} > u_c.

Proof. The offset of cell ii in the cluster is ωi−ωl\omega_i - \omega_l. Line L12 adds cell j=rj = r with the offset Wc=ωj−ωlW_c = \omega_j - \omega_l, and line L18 adds to each cell of cc the offset Wc′W_{c'}, the width before it. By induction on these two lines, qc=∑i=lrei(xi′−ωi+ωl)=∑ei(ti+ωl)=Ec(mc+ωl)q_c = \sum_{i=l}^{r} e_i (x'_i - \omega_i + \omega_l) = \sum e_i (t_i + \omega_l) = E_c (m_c + \omega_l). So qc/ec−ωl=mcq_c / e_c - \omega_l = m_c. The clamp xc≥ax_c \ge a is uc≥a−ωlu_c \ge a - \omega_l, and xc≤b−Wcx_c \le b - W_c is uc≤b−ωr+1=Bru_c \le b - \omega_{r+1} = B_r. If c′c' has the cells l′,…,l−1l', \ldots, l - 1, then xc′+Wc′=uc′+ωl′+(ωl−ωl′)=uc′+ωlx_{c'} + W_{c'} = u_{c'} + \omega_{l'} + (\omega_l - \omega_{l'}) = u_{c'} + \omega_l, which is more than xc=uc+ωlx_c = u_c + \omega_l exactly when uc′>ucu_{c'} > u_c. □\square

The plain run. In the plain run, cell jj always starts a new cluster {j}\{j\}. The current (last) cluster γ\gamma gets the value uγ=min⁡(max⁡(mγ,a),Bj)u_\gamma = \min(\max(m_\gamma, a), B_j) if it is the first cluster of the row, and uγ=min⁡(mγ,Bj)u_\gamma = \min(m_\gamma, B_j) otherwise. While a cluster β\beta comes just before γ\gamma with uβ>uγu_\beta > u_\gamma, the two merge into the current cluster βγ\beta\gamma, 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 aa: the first cluster is clamped to aa 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 jj to the last cluster cc when uc>tju_c > t_j (Lemma 2 with xj′=tj+ωjx'_j = t_j + \omega_j). In the plain run, {j}\{j\} gets a value at most tj<uct_j < u_c, so it merges with cc at once, and line L18 for the one-cell cluster with q=ejxj′q = e_j x'_j makes the same change as line L12. Both then collapse the merged cluster. (ii) A cluster γ\gamma that is not the first is clamped from below to a−ωla - \omega_l by line L15, and not in the plain run. If mγ≥a−ωlm_\gamma \ge a - \omega_l, the clamp does nothing. If mγ<a−ωlm_\gamma < a - \omega_l, PlaceRow gives uγ=a−ωl<au_\gamma = a - \omega_l < a and the plain run gives uγ≤mγ<au_\gamma \le m_\gamma < a. Both are less than the value of the cluster before it, which is at least aa, so both runs merge, and the merged value is computed again from qq and ee. □\square

Good blocks. Call a block β\beta balanced if every proper prefix π\pi has mπ≥mβm_\pi \ge m_\beta. Because fπ(mβ)+fσ(mβ)=fβ(mβ)=0f_\pi(m_\beta) + f_\sigma(m_\beta) = f_\beta(m_\beta) = 0 for the complementary suffix σ\sigma, this is the same as: every proper suffix has mσ≤mβm_\sigma \le m_\beta. Call β\beta high at vv if every proper prefix has mπ≥vm_\pi \ge v, and low at vv if every proper suffix has mσ≤vm_\sigma \le v. A block of one cell is all of these. A balanced block is high at every v≤mβv \le m_\beta and low at every v≥mβv \ge m_\beta.

Invariant (J) after cell jj. The clusters β1,…,βs\beta_1, \ldots, \beta_s have values v1≤v2≤⋯≤vsv_1 \le v_2 \le \cdots \le v_s, with a≤v1a \le v_1 and vs≤Bjv_s \le B_j, and each βk\beta_k is in one of three states:

  • free: vk=mβkv_k = m_{\beta_k} and βk\beta_k is balanced;
  • low: k=1k = 1, v1=a>mβ1v_1 = a > m_{\beta_1}, and β1\beta_1 is low at aa;
  • high: k=sk = s, vs=Bj<mβsv_s = B_j < m_{\beta_s}, and βs\beta_s is high at BjB_j.

Lemma 4 (optimality). If (J) holds after cell jj, the values of the clusters, copied to their cells, are the unique minimum of RjR_j.

Proof. Let ui=vku_i = v_k for i∈βki \in \beta_k. It is feasible by (J). If a=Bja = B_j, the feasible set is the single point u=au = a, and we are done. Let a<Bja < B_j, so no cluster is both low and high. The objective is strictly convex because every ei>0e_i > 0, 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 λ0≥0\lambda_0 \ge 0 for a−u1≤0a - u_1 \le 0, λi≥0\lambda_i \ge 0 for ui−ui+1≤0u_i - u_{i+1} \le 0 (1≤i<j1 \le i < j), and λj≥0\lambda_j \ge 0 for uj−Bj≤0u_j - B_j \le 0, the stationarity condition for uiu_i is ei(ui−ti)+λi−λi−1=0e_i (u_i - t_i) + \lambda_i - \lambda_{i-1} = 0. So set

λ0={−fβ1(a)if β1 is low,0otherwise,λi=λ0+∑l≤iel(tl−ul)(1≤i≤j).\lambda_0 = \begin{cases} -f_{\beta_1}(a) & \text{if } \beta_1 \text{ is low,} \\ 0 & \text{otherwise,} \end{cases} \qquad \lambda_i = \lambda_0 + \sum_{l \le i} e_l (t_l - u_l) \quad (1 \le i \le j).

Stationarity holds by construction. It remains to show that every λi≥0\lambda_i \ge 0, with complementary slackness. Note λ0≥0\lambda_0 \ge 0, since a low block has mβ1<am_{\beta_1} < a.

At the end of a cluster. The sum over a cluster βk\beta_k is fβk(vk)f_{\beta_k}(v_k). It is 0 for a free cluster, fβ1(a)f_{\beta_1}(a) for the low cluster, and fβs(Bj)>0f_{\beta_s}(B_j) > 0 for the high cluster. So λi=0\lambda_i = 0 at the last cell of each βk\beta_k with k<sk < s: the low part cancels λ0\lambda_0, and the high cluster can only be the last. At i=ji = j, λj=fβs(Bj)>0\lambda_j = f_{\beta_s}(B_j) > 0 if βs\beta_s is high, and then uj=Bju_j = B_j; otherwise λj=0\lambda_j = 0. Also λ0>0\lambda_0 > 0 only if β1\beta_1 is low, and then u1=au_1 = a. So slackness holds for the bounds and for the constraints between clusters.

Inside a cluster βk\beta_k with the cells l,…,rl, \ldots, r, for l≤i<rl \le i < r, let π={l,…,i}\pi = \{l, \ldots, i\} and σ={i+1,…,r}\sigma = \{i + 1, \ldots, r\}. Then ui=ui+1u_i = u_{i+1}, so slackness holds, and λi=λl−1+fπ(vk)\lambda_i = \lambda_{l-1} + f_\pi(v_k), where λl−1=0\lambda_{l-1} = 0 for k≥2k \ge 2 and λl−1=λ0\lambda_{l - 1} = \lambda_0 for k=1k = 1. If βk\beta_k is free, fπ(mβk)≥0f_\pi(m_{\beta_k}) \ge 0 since it is balanced, so λi≥0\lambda_i \ge 0. If βk\beta_k is high, λl−1≥0\lambda_{l-1} \ge 0 and fπ(Bj)≥0f_\pi(B_j) \ge 0 since mπ≥Bjm_\pi \ge B_j. If βk=β1\beta_k = \beta_1 is low, λi=−fβ1(a)+fπ(a)=−fσ(a)≥0\lambda_i = -f_{\beta_1}(a) + f_\pi(a) = -f_\sigma(a) \ge 0 since mσ≤am_\sigma \le a. □\square

Lemma 5 (one step keeps (J)). If (J) holds after cell j−1j - 1 (or j=1j = 1), it holds after cell jj in the plain run.

Proof. Write B=BjB = B_j, and B′=Bj−1>BB' = B_{j-1} > B if j≥2j \ge 2. Note a≤Ba \le B. During the collapse of step jj we keep this claim (K): the clusters before the current cluster γ\gamma are in the states of (J) for j−1j - 1 with the bound B′B', a high cluster among them can only be the one just before γ\gamma, and then γ={j}\gamma = \{j\}; the current cluster is either balanced with uγ=mγu_\gamma = m_\gamma, or high at BB with uγ=B<mγu_\gamma = B < m_\gamma, or (only if it is the first cluster) low at aa with uγ=a>mγu_\gamma = a > m_\gamma.

At the start γ={j}\gamma = \{j\} is one cell, so it is in the state that its value gives, and (K) holds. Now let β\beta be the cluster before γ\gamma with uβ>uγu_\beta > u_\gamma, and let m=mβγm = m_{\beta\gamma}, a weighted mean of mβm_\beta and mγm_\gamma. The prefixes of βγ\beta\gamma are the proper prefixes of β\beta, β\beta itself, and β\beta with a proper prefix of γ\gamma; the suffixes are similar.

  1. β\beta free and γ\gamma balanced. Then mβ>mγm_\beta > m_\gamma, so mγ<m<mβm_\gamma < m < m_\beta. A proper prefix π\pi of β\beta has mπ≥mβ>mm_\pi \ge m_\beta > m, and mβ>mm_\beta > m. For π=β∪γ′\pi = \beta \cup \gamma' with a proper prefix γ′\gamma' of γ\gamma, the rest is a proper suffix σ\sigma of γ\gamma with mσ≤mγ<mm_\sigma \le m_\gamma < m, so fπ(m)=−fσ(m)>0f_\pi(m) = -f_\sigma(m) > 0. So βγ\beta\gamma is balanced, and its new value puts it in the free, high or low state.
  2. β\beta free and γ\gamma high. Then mβ=uβ>Bm_\beta = u_\beta > B and mγ>Bm_\gamma > B, so m>B≥am > B \ge a and the new value is BB. A proper prefix of β\beta has mean at least mβ>Bm_\beta > B; β\beta has mβ>Bm_\beta > B; and β∪γ′\beta \cup \gamma' has f=fβ(B)+fγ′(B)>0f = f_\beta(B) + f_{\gamma'}(B) > 0. So βγ\beta\gamma is high at BB.
  3. β\beta low (so it is the first cluster, uβ=au_\beta = a). Then γ\gamma is not first and uγ=min⁡(mγ,B)<a≤Bu_\gamma = \min(m_\gamma, B) < a \le B, so uγ=mγu_\gamma = m_\gamma and γ\gamma is balanced. Then m<am < a, and the new value of the first cluster βγ\beta\gamma is aa. A proper suffix of γ\gamma has mean at most mγ<am_\gamma < a; γ\gamma has mγ<am_\gamma < a; and β′′∪γ\beta'' \cup \gamma for a proper suffix β′′\beta'' of β\beta has f=fβ′′(a)+fγ(a)<0f = f_{\beta''}(a) + f_\gamma(a) < 0. So βγ\beta\gamma is low at aa.
  4. β\beta high at B′B'. By (K), γ={j}\gamma = \{j\}, with t=tjt = t_j, and uβ=B′>B≥uγu_\beta = B' > B \ge u_\gamma. Every proper prefix of β\beta has mean at least B′B', and mβ>B′m_\beta > B'. Let vv be the new value. If v≤mv \le m, then v≤B<B′v \le B < B', so every proper prefix of βγ\beta\gamma (those of β\beta, and β\beta) has mean more than vv: βγ\beta\gamma is high at vv, which is the high state for v=B<mv = B < m and the balanced (free) state for v=mv = m. If v>mv > m, then βγ\beta\gamma is first and v=a>mv = a > m. Since m<a<mβm < a < m_\beta, also t<m<at < m < a, so the suffix {j}\{j\} is fine. For σ=β′′∪{j}\sigma = \beta'' \cup \{j\} with a proper suffix β′′\beta'' of β\beta and the rest β′\beta' of β\beta, fσ(a)=fβγ(a)−fβ′(a)<0f_\sigma(a) = f_{\beta\gamma}(a) - f_{\beta'}(a) < 0, because fβγ(a)=E(m−a)<0f_{\beta\gamma}(a) = E (m - a) < 0 and mβ′≥B′>am_{\beta'} \ge B' > a. So βγ\beta\gamma is low at aa.

The case β\beta low and γ\gamma high would need a=uβ>uγ=Ba = u_\beta > u_\gamma = B, which is false, and the case β\beta high with γ≠{j}\gamma \ne \{j\} is excluded by (K). So (K) holds after each merge. When the collapse stops, either γ\gamma is first or uβ≤uγu_\beta \le u_\gamma for the cluster β\beta before it. A high cluster at B′B' cannot be before γ\gamma, since B′>B≥uγB' > B \ge u_\gamma 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 uγ≤Bu_\gamma \le B, and the first is at least aa. If γ\gamma is not first, uγ≥uβ≥au_\gamma \ge u_\beta \ge a, so γ\gamma is free or high. This is (J) after cell jj. □\square

Theorem 1 (PlaceRow is exact). For the cells of a row in a fixed order with ∑Wi≤b−a\sum W_i \le b - a, PlaceRow returns the unique positions with a≤x1a \le x_1, xi+Wi≤xi+1x_i + W_i \le x_{i+1} and xk+Wk≤bx_k + W_k \le b that minimize ∑ei(xi−xi′)2\sum e_i (x_i - x'_i)^2.

Proof. By Lemmas 3 and 5, (J) holds after cell kk. By Lemma 4 the values solve RkR_k uniquely, and by Lemmas 1 and 2 the cluster positions xc=uc+ωlx_c = u_c + \omega_l give the cells the positions xi=ui+ωix_i = u_i + \omega_i, the unique minimum of the row problem. ■\blacksquare

Theorem 2 (legal output). If Abacus does not stop with failure, line L9 returns a legal placement, and each cell is within 12\frac12 of its position in the exact row minimum.

Proof. Line L5 keeps the total width of each row at most SS, so Theorem 1 applies with [a,b]=[0,S][a, b] = [0, S]. The clusters of the minimum satisfy xc+Wc≤xc+1x_c + W_c \le x_{c+1}, x1≥0x_1 \ge 0 and xlast+Wlast≤Sx_{\text{last}} + W_{\text{last}} \le S. Let R(x)=⌊x+12⌋R(x) = \lfloor x + \frac12 \rfloor. It is nondecreasing, R(n)=nR(n) = n and R(x+n)=R(x)+nR(x + n) = R(x) + n for every integer nn. So R(xc)+Wc=R(xc+Wc)≤R(xc+1)R(x_c) + W_c = R(x_c + W_c) \le R(x_{c+1}), R(x1)≥R(0)=0R(x_1) \ge R(0) = 0, and R(xlast)+Wlast=R(xlast+Wlast)≤R(S)=SR(x_{\text{last}}) + W_{\text{last}} = R(x_{\text{last}} + W_{\text{last}}) \le R(S) = S. The cells of a cluster are put side by side from the integer R(xc)R(x_c), so they lie on sites, they do not overlap each other, and they do not overlap the next cluster. Each cell moves by ∣R(xc)−xc∣≤12|R(x_c) - x_c| \le \frac12. ■\blacksquare

Theorem 3 (failure and the stop of line L4). Abacus stops with failure only if cell ii 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 ii 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 (yr−yi′)2(y_r - y'_i)^2, and the cost of row rr is at least (yr−yi′)2(y_r - y'_i)^2. 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. □\square

Theorem 4 (running time). PlaceRow on kk cells makes at most kk clusters and at most k−1k - 1 merges, so it runs in O(k)O(k) time when a cluster stores its first and last cell. Abacus runs in O(nlog⁡n+Knk)O(n \log n + K n k) time, where kk 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 kk. Each call of COLLAPSE does O(1)O(1) work besides a merge, and there is one call per step plus one per merge. Lines L12 and L18 cost O(1)O(1) 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 kk positions. The sort of line L1 costs O(nlog⁡n)O(n \log n); each of the nn cells makes at most KK trials, each one PlaceRow on at most kk cells, and line L9 costs O(n)O(n) over all rows. ■\blacksquare

Complexity

  • PlaceRow. Each cell starts at most one cluster, and each merge removes one, so a run on kk cells does at most kk merges and O(k)O(k) 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 KK rows, and each trial is one PlaceRow on at most kk cells. With the sort, the worst case is O(nlog⁡n+Knk)O(n \log n + K n k), and k≤nk \le n.
  • In practice. Line L4 stops after tt rows on average, and tt is small when the global placement is good. An implementation can keep the clusters of each row and only add cell ii to the end and collapse, because PlaceRow on the cells of rr followed by ii makes the same clusters for the cells of rr before it reaches ii. 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 O(nlog⁡n+n)O(n \log n + n).
  • Space. The clusters and the rows: O(n+K)O(n + K).
  • 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 12\frac12 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 x′x', 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 rr changes only row rr.

Variants and improvements

  • Linear movement. With the cost ∑ej∣xj−xj′∣\sum e_j |x_j - x'_j| 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 O(nlog⁡n)O(n \log n) 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 ii alone. This is more exact and slower.
  • Several sites per cell and mixed heights. Multi-row cells must take the same xx 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 [a,b][a, b].
  • 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 xx; 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 WcW_c before the new width is added, and in line L18 it uses Wc′W_{c'} 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 ii 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.

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

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

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