Algorithm Search⌘K

Algorithmcore

Quadratic placement

Also called quadratic wirelength minimization.

Minimizes the sum of squared two-pin wire lengths, a convex quadratic solved by sparse linear systems, which clusters cells near the centre.

Solves
Placement
Time
O(P + E + n (n + E)) worstO(P + E + k (n + E)) averageO(P + E + n + E) best
Space
O(n + E) extra
Where
E = the number of two-pin edges of the net model, at most the sum of p(p - 1)/2 over the nets; P = the number of pins; k = the number of conjugate gradient steps; n = the number of movable cells
Properties
deterministicnot exactiterative
Origin
Kenneth M. Hall, Jürgen M. Kleinhans, Georg Sigl, Frank M. Johannes, Kurt J. Antreich, 1970

Quadratic placement gives each movable cell of a netlist a point in the plane by minimizing the sum of the squared lengths of two-pin wires, with the pads fixed. It belongs to chip design (EDA): it is the global placement step of many standard cell placers. The nets are first turned into two-pin edges by the clique net model. The objective is a convex quadratic in the cell coordinates, so its minimum is the solution of one sparse linear system per coordinate, whose matrix is a Laplacian plus a diagonal; the conjugate gradient method solves it. The minimum is exact for the quadratic objective, but that objective is only a model of HPWL, and the minimum ignores overlap: the cells crowd together inside the convex hull of the pads. So quadratic placement is a heuristic for the placement problem, and real placers add spreading.

In plain words

Tie each wire as a rubber band between its two ends, and nail the pads to the board. Let the parts go: they slide until the pull of the bands is balanced. That balance is the placement. Each part ends at the weighted middle of the parts it is tied to.

The bands pull hard on long wires, so the result has no very long wire. But nothing pushes the parts apart. They bunch up in the middle, often on top of each other, and a later step must spread them out.

The problem

The input is a netlist with nn movable cells 0,…,n−10, \ldots, n - 1 and fixed pads at positions (xq,yq)(x_q, y_q), nets ee of pep_e pins with weights we>0w_e > 0, and every pin at the center of its cell or pad (no pin offsets). The clique model gives each pair of pins of net ee the weight we/(pe−1)w_e / (p_e - 1). Summing over the nets gives a weight wijw_{ij} for each pair. The output is real positions (xi,yi)(x_i, y_i) that minimize

Φ(x,y)=∑{i,j}wij((xi−xj)2+(yi−yj)2),\Phi(x, y) = \sum_{\{i, j\}} w_{ij} \left( (x_i - x_j)^2 + (y_i - y_j)^2 \right),

the sum over all pairs with a cell or a pad on each end. The output is not a legal placement; it may have overlap.

The objective is the sum of a part in xx and a part in yy, so the two coordinates are solved apart. For the xx part, let AA be the n×nn \times n matrix with

Aii=∑jwij,Aij=−wij    (i≠j both cells),bi=∑q padwiqxq,A_{ii} = \sum_{j} w_{ij}, \qquad A_{ij} = -w_{ij} \;\; (i \ne j \text{ both cells}), \qquad b_i = \sum_{q \text{ pad}} w_{iq} x_q,

where the first sum runs over cells and pads. Then Φx(x)=xTAx−2bTx+c\Phi_x(x) = x^{\mathsf T} A x - 2 b^{\mathsf T} x + c for a constant cc, and AA is the Laplacian of the cell to cell edges plus the diagonal of the cell to pad weights.

The algorithm

  1. QUADRATIC-PLACE(n, nets, w, pads)
  2. 1for each net e with p ≥ 2 pins: add w_e / (p − 1) to w_ij for each pair {i, j} of its pins
  3. 2build A and b_x, b_y from the weights w_ij as above
  4. 3if some connected group of cells has no edge to a pad then stop: A is singular
  5. 4for each coordinate c ∈ {x, y}
  6. 5z ← 0; r ← b_c; d ← r
  7. 6while |r|^2 > tol^2 |b_c|^2
  8. 7α ← |r|^2 / (dᵀ A d)
  9. 8z ← z + α d; r_new ← r − α A d
  10. 9β ← |r_new|^2 / |r|^2; d ← r_new + β d; r ← r_new
  11. 10c_i ← z_i for each cell i
  12. 11return the positions (x_i, y_i)

Lines L1 and L2 build the system; an edge between two pads is a constant and is left out. Line L3 checks the condition of the Theorem below: without it the cells of a free group can slide together to any place, and the minimum is not unique. Lines L5 to L9 are the conjugate gradient method from z=0z = 0, with residual r=b−Azr = b - A z and search direction dd. With exact rational arithmetic and tol=0tol = 0, the loop stops with r=0r = 0 after at most nn steps. With floating point it stops when the residual is small relative to bb.

Example

Four cells a,b,c,da, b, c, d and two pads, PP at (0,0)(0, 0) and QQ at (6,3)(6, 3). The nets, all of weight 1, are

{P,a},  {a,b},  {a,c},  {b,c,d},  {d,Q}.\{P, a\}, \; \{a, b\}, \; \{a, c\}, \; \{b, c, d\}, \; \{d, Q\}.

The 3-pin net gives the pairs bcbc, bdbd and cdcd the weight 12\frac12 each; every other pair has weight 1. With the cells in the order a,b,c,da, b, c, d,

A=(3−1−10−12−12−12−1−122−120−12−122),bx=(0,0,0,6),by=(0,0,0,3).A = \begin{pmatrix} 3 & -1 & -1 & 0 \\ -1 & 2 & -\frac12 & -\frac12 \\ -1 & -\frac12 & 2 & -\frac12 \\ 0 & -\frac12 & -\frac12 & 2 \end{pmatrix}, \qquad b_x = (0, 0, 0, 6), \qquad b_y = (0, 0, 0, 3).

Exact conjugate gradients on Ax=bxA x = b_x, from the implementation with Fractions:

step ∣r∣2\lvert r \rvert^2 after the step xx after the step
0 36 (0,0,0,0)(0, 0, 0, 0)
1 92\frac92 (0,0,0,3)(0, 0, 0, 3)
2 14425\frac{144}{25} (65,125,125,215)(\frac{6}{5}, \frac{12}{5}, \frac{12}{5}, \frac{21}{5})
3 0 (127,187,187,307)(\frac{12}{7}, \frac{18}{7}, \frac{18}{7}, \frac{30}{7})

The residual norm goes up in step 2: conjugate gradients make the error small in the norm of AA, not the residual. The method stops after 3 steps, not 4, because bb and cc play the same role, so AA has only 3 different eigenvalues on the space that bxb_x spans. The yy system has by=bx/2b_y = b_x / 2, so y=x/2y = x / 2. The result is

a=(127,67),b=c=(187,97),d=(307,157).a = (\tfrac{12}{7}, \tfrac{6}{7}), \quad b = c = (\tfrac{18}{7}, \tfrac{9}{7}), \quad d = (\tfrac{30}{7}, \tfrac{15}{7}).

Each cell is at the weighted mean of its neighbors: for aa, (0+187+187)/3=127(0 + \frac{18}{7} + \frac{18}{7}) / 3 = \frac{12}{7}. The cells bb and cc lie on the same point, which is the overlap that a later step must remove. All four cells lie on the segment from PP to QQ. The objective is Φ=907\Phi = \frac{90}{7}, and the HPWL of the result is 727\frac{72}{7}.

Correctness

The proof shows the following.

  • The system. Φx(x)=xTAx−2bTx+c\Phi_x(x) = x^{\mathsf T} A x - 2 b^{\mathsf T} x + c, so the gradient is 2(Ax−b)2 (A x - b).
  • Uniqueness. xTAx=∑wij(xi−xj)2+∑wiqxi2x^{\mathsf T} A x = \sum w_{ij} (x_i - x_j)^2 + \sum w_{iq} x_i^2 over the cell to cell and the cell to pad edges. If every connected group of cells has an edge to a pad, this is zero only for x=0x = 0, so AA is positive definite and Φ\Phi has exactly one minimum, the solution of Ax=bA x = b. If some group has no edge to a pad, AA is singular and line L3 stops.
  • Termination. For a positive definite AA, exact conjugate gradients reach r=0r = 0 in at most nn steps (Hestenes and Stiefel 1952).
  • Weighted means and the hull. At the minimum each cell is at the weighted mean of its neighbors, and every cell lies in the convex hull of the pads that its group reaches. So the result puts all cells in the hull of the pads, and with few pads, many cells meet in a small area.
Proof: Quadratic placement has a unique minimum when every group of cells reaches a pad, conjugate gradients find it, and it lies in the hull of the padsfull

Write VV for the cells, FF for the pads, and wij>0w_{ij} > 0 for the weight of a pair after the clique model (pairs with weight 0 are not edges). The xx part of the objective is

Φx(x)=∑{i,j}⊆Vwij(xi−xj)2+∑i∈V, q∈Fwiq(xi−xq)2.\Phi_x(x) = \sum_{\{i, j\} \subseteq V} w_{ij} (x_i - x_j)^2 + \sum_{i \in V, \, q \in F} w_{iq} (x_i - x_q)^2 .

The yy part has the same form, and Φ=Φx+Φy\Phi = \Phi_x + \Phi_y with no term that joins xx and yy, so it is enough to treat Φx\Phi_x. Pairs of two pads add a constant and are left out.

Lemma 1 (the system). With AA and bb as on the page, Φx(x)=xTAx−2bTx+c\Phi_x(x) = x^{\mathsf T} A x - 2 b^{\mathsf T} x + c with c=∑wiqxq2c = \sum w_{iq} x_q^2, and ∇Φx=2(Ax−b)\nabla \Phi_x = 2 (A x - b).

Proof. Expand each square. A cell pair gives wijxi2+wijxj2−2wijxixjw_{ij} x_i^2 + w_{ij} x_j^2 - 2 w_{ij} x_i x_j. In xTAxx^{\mathsf T} A x the term xi2x_i^2 has the coefficient Aii=∑j∈Vwij+∑q∈FwiqA_{ii} = \sum_{j \in V} w_{ij} + \sum_{q \in F} w_{iq}, and the term xixjx_i x_j appears twice with Aij=−wijA_{ij} = -w_{ij}, which gives −2wijxixj-2 w_{ij} x_i x_j. A cell to pad pair gives wiqxi2−2wiqxqxi+wiqxq2w_{iq} x_i^2 - 2 w_{iq} x_q x_i + w_{iq} x_q^2: the first part is in AiiA_{ii}, the second is −2bixi-2 b_i x_i summed over qq, and the third is in cc. The gradient of xTAxx^{\mathsf T} A x is 2Ax2 A x because AA is symmetric. □\square

Lemma 2 (positive definite). Call a connected component of the graph on VV with the cell to cell edges a group. If every group has a cell with an edge to a pad, AA is positive definite. If some group has none, AA is singular.

Proof. By the same expansion as in Lemma 1 with xq=0x_q = 0,

xTAx=∑{i,j}⊆Vwij(xi−xj)2+∑i,qwiqxi2≥0.x^{\mathsf T} A x = \sum_{\{i, j\} \subseteq V} w_{ij} (x_i - x_j)^2 + \sum_{i, q} w_{iq} x_i^2 \ge 0 .

If this is 0, every term is 0. The first sum makes xx constant on each group, and the second makes xi=0x_i = 0 for every cell with a pad edge. If every group has such a cell, x=0x = 0. So xTAx>0x^{\mathsf T} A x > 0 for x≠0x \ne 0. If a group GG has no pad edge, let xx be 1 on GG and 0 elsewhere. Every edge inside GG has equal ends, no edge leaves GG to another cell (since GG is a component), and no cell of GG has a pad edge, so xTAx=0x^{\mathsf T} A x = 0 for this x≠0x \ne 0, and Ax=0A x = 0 because AA is positive semidefinite. □\square

Theorem 1 (unique minimum). If every group reaches a pad, Φ\Phi has exactly one minimizer, the solutions of Ax=bxA x = b_x and Ay=byA y = b_y.

Proof. For a positive definite AA, Φx\Phi_x is strictly convex, because Φx(x+tu)=Φx(x)+2tuT(Ax−b)+t2uTAu\Phi_x(x + t u) = \Phi_x(x) + 2 t u^{\mathsf T}(A x - b) + t^2 u^{\mathsf T} A u with uTAu>0u^{\mathsf T} A u > 0 for u≠0u \ne 0. Let x∗=A−1bx^\ast = A^{-1} b. Then for every u≠0u \ne 0, Φx(x∗+u)=Φx(x∗)+uTAu>Φx(x∗)\Phi_x(x^\ast + u) = \Phi_x(x^\ast) + u^{\mathsf T} A u > \Phi_x(x^\ast). So x∗x^\ast is the only minimizer. The same holds for yy. ■\blacksquare

Theorem 2 (termination of conjugate gradients). For a positive definite AA of order nn, lines L5 to L9 in exact arithmetic with tol=0tol = 0 stop after at most nn steps with r=0r = 0, and then z=A−1bz = A^{-1} b.

Proof. The loop keeps r=b−Azr = b - A z: line L8 adds αd\alpha d to zz and subtracts αAd\alpha A d from rr. The conjugate gradient method has the property that, as long as no residual is zero, the residuals r0,r1,…r_0, r_1, \ldots are pairwise orthogonal and α\alpha is defined because dTAd>0d^{\mathsf T} A d > 0 for d≠0d \ne 0 (Hestenes and Stiefel 1952; the induction is on the conjugate gradient method page). Pairwise orthogonal nonzero vectors in Rn\mathbb{R}^n are linearly independent, so there are at most nn of them, and rk=0r_k = 0 for some k≤nk \le n. Then Az=bA z = b. □\square

Lemma 3 (weighted mean). At the minimum, xi=(∑j∈Vwijxj+∑q∈Fwiqxq)/Aiix_i = \left( \sum_{j \in V} w_{ij} x_j + \sum_{q \in F} w_{iq} x_q \right) / A_{ii} for every cell ii, and the same for yy.

Proof. Row ii of Ax=bA x = b reads Aiixi−∑j∈Vwijxj=∑qwiqxqA_{ii} x_i - \sum_{j \in V} w_{ij} x_j = \sum_q w_{iq} x_q. Divide by Aii>0A_{ii} > 0; it is positive because every cell has an edge (a cell with no edge forms a group with no pad and was excluded). □\square

Theorem 3 (convex hull). Let GG be a group and FGF_G the set of pads with an edge to a cell of GG. At the minimum, every cell of GG lies in the convex hull of the positions of FGF_G.

Proof. Take any vector u∈R2u \in \mathbb{R}^2, and let f(v)=u⋅(xv,yv)f(v) = u \cdot (x_v, y_v) for cells and pads. By Lemma 3, f(i)f(i) is the weighted mean of ff over the neighbors of ii, with positive weights, because ff is linear. Let M=max⁡i∈Gf(i)M = \max_{i \in G} f(i) and suppose that M>max⁡q∈FGf(q)M > \max_{q \in F_G} f(q). Let SS be the cells of GG with f=Mf = M. For i∈Si \in S, every neighbor has f≤Mf \le M: a cell neighbor is in GG, and a pad neighbor is in FGF_G with f<Mf < M. A weighted mean with positive weights of values at most MM equals MM only if all values equal MM. So every neighbor of ii is a cell of SS, and ii has no pad neighbor. Then SS is closed under neighbors inside the connected group GG, so S=GS = G, and no cell of GG has a pad edge, which contradicts FG≠∅F_G \ne \emptyset (Lemma 2 needs a pad edge in GG). So for every uu, max⁡i∈Gf(i)≤max⁡q∈FGf(q)\max_{i \in G} f(i) \le \max_{q \in F_G} f(q). A point that satisfies this for every uu lies in the convex hull of FGF_G: otherwise a line strictly separates it from the hull, and the normal uu of that line breaks the inequality. □\square

Running time. Line L1 visits the pe(pe−1)/2p_e (p_e - 1)/2 pairs of each net, O(P+E)O(P + E) with a hash map for the weights. Line L2 makes the sparse rows in O(n+E)O(n + E), and line L3 is a graph search in O(n+E)O(n + E). Each step of the loop does one product AdA d in O(n+E)O(n + E) operations and a constant number of vector operations in O(n)O(n). By Theorem 2 there are at most nn steps per coordinate in exact arithmetic, so the total is O(P+E+n(n+E))O(P + E + n (n + E)) arithmetic operations, and the space is O(n+E)O(n + E) for AA and five vectors. With kk steps in floating point the loop costs O(k(n+E))O(k (n + E)).

Complexity

  • Building. Line L1 makes pe(pe−1)/2p_e (p_e - 1) / 2 pairs for a net of pep_e pins, so it costs O(P+E)O(P + E). The star model replaces each net by pep_e edges to a new free node, so E=O(P)E = O(P), at the price of one more variable per net.
  • One step. A product AdA d costs O(n+E)O(n + E), and the other lines of a step cost O(n)O(n).
  • Steps. In exact arithmetic at most nn steps, which gives O(n(n+E))O(n (n + E)). In floating point the number of steps kk to reduce the error in the AA norm by a factor ε\varepsilon is O(κlog⁡(1/ε))O(\sqrt{\kappa} \log(1/\varepsilon)) for the condition number κ\kappa of AA. With preconditioning placers need far fewer than nn steps; this is measured, not proved.
  • Space. The sparse rows of AA and the vectors: O(n+E)O(n + E).
  • The implementation uses exact Fractions by default. The bit size of the fractions can grow, so the real RAM count above is a count of arithmetic operations, not of bit operations.

Properties

What is proved. For a netlist in which every group of cells reaches a pad, the quadratic objective has one minimum, the linear system finds it, and the cells lie in the convex hull of the pads. With the clique weight 1/(p−1)1/(p - 1) a net of 2 pins counts as one squared length. No bound relates the HPWL of the quadratic minimum to the least HPWL, and the minimum is not legal.

What is measured. Quadratic placement with spreading (GORDIAN, FastPlace, Kraftwerk2, SimPL) was compared with other placers on the ISPD 2005 and 2006 placement contest benchmarks; see those papers for the numbers. The quadratic step alone gives a strongly overlapped placement, and published placers do not report it alone.

  • Convexity. The objective is convex, so the result does not depend on a start point or on the order of cells. Min-cut and annealing placers do not have this property.
  • Squares favor short wires. A wire of length 4 costs 16, four wires of length 1 cost 4. So the quadratic objective spreads the length over many wires, and it is not the same as HPWL even for 2-pin nets.
  • The two coordinates are independent. The xx and yy systems have the same matrix AA, and only bb differs.

Variants and improvements

  • Star model. Replace a net of pp pins by a star with a free center node. With the center weight p wp \, w the star has the same quadratic minimum as the clique of weight ww (see the clique net model), with pp edges instead of p(p−1)/2p (p - 1) / 2.
  • Bound to bound net model. Kraftwerk2 (Spindler, Schlichtmann and Johannes, 2008) joins the two extreme pins of a net of pp pins to each other and joins every inner pin to both of them, each edge with the weight 2(p−1)∣xi−xj∣\frac{2}{(p - 1) |x_i - x_j|} at the current distance. Each inner pin then adds 2p−1\frac{2}{p - 1} times the span of the net, and so does the edge between the extremes, so at the current placement the quadratic cost of the net in xx equals twice its span in xx. The weights change, so the system is solved again and again.
  • Linearization. Divide each weight by the current length ∣xi−xj∣|x_i - x_j| so that the squared cost behaves like a linear one near the current placement.
  • Spreading by partitioning. GORDIAN splits the region and the cells and adds a linear constraint that keeps the center of gravity of each part at the center of its region.
  • Spreading by forces or anchors. Force-directed placement in the Kraftwerk form adds constant spreading forces to bb; SimPL and FastPlace add pseudo nets from each cell to a spread position. Both keep the problem a positive definite system.
  • Eigenvector placement. With no pads, Hall minimized Φ\Phi under the condition ∑xi2=1\sum x_i^2 = 1; the minimum is an eigenvector of the Laplacian, the same idea as spectral partitioning.

When to use it

Use quadratic placement as the first step of global placement when the netlist is large and you need a good relative order of the cells fast. It is convex and solved by a sparse linear solve, so it scales to millions of cells and is stable under small changes of the netlist. It needs fixed pads or anchors, it does not model HPWL exactly, and it needs a spreading method. For the final wirelength, the nonlinear models of analytical placement, such as the log-sum-exp wirelength, are closer to HPWL. Min-cut placement is legal by construction but has no global view.

Pitfalls

  • No pads. A group of cells without a path to a pad makes AA singular, and conjugate gradients fail or drift. Check the condition, as line L3 does, or add a weak anchor to each free group.
  • Wrong clique weight. With weight 1 per pair, a large net pulls with p(p−1)/2p (p - 1) / 2 pairs and dominates the system. Use we/(p−1)w_e / (p - 1) or 2we/p2 w_e / p, and say which one.
  • Clique edges of large nets. A net with 1000 pins has about 500000 pairs. Use the star or the bound to bound model for large nets.
  • Reading the result as a placement. The minimum overlaps heavily. Its HPWL is not the HPWL of any legal placement, and must not be reported as one.
  • Floating point stop test. A test on the residual alone can stop too early on a badly conditioned system. Precondition, and check the result on a few cells.

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.

quadratic_placement.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/quadratic-placement/. The authors are listed in prov/01NV03.jsonl.

"""Quadratic placement with the clique net model, solved by conjugate gradients.

Pins 0 .. n-1 are the movable cells, and pins n, n+1, ... are the fixed pads.
Every pin sits at the center of its cell or pad (no pin offsets).
With Fraction input and tol = 0, the conjugate gradient method runs in exact
arithmetic and stops with a zero residual after at most n steps.
"""

from fractions import Fraction
from typing import Optional, Sequence

Number = Fraction | float


def clique_edges(nets: Sequence[Sequence[int]], weights: Optional[Sequence[Number]] = None) -> dict:
    """Two-pin edges of the clique model: each pair of a p-pin net gets w_e / (p - 1)."""
    edges: dict = {}
    for k, e in enumerate(nets):
        pins = sorted(set(e))
        p = len(pins)
        if p < 2:
            continue
        w = (Fraction(1) if weights is None else Fraction(weights[k])) / (p - 1)
        for a in range(p):
            for b in range(a + 1, p):
                key = (pins[a], pins[b])
                edges[key] = edges.get(key, 0) + w  # @line L1
    return edges


def build_system(n: int, nets, pads, weights=None):
    """Return (A, bx, by): A is a list of sparse rows {j: a_ij}, the Laplacian of the
    cell-to-cell edges plus a diagonal for the cell-to-pad edges; b holds w times the pad coordinate."""
    A = [dict() for _ in range(n)]  # @line L2
    bx = [Fraction(0)] * n
    by = [Fraction(0)] * n
    adj = [set() for _ in range(n)]
    anchored = [False] * n
    for (a, b), w in clique_edges(nets, weights).items():
        if b < n:  # a < b, so both are cells
            A[a][a] = A[a].get(a, 0) + w
            A[b][b] = A[b].get(b, 0) + w
            A[a][b] = A[a].get(b, 0) - w
            A[b][a] = A[b].get(a, 0) - w
            adj[a].add(b)
            adj[b].add(a)
        elif a < n:  # a is a cell, b is a pad
            qx, qy = pads[b - n]
            A[a][a] = A[a].get(a, 0) + w
            bx[a] += w * Fraction(qx)
            by[a] += w * Fraction(qy)
            anchored[a] = True
        # an edge between two pads adds a constant and is left out
    seen = [False] * n
    for s in range(n):
        if seen[s]:
            continue
        comp, stack = [], [s]
        seen[s] = True
        while stack:
            u = stack.pop()
            comp.append(u)
            for v in adj[u]:
                if not seen[v]:
                    seen[v] = True
                    stack.append(v)
        if not any(anchored[u] for u in comp):
            raise ValueError("a group of cells has no path to a pad, so the system is singular")  # @line L3
    return A, bx, by


def matvec(A, v):
    return [sum(a * v[j] for j, a in row.items()) for row in A]


def dot(u, v):
    return sum(a * b for a, b in zip(u, v))


def conjugate_gradient(A, b, tol: float = 0, max_iter: Optional[int] = None):
    """Solve A x = b for a symmetric positive definite A, from x = 0.
    Stops when |r|^2 <= tol^2 |b|^2. Returns (x, steps, list of |r|^2 after each step)."""
    n = len(b)
    if max_iter is None:
        max_iter = n if tol == 0 else 10 * n + 10
    zero = b[0] * 0 if n else 0
    x = [zero] * n  # @line L5
    r = list(b)
    p = list(r)
    rr = dot(r, r)
    limit = tol * tol * rr
    history = [rr]
    k = 0
    while rr > limit and k < max_iter:  # @line L6
        Ap = matvec(A, p)
        alpha = rr / dot(p, Ap)  # @line L7
        x = [xi + alpha * pi for xi, pi in zip(x, p)]  # @line L8
        r = [ri - alpha * qi for ri, qi in zip(r, Ap)]
        rr_new = dot(r, r)
        beta = rr_new / rr  # @line L9
        p = [ri + beta * pi for ri, pi in zip(r, p)]
        rr = rr_new
        history.append(rr)
        k += 1
    return x, k, history


def quadratic_placement(n: int, nets, pads, weights=None, exact: bool = True, tol: float = 1e-12):
    """Positions (x_i, y_i) of the n cells that minimize the clique-model quadratic wirelength.
    exact=True keeps Fractions and solves exactly; exact=False uses floats with tolerance tol."""
    A, bx, by = build_system(n, nets, pads, weights)
    if not exact:
        A = [{j: float(a) for j, a in row.items()} for row in A]
        bx = [float(v) for v in bx]
        by = [float(v) for v in by]
        t = tol
    else:
        t = 0
    x, _, _ = conjugate_gradient(A, bx, t)  # @line L4
    y, _, _ = conjugate_gradient(A, by, t)  # @line L10
    return list(zip(x, y))  # @line L11


def quadratic_wirelength(pos, n: int, nets, pads, weights=None):
    """Sum over the clique edges of w_ij ((x_i - x_j)^2 + (y_i - y_j)^2)."""
    pts = list(pos) + [(Fraction(a), Fraction(b)) for a, b in pads]
    total = 0
    for (a, b), w in clique_edges(nets, weights).items():
        total += w * ((pts[a][0] - pts[b][0]) ** 2 + (pts[a][1] - pts[b][1]) ** 2)
    return total


def hpwl(pos, n: int, nets, pads):
    """Total half-perimeter wirelength with every pin at its cell or pad center."""
    pts = list(pos) + [(Fraction(a), Fraction(b)) for a, b in pads]
    total = 0
    for e in nets:
        xs = [pts[p][0] for p in e]
        ys = [pts[p][1] for p in e]
        total += max(xs) - min(xs) + max(ys) - min(ys)
    return total
test_quadratic_placement.py 113 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/quadratic-placement/. The authors are listed in prov/01NV03.jsonl.

import random
from fractions import Fraction

import pytest

from quadratic_placement import (
    build_system,
    conjugate_gradient,
    hpwl,
    quadratic_placement,
    quadratic_wirelength,
)


def gauss_solve(M, b):
    """Reference: Gaussian elimination with Fractions on a dense copy."""
    n = len(b)
    a = [[Fraction(M[i].get(j, 0)) for j in range(n)] + [Fraction(b[i])] for i in range(n)]
    for c in range(n):
        piv = next(r for r in range(c, n) if a[r][c] != 0)
        a[c], a[piv] = a[piv], a[c]
        for r in range(n):
            if r != c and a[r][c] != 0:
                f = a[r][c] / a[c][c]
                a[r] = [x - f * y for x, y in zip(a[r], a[c])]
    return [a[i][n] / a[i][i] for i in range(n)]


def random_instance(rng, n, q, m):
    pads = [(rng.randint(0, 10), rng.randint(0, 10)) for _ in range(q)]
    nets = []
    for i in range(n):  # every cell gets a net to a pad or to an earlier cell, so all are anchored
        nets.append([i, n + rng.randrange(q)] if i == 0 or rng.random() < 0.3 else [i, rng.randrange(i)])
    for _ in range(m):
        k = min(rng.choice([2, 2, 3, 4]), n + q)
        nets.append(rng.sample(range(n + q), k))
    weights = [rng.randint(1, 3) for _ in nets]
    return nets, pads, weights


def test_chain_closed_form():
    # pads at x = 0 and x = L, cells 1 .. n in a chain: x_i = i L / (n + 1)
    for n in range(1, 9):
        L = 7
        nets = [[n, 0]] + [[i, i + 1] for i in range(n - 1)] + [[n - 1, n + 1]]
        pads = [(0, 0), (L, 0)]
        pos = quadratic_placement(n, nets, pads)
        assert [x for x, _ in pos] == [Fraction((i + 1) * L, n + 1) for i in range(n)]
        assert all(y == 0 for _, y in pos)


def test_exact_cg_matches_gaussian_elimination():
    rng = random.Random(2026)
    for _ in range(60):
        n = rng.randint(1, 7)
        nets, pads, weights = random_instance(rng, n, rng.randint(1, 3), rng.randint(0, 6))
        A, bx, by = build_system(n, nets, pads, weights)
        for b in (bx, by):
            x, steps, hist = conjugate_gradient(A, b)
            assert x == gauss_solve(A, b)
            assert steps <= n and hist[-1] == 0


def test_float_cg_close_to_exact():
    rng = random.Random(7)
    for _ in range(40):
        n = rng.randint(2, 12)
        nets, pads, weights = random_instance(rng, n, 2, rng.randint(0, 10))
        ex = quadratic_placement(n, nets, pads, weights)
        fl = quadratic_placement(n, nets, pads, weights, exact=False, tol=1e-13)
        for (a, b), (c, d) in zip(ex, fl):
            assert abs(float(a) - c) < 1e-8 and abs(float(b) - d) < 1e-8


def test_solution_is_the_minimum():
    rng = random.Random(11)
    for _ in range(40):
        n = rng.randint(1, 6)
        nets, pads, weights = random_instance(rng, n, 2, 4)
        pos = quadratic_placement(n, nets, pads, weights)
        best = quadratic_wirelength(pos, n, nets, pads, weights)
        for _ in range(10):
            i = rng.randrange(n)
            d = (Fraction(rng.randint(-5, 5), 7), Fraction(rng.randint(-5, 5), 7))
            moved = list(pos)
            moved[i] = (pos[i][0] + d[0], pos[i][1] + d[1])
            assert quadratic_wirelength(moved, n, nets, pads, weights) >= best


def test_example_of_the_page():
    # cells a, b, c, d = 0 .. 3; pads P = 4 at (0, 0) and Q = 5 at (6, 3)
    nets = [[4, 0], [0, 1], [0, 2], [1, 2, 3], [3, 5]]
    pads = [(0, 0), (6, 3)]
    pos = quadratic_placement(4, nets, pads)
    assert pos == [
        (Fraction(12, 7), Fraction(6, 7)),
        (Fraction(18, 7), Fraction(9, 7)),
        (Fraction(18, 7), Fraction(9, 7)),
        (Fraction(30, 7), Fraction(15, 7)),
    ]
    assert hpwl(pos, 4, nets, pads) == Fraction(72, 7)
    assert quadratic_wirelength(pos, 4, nets, pads) == Fraction(90, 7)
    A, bx, _ = build_system(4, nets, pads)
    _, steps, hist = conjugate_gradient(A, bx)
    assert steps == 3 and hist == [36, Fraction(9, 2), Fraction(144, 25), 0]


def test_unanchored_component_is_rejected():
    with pytest.raises(ValueError):
        build_system(3, [[0, 1], [2, 3]], [(0, 0)])

History

Hall (1970) placed the vertices of a weighted graph in rr dimensions by minimizing the weighted sum of squared distances under a normalization, and solved it with eigenvectors of the Laplacian. Tutte (1963) had used the same balance of springs with a fixed outer face to draw planar graphs (see the Tutte embedding). In chip placement, the system with fixed pads became the global step of placers in the late 1980s. GORDIAN (Kleinhans, Sigl and Johannes, ICCAD 1988; journal version with Antreich, 1991) alternated quadratic solves with partitioning. Later quadratic placers include Kraftwerk (Eisenmann and Johannes, 1998), FastPlace (Viswanathan and Chu, 2004) and SimPL (Kim, Lee and Markov, 2010 and 2012).

References

  1. Kenneth M. Hall, An r-dimensional quadratic placement algorithm, Management Science 17(3), 219 to 229, 1970, the sum of squared distances weighted by connections, and its minimum under a normalization by eigenvectors of the Laplacian (no fixed points)
  2. Jürgen M. Kleinhans, Georg Sigl, Frank M. Johannes and Kurt J. Antreich, GORDIAN: VLSI placement by quadratic programming and slicing optimization, IEEE Transactions on Computer-Aided Design of Integrated Circuits and Systems 10(3), 356 to 365, 1991, the global optimization by quadratic programs with unique minima, alternated with partitioning steps that add center of gravity constraints
  3. Magnus R. Hestenes and Eduard Stiefel, Methods of conjugate gradients for solving linear systems, Journal of Research of the National Bureau of Standards 49(6), 409 to 436, 1952, the method, and its exact termination in at most n steps for a positive definite system of order n
  4. 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 (quadratic placement, the clique and star net models and the linear system; general locator)
  5. Myung-Chul Kim, Dong-Jin Lee and Igor L. Markov, SimPL, an effective placement algorithm, IEEE Transactions on Computer-Aided Design of Integrated Circuits and Systems 31(1), 50 to 60, 2012, the quadratic lower-bound placement and its use inside a modern placer

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