Algorithm Search⌘K

Algorithmadvanced

Linear programming fill synthesis

Also called Kahng-Robins-Singh-Zelikovsky fill, LP-based dummy fill.

Kahng, Robins, Singh and Zelikovsky's fill method that solves a linear program over fixed dissections to minimize the largest window density variation.

Time
O(m^2 r^2) build
Space
O(m^4) extra
Where
m = the number of tiles on a side; r = the number of tiles on a side of a window
Properties
deterministicexactofflineiterative
Origin
Andrew B. Kahng, Gabriel Robins, Anish Singh, Alexander Zelikovsky, 1999

Linear programming fill synthesis solves the dummy fill problem on a fixed grid of tiles. Kahng, Robins, Singh and Zelikovsky observed that once the layout is cut into tiles and the windows are blocks of tiles, the density of a window is a sum of tile amounts, so the min-variation objective becomes a linear program with one fill variable per tile. The linear program gives the exact optimum for the tiled problem. A geometric lemma from their 1998 paper bounds how far the true sliding windows can then be from the tiled ones, which this page proves.

In plain words

The chip is cut into a grid of equal tiles, and a window is a square block of tiles. For each tile we know how much metal it already has and how much free space can take fill.

We choose how much fill to put in each tile. A window's metal is the sum over its tiles, so every rule is a sum: no window may go above the upper limit, and we want the emptiest window as full as possible.

Such a set of sums and limits is a linear program, and a standard solver finds the best amounts exactly. Then fill shapes are drawn in each tile to match its amount.

Windows that slide between grid lines are not checked, but their density can differ only by a known small amount, which shrinks as the tiles get finer.

The problem

Input. An m×mm \times m grid of tiles TijT_{ij} of side tt, with the feature area aij=area⁡(F∩Tij)a_{ij} = \operatorname{area}(F \cap T_{ij}) and the slack sijs_{ij}, the area in TijT_{ij} where fill may go. An integer r≥1r \ge 1; the windows are the (m−r+1)2(m - r + 1)^2 blocks WW of r×rr \times r tiles, of side w=rtw = rt and area w2w^2. An upper density bound UU.

Assumption. Any amount pij∈[0,sij]p_{ij} \in [0, s_{ij}] of fill can be drawn in the slack of TijT_{ij}. This is the continuous model; it holds approximately when fill shapes are small against the tile.

Output. Fill amounts pijp_{ij} that maximize the minimum window density

min⁡W1w2∑Tij⊆W(aij+pij)subject to0≤pij≤sij,1w2∑Tij⊆W(aij+pij)≤U for every W,\min_W \frac{1}{w^2} \sum_{T_{ij} \subseteq W} (a_{ij} + p_{ij}) \quad \text{subject to} \quad 0 \le p_{ij} \le s_{ij}, \qquad \frac{1}{w^2} \sum_{T_{ij} \subseteq W} (a_{ij} + p_{ij}) \le U \text{ for every } W,

or a report that no fill meets the upper bound.

The algorithm

Write a(W)=∑Tij⊆Waija(W) = \sum_{T_{ij} \subseteq W} a_{ij} and p(W)=∑Tij⊆Wpijp(W) = \sum_{T_{ij} \subseteq W} p_{ij}. The variable MM stands for the area of the emptiest window.

  1. LP-DENSITY-FILL(a, s, r, U, w)
  2. 1if a(W) > U·w² for some window W then return infeasible
  3. 2variables: p_ij for every tile, and M
  4. 3objective: maximize M
  5. 4for every tile T_ij: p_ij ≤ s_ij
  6. 5for every window W: p(W) ≤ U·w² − a(W)
  7. 6for every window W: M − p(W) ≤ a(W)
  8. 7solve with the simplex method from the origin (all p_ij = 0, M = 0)
  9. 8return M / w², and the amounts p_ij

All variables are nonnegative. Line L1 makes every right-hand side nonnegative, so the origin is a feasible start and the simplex method needs no first phase. Line L6 says M≤a(W)+p(W)M \le a(W) + p(W), so at the optimum MM equals the smallest window area. After line L8, fill shapes of total area pijp_{ij} are drawn in the slack of each tile, for example as a regular array of squares.

The implementation is a dense simplex method in exact rational arithmetic with Bland's rule, which prevents cycling. It also returns the dual solution, so the tests can check strong duality as a certificate of optimality without trusting the pivots.

Example

Take a 3×33 \times 3 grid of unit tiles, windows of 2×22 \times 2 tiles (r=2r = 2, w=2w = 2, w2=4w^2 = 4) and U=12U = \frac{1}{2}. Rows are listed from the top:

feature area aija_{ij} slack sijs_{ij}
row 0 0.6, 0.2, 0.1 0.1, 0.4, 0.5
row 1 0.5, 0.3, 0.0 0.2, 0.3, 0.6
row 2 0.4, 0.1, 0.0 0.3, 0.5, 0.2

There are four windows. Name them by their top-left tile: W00W_{00}, W01W_{01}, W10W_{10} and W11W_{11}. Their feature areas are 1.61.6, 0.60.6, 1.31.3 and 0.40.4, densities 0.40.4, 0.150.15, 0.3250.325 and 0.10.1. The upper bound allows each window an area of 22.

The solver returns M/w2=1940=0.475M / w^2 = \frac{19}{40} = 0.475. One optimal fill, row by row, is (0,0.1,0.3)(0, 0.1, 0.3), (0,0.3,0.6)(0, 0.3, 0.6), (0,0.4,0.2)(0, 0.4, 0.2), which gives window densities 0.50.5, 0.4750.475, 0.50.5 and 0.4750.475.

Why not 0.50.5? Window W11W_{11} has feature area 0.40.4 and needs fill M−0.4M - 0.4 from tiles (1,1)(1,1), (1,2)(1,2), (2,1)(2,1) and (2,2)(2,2). Tiles (1,2)(1,2) and (2,2)(2,2) give at most 0.6+0.20.6 + 0.2, so p11+p21≥M−1.2p_{11} + p_{21} \ge M - 1.2. But tiles (1,1)(1,1) and (2,1)(2,1) also lie in W10W_{10}, which has room for only 2−1.3=0.72 - 1.3 = 0.7 more, so p11+p21≤0.7p_{11} + p_{21} \le 0.7. Hence M≤1.9M \le 1.9 and M/w2≤0.475M / w^2 \le 0.475. This chain of inequalities is a dual solution of the linear program, and it is what the dual certificate in the tests checks in general.

With U=0.3U = 0.3 line L1 reports infeasible, since W00W_{00} already has density 0.40.4.

Correctness

The full proof shows the following.

The linear program is the tiled problem. Every feasible fill gives a feasible point (p,M)(p, M) with MM the smallest window area, and every feasible point gives a feasible fill whose smallest window area is at least MM. So the optimum of the linear program, divided by w2w^2, is the best minimum density on the fixed dissection, and the optimal pp is an optimal fill. The program is feasible after line L1 and bounded, so the simplex method returns an optimum.

Fixed windows against floating windows. If every window of the fixed rr-dissection has density in [L,U][L, U], then every w×ww \times w window, at any position, has density in [L−εr,U+εr][L - \varepsilon_r, U + \varepsilon_r] with

εr=1r−14r2.\varepsilon_r = \frac{1}{r} - \frac{1}{4r^2}.

The proof moves a floating window to the nearest fixed window, which is at most t/2t/2 away in each coordinate, and bounds the area they do not share. This is Theorem 8 of Kahng et al. (1998). A square of features placed at offset (t/2,t/2)(t/2, t/2) shows the bound is attained.

What the fill achieves for floating windows. The fixed problem is a relaxation of the floating one, so its optimum M∗M^* is at least the best floating minimum. With the LP fill, every floating window has density at least M∗/w2−εrM^*/w^2 - \varepsilon_r and at most U+εrU + \varepsilon_r. So the LP fill is within εr\varepsilon_r of the floating optimum, and it exceeds the floating upper bound by at most εr\varepsilon_r.

What is not proved here. The correctness and termination of the simplex method with Bland's rule are cited from the simplex method page; the tests confirm each returned optimum with a dual certificate. The claim that the slack can be filled by any amount is a modeling assumption, not a theorem.

Proof: The fixed-dissection linear program gives min-variation fill, and fixed windows bound floating windowsfull

Setting. The layout is R=[0,n]2R = [0, n]^2 with features FF, a finite union of rectangles. A tile side t>0t > 0 divides nn, so RR is cut into an m×mm \times m grid of tiles TijT_{ij} with m=n/tm = n/t. For an integer r≥1r \ge 1 with rt≤nrt \le n, let w=rtw = rt. A fixed window is a block of r×rr \times r tiles; a floating window is any square x+[0,w]2⊆Rx + [0, w]^2 \subseteq R. Tile TijT_{ij} has feature area aija_{ij} and slack sij≥0s_{ij} \ge 0. For a fill amount p=(pij)p = (p_{ij}) and a fixed window WW, write a(W)=∑Tij⊆Waija(W) = \sum_{T_{ij} \subseteq W} a_{ij}, p(W)=∑Tij⊆Wpijp(W) = \sum_{T_{ij} \subseteq W} p_{ij}, and Dp(W)=(a(W)+p(W))/w2D_p(W) = (a(W) + p(W))/w^2.

Continuous model. A fill is a choice of pij∈[0,sij]p_{ij} \in [0, s_{ij}] for every tile, and its fill shapes in TijT_{ij} have total area pijp_{ij} and lie in TijT_{ij}. The fixed problem is: maximize min⁡WDp(W)\min_W D_p(W) over fills with max⁡WDp(W)≤U\max_W D_p(W) \le U, the minimum and maximum over fixed windows.

Lemma 1 (density of a fixed window). For any fill, the density of a fixed window WW is Dp(W)D_p(W).

Proof. WW is the union of its r2r^2 tiles, which meet only on their boundaries, of area zero. Fill shapes in a tile lie in that tile and do not overlap features, since they lie in the slack. So the area of features and fill in WW is ∑Tij⊆W(aij+pij)=a(W)+p(W)\sum_{T_{ij} \subseteq W} (a_{ij} + p_{ij}) = a(W) + p(W). □\square

Theorem 1 (the linear program is the fixed problem). Consider the program of lines L3 to L6: variables pij≥0p_{ij} \ge 0 and M≥0M \ge 0, maximize MM subject to pij≤sijp_{ij} \le s_{ij}, p(W)≤Uw2−a(W)p(W) \le U w^2 - a(W) and M−p(W)≤a(W)M - p(W) \le a(W) for every fixed window WW. If a(W)≤Uw2a(W) \le U w^2 for every WW, the program has an optimal solution (p∗,M∗)(p^*, M^*), the optimum of the fixed problem is M∗/w2M^*/w^2, and p∗p^* is an optimal fill. If a(W)>Uw2a(W) > U w^2 for some WW, the fixed problem has no feasible fill.

Proof. Infeasible case: every fill has p(W)≥0p(W) \ge 0, so Dp(W)≥a(W)/w2>UD_p(W) \ge a(W)/w^2 > U.

Feasible case. Feasibility. The origin p=0p = 0, M=0M = 0 satisfies all constraints, since the right-hand sides sijs_{ij}, Uw2−a(W)U w^2 - a(W) and a(W)a(W) are all nonnegative. Boundedness. For any window W0W_0, M≤a(W0)+p(W0)≤a(W0)+∑sijM \le a(W_0) + p(W_0) \le a(W_0) + \sum s_{ij}. A feasible bounded linear program has an optimal solution, by the fundamental theorem of linear programming.

From fills to program points. Let pp be a fill feasible for the fixed problem and let M=min⁡W(a(W)+p(W))M = \min_W (a(W) + p(W)). Then 0≤pij≤sij0 \le p_{ij} \le s_{ij}, a(W)+p(W)≤Uw2a(W) + p(W) \le U w^2 by Lemma 1, and M≤a(W)+p(W)M \le a(W) + p(W) for every WW, with M≥0M \ge 0. So (p,M)(p, M) is feasible with objective w2min⁡WDp(W)w^2 \min_W D_p(W). Hence the program optimum M∗M^* is at least w2w^2 times the fixed optimum.

From program points to fills. Let (p,M)(p, M) be feasible. Then pp is a fill with Dp(W)≤UD_p(W) \le U for all WW, and M≤a(W)+p(W)M \le a(W) + p(W) for all WW gives min⁡WDp(W)≥M/w2\min_W D_p(W) \ge M/w^2. So the fixed optimum is at least M∗/w2M^*/w^2, and p∗p^* attains it. □\square

Lemma 2 (overlap of shifted squares). Let Q=[x,x+w]×[y,y+w]Q = [x, x + w] \times [y, y + w] and Q′=[x′,x′+w]×[y′,y′+w]Q' = [x', x' + w] \times [y', y' + w] with ∣x−x′∣≤δ|x - x'| \le \delta and ∣y−y′∣≤δ|y - y'| \le \delta, where 0≤δ≤w0 \le \delta \le w. Then area⁡(Q∖Q′)=area⁡(Q′∖Q)≤w2−(w−δ)2\operatorname{area}(Q \setminus Q') = \operatorname{area}(Q' \setminus Q) \le w^2 - (w - \delta)^2.

Proof. Q∩Q′Q \cap Q' is the rectangle of sides w−∣x−x′∣w - |x - x'| and w−∣y−y′∣w - |y - y'|, both at least w−δ≥0w - \delta \ge 0. So area⁡(Q∩Q′)≥(w−δ)2\operatorname{area}(Q \cap Q') \ge (w - \delta)^2, and both differences have area w2−area⁡(Q∩Q′)w^2 - \operatorname{area}(Q \cap Q'). □\square

Theorem 2 (floating windows, Kahng et al. 1998, Theorem 8). Let G⊆RG \subseteq R be any measurable set (features and fill together), and suppose every fixed window WW has area⁡(G∩W)/w2∈[L,U]\operatorname{area}(G \cap W)/w^2 \in [L, U]. Then every floating window QQ has

L−εr≤area⁡(G∩Q)w2≤U+εr,εr=1r−14r2.L - \varepsilon_r \le \frac{\operatorname{area}(G \cap Q)}{w^2} \le U + \varepsilon_r, \qquad \varepsilon_r = \frac{1}{r} - \frac{1}{4r^2}.

Proof. Let Q=(x,y)+[0,w]2⊆RQ = (x, y) + [0, w]^2 \subseteq R, so x,y∈[0,n−w]x, y \in [0, n - w]. Let x′x' be a multiple of tt nearest to xx, and y′y' likewise. Since 00 and n−w=(m−r)tn - w = (m - r)t are multiples of tt, the rounding stays in [0,n−w][0, n - w], so Q′=(x′,y′)+[0,w]2Q' = (x', y') + [0, w]^2 is a fixed window, and ∣x−x′∣,∣y−y′∣≤t/2|x - x'|, |y - y'| \le t/2. By Lemma 2 with δ=t/2=w/(2r)\delta = t/2 = w/(2r),

area⁡(Q∖Q′)≤w2−(w−w2r)2=w2(1r−14r2)=w2εr.\operatorname{area}(Q \setminus Q') \le w^2 - \Big(w - \frac{w}{2r}\Big)^2 = w^2 \Big(\frac{1}{r} - \frac{1}{4r^2}\Big) = w^2 \varepsilon_r.

Then area⁡(G∩Q)≤area⁡(G∩Q′)+area⁡(Q∖Q′)≤Uw2+εrw2\operatorname{area}(G \cap Q) \le \operatorname{area}(G \cap Q') + \operatorname{area}(Q \setminus Q') \le U w^2 + \varepsilon_r w^2, and area⁡(G∩Q)≥area⁡(G∩Q′)−area⁡(Q′∖Q)≥Lw2−εrw2\operatorname{area}(G \cap Q) \ge \operatorname{area}(G \cap Q') - \operatorname{area}(Q' \setminus Q) \ge L w^2 - \varepsilon_r w^2. Divide by w2w^2. □\square

Proposition 3 (the bounds are attained). Suppose n≥w+tn \ge w + t. Let G=(t/2,t/2)+[0,w]2G = (t/2, t/2) + [0, w]^2. The floating window GG has density 11, and every fixed window has density at most (1−12r)2=1−εr(1 - \frac{1}{2r})^2 = 1 - \varepsilon_r. For the complement R∖GR \setminus G, the window GG has density 00 and every fixed window has density at least εr\varepsilon_r.

Proof. A fixed window Q′=(it,jt)+[0,w]2Q' = (it, jt) + [0, w]^2 meets GG in a rectangle whose sides are w−∣it−t/2∣w - |it - t/2| and w−∣jt−t/2∣w - |jt - t/2| (or zero). Since ii is an integer, ∣it−t/2∣≥t/2|it - t/2| \ge t/2, so each side is at most w−t/2w - t/2, and the density is at most (w−t/2)2/w2=(1−12r)2(w - t/2)^2/w^2 = (1 - \frac{1}{2r})^2. For i=j=0i = j = 0 the bound holds with equality. For the complement, the density of each fixed window is 11 minus its density for GG, so it is at least 1−(1−12r)2=εr1 - (1 - \frac{1}{2r})^2 = \varepsilon_r. □\square

So with U=1−εrU = 1 - \varepsilon_r the upper bound of Theorem 2 is reached, and with L=εrL = \varepsilon_r the lower bound is. Kahng et al. state that the bounds are tight; this proposition shows it for one value of UU and one of LL for every rr.

Corollary 4 (quality of the LP fill for floating windows). Let M∗M^* be the program optimum and p∗p^* the LP fill. Let OPT\mathrm{OPT} be the largest minimum floating-window density over fills with every floating-window density at most UU. Then with p∗p^* every floating window has density in [M∗/w2−εr,U+εr][M^*/w^2 - \varepsilon_r, U + \varepsilon_r], and M∗/w2≥OPTM^*/w^2 \ge \mathrm{OPT}.

Proof. With p∗p^*, every fixed window has density in [M∗/w2,U][M^*/w^2, U] by Theorem 1, and Theorem 2 gives the first claim. Fixed windows are floating windows, so a fill that meets UU on all floating windows meets it on all fixed windows, and its minimum over fixed windows is at least its minimum over floating windows. So it is feasible for the fixed problem with value at least its floating value, and Theorem 1 gives M∗/w2≥OPTM^*/w^2 \ge \mathrm{OPT}. □\square

So the LP fill reaches a floating minimum within εr\varepsilon_r of the floating optimum, and exceeds the floating bound UU by at most εr\varepsilon_r. Running the program with U−εrU - \varepsilon_r in place of UU removes the excess, at the cost of a lower optimum.

About the solver. Line L7 uses the simplex method with Bland's rule, which terminates with an optimal basic solution on a feasible bounded program (Bland, 1977); this is cited, not proved here. The implementation also returns the dual vector yy from the final tableau. For any x≥0x \ge 0 with Ax≤bAx \le b and y≥0y \ge 0 with ATy≥cA^{\mathsf T} y \ge c, weak duality gives cTx≤yTAx≤yTbc^{\mathsf T} x \le y^{\mathsf T} A x \le y^{\mathsf T} b, so equality cTx=bTyc^{\mathsf T} x = b^{\mathsf T} y proves that xx is optimal. The tests check exactly these conditions in exact arithmetic, so each tested optimum is certified independently of the pivoting.

Complexity

The program has m2+1m^2 + 1 variables and m2+2(m−r+1)2m^2 + 2(m - r + 1)^2 constraints. Each window constraint has r2+1r^2 + 1 nonzero entries, so building it costs O(m2r2)O(m^2 r^2). A dense tableau has O(m4)O(m^4) entries.

The time to solve depends on the solver. The simplex method takes few pivots in practice but an exponential number on some inputs. Interior point methods such as Karmarkar's algorithm solve it in time polynomial in its size and the bit length of the data. On the test instances, with up to m=6m = 6, the exact solver takes well under a second.

The size grows with r2r^2 for a fixed window: halving εr\varepsilon_r needs about twice the rr and four times the variables. For large layouts this growth is the reason for the Monte Carlo, greedy and hierarchical methods below, which Kahng and Samadi survey; they note that the Monte Carlo and greedy methods can end with a minimum density well below the optimum.

Properties

  • Exact for the tiled problem. With rational data the implementation returns the exact optimum and an optimal dual, so the result is certified.
  • Not unique. Many fills reach the optimum. In the example, any fill within the slacks that keeps every window area between 1.91.9 and 22 is optimal.
  • Ignores coupling. The objective sees only density. Where fill goes inside a tile, and how it couples to signal wires, is left to the placement step.
  • Error from the grid. Densities of floating windows can differ from the fixed ones by up to εr\varepsilon_r, which is 0.750.75, 0.43750.4375, 0.2340.234 and 0.0610.061 for r=1r = 1, 22, 44 and 1616.

Variants and improvements

  • Min-Fill. Minimize ∑pij\sum p_{ij} subject to Lw2≤a(W)+p(W)≤Uw2L w^2 \le a(W) + p(W) \le U w^2 for every window. Kahng and Samadi credit this linear program to Tian et al.
  • Variation budget. Given a target density, minimize a budget ε\varepsilon such that every window lies within ε/2\varepsilon/2 of the target, again a linear program (Tian et al., as surveyed by Kahng and Samadi).
  • Integer fill. When fill comes in fixed squares, the amounts are integers and the problem is an integer program. Rounding the LP amounts down keeps every upper bound and loses less than one square per tile, so less than r2r^2 squares per window.
  • Monte Carlo and greedy. Chen, Kahng, Robins and Zelikovsky (ASP-DAC 2000) add fill one unit at a time to a tile chosen at random with priority proportional to UU minus the smallest density of the windows that contain it, or to the tile of highest priority. These scale far better and give no optimality guarantee.
  • Model-based. Replace window density by an effective density, a weighted sum over nearby tiles. The constraints stay linear, so the method still applies.

When to use it

Use it when the grid is small enough for an LP solver, for example inside one block or as the exact core of a hierarchical method, and the density rule is the target. Use Monte Carlo or greedy fill for full chips, and a performance-aware method when the added coupling capacitance on critical nets matters.

Pitfalls

  • Coarse grid. With r=1r = 1 the fixed windows can all meet the rule while a sliding window has density 34\frac{3}{4} higher. Choose rr so that εr\varepsilon_r is below the tolerance, or tighten UU by εr\varepsilon_r.
  • Slack is not free area. The slack must exclude the buffer around signal wires and the space lost to fill design rules, or the amounts cannot be drawn.
  • Windows at the edge. The grid must cover the layout so that every window lies inside; partial windows at the edge need their own rule.
  • Infeasible inputs. If a window already exceeds UU, no fill helps; the layout must change or wide wires must be slotted.

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.

lp_density_fill.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lp-density-fill/. The authors are listed in prov/6QQEE4.jsonl.
"""Min-variation dummy fill on a fixed r-dissection, solved exactly as a linear program.

The layout is cut into an m by m grid of tiles. area[i][j] is the feature area in tile
(i, j) and slack[i][j] is the area in which fill may go. A window is an r by r block of
tiles, of area w2. The linear program is

    maximize M
    subject to  0 <= p[i][j] <= slack[i][j]                      for every tile,
                sum over W of p <= U * w2 - area(W)              for every window W,
                M - sum over W of p <= area(W)                   for every window W.

It is solved by a dense simplex method in exact rational arithmetic with Bland's rule.
All inputs may be ints or Fractions; outputs are Fractions.
"""

from fractions import Fraction


def windows(m, r):
    """The top-left tiles of all r by r blocks of an m by m grid."""
    return [(i, j) for i in range(m - r + 1) for j in range(m - r + 1)]


def window_tiles(i0, j0, r):
    return [(i, j) for i in range(i0, i0 + r) for j in range(j0, j0 + r)]


def simplex_max(c, A, b):
    """Maximize c.x subject to A x <= b and x >= 0, where every b_i >= 0.

    The origin is feasible, so the slack basis starts the method. Bland's rule
    (smallest index enters, smallest basic index leaves among ties) prevents cycling.
    Returns (value, x, y) where y is an optimal dual solution, or None if unbounded.
    """
    n, k = len(c), len(A)
    width = n + k + 1
    rows = []
    for i in range(k):
        row = [Fraction(v) for v in A[i]] + [Fraction(0)] * k + [Fraction(b[i])]
        row[n + i] = Fraction(1)
        rows.append(row)
    obj = [-Fraction(v) for v in c] + [Fraction(0)] * (k + 1)
    basis = [n + i for i in range(k)]
    while True:
        enter = next((j for j in range(n + k) if obj[j] < 0), None)
        if enter is None:
            break
        leave, best = None, None
        for i in range(k):
            a = rows[i][enter]
            if a > 0:
                ratio = rows[i][-1] / a
                if best is None or ratio < best or (ratio == best and basis[i] < basis[leave]):
                    leave, best = i, ratio
        if leave is None:
            return None
        piv = rows[leave]
        a = piv[enter]
        piv = [v / a for v in piv]
        rows[leave] = piv
        nz = [j for j in range(width) if piv[j] != 0]
        for i in range(k):
            if i != leave and rows[i][enter] != 0:
                f = rows[i][enter]
                row = rows[i]
                for j in nz:
                    row[j] -= f * piv[j]
        f = obj[enter]
        for j in nz:
            obj[j] -= f * piv[j]
        basis[leave] = enter
    x = [Fraction(0)] * n
    for i, v in enumerate(basis):
        if v < n:
            x[v] = rows[i][-1]
    y = [obj[n + i] for i in range(k)]
    return obj[-1], x, y


def build_lp(area, slack, r, U, w2):
    """The constraint matrix of the Min-Var program; variables are the tiles row by row, then M."""
    m = len(area)
    n = m * m + 1
    A, b = [], []
    for i in range(m):
        for j in range(m):
            row = [0] * n
            row[i * m + j] = 1
            A.append(row)
            b.append(Fraction(slack[i][j]))  # @line L4
    wins = windows(m, r)
    for i0, j0 in wins:
        tiles = window_tiles(i0, j0, r)
        feat = sum(Fraction(area[i][j]) for i, j in tiles)
        row = [0] * n
        for i, j in tiles:
            row[i * m + j] = 1
        A.append(row)
        b.append(Fraction(U) * w2 - feat)  # @line L5
    for i0, j0 in wins:
        tiles = window_tiles(i0, j0, r)
        feat = sum(Fraction(area[i][j]) for i, j in tiles)
        row = [0] * n
        for i, j in tiles:
            row[i * m + j] = -1
        row[-1] = 1
        A.append(row)
        b.append(feat)  # @line L6
    c = [0] * (n - 1) + [1]  # @line L3
    return c, A, b


def lp_density_fill(area, slack, r, U, w2):
    """Optimal min-variation fill on the fixed r-dissection.

    Returns (density, p) where density is the largest possible minimum window
    density and p[i][j] the fill area of each tile, or None if some window already
    has feature density above U.
    """
    m = len(area)
    for i0, j0 in windows(m, r):
        if sum(Fraction(area[i][j]) for i, j in window_tiles(i0, j0, r)) > Fraction(U) * w2:  # @line L1
            return None
    c, A, b = build_lp(area, slack, r, U, w2)  # @line L2
    value, x, _ = simplex_max(c, A, b)  # @line L7
    p = [[x[i * m + j] for j in range(m)] for i in range(m)]
    return value / Fraction(w2), p  # @line L8


def window_densities(area, p, r, w2):
    """The density of every fixed window under fill p."""
    m = len(area)
    return [sum(Fraction(area[i][j]) + p[i][j] for i, j in window_tiles(i0, j0, r)) / Fraction(w2) for i0, j0 in windows(m, r)]


def floating_error(r):
    """The largest density difference between a floating window and every fixed window (Theorem 8)."""
    return Fraction(1, r) - Fraction(1, 4 * r * r)
test_lp_density_fill.py 216 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lp-density-fill/. The authors are listed in prov/6QQEE4.jsonl.

import itertools
import random
from fractions import Fraction

from lp_density_fill import (
    build_lp,
    floating_error,
    lp_density_fill,
    simplex_max,
    window_densities,
    window_tiles,
    windows,
)


def random_instance(rng, m, tile_area, denom):
    """Feature area and slack per tile, with area + slack <= tile area."""
    area, slack = [], []
    for i in range(m):
        ra, rs = [], []
        for j in range(m):
            a = Fraction(rng.randint(0, denom), denom) * tile_area
            s = Fraction(rng.randint(0, denom), denom) * (tile_area - a)
            ra.append(a)
            rs.append(s)
        area.append(ra)
        slack.append(rs)
    return area, slack


def solve_linear(M, v):
    """Solve M x = v exactly; None if M is singular."""
    n = len(M)
    a = [list(map(Fraction, row)) + [Fraction(v[i])] for i, row in enumerate(M)]
    for col in range(n):
        piv = next((i for i in range(col, n) if a[i][col] != 0), None)
        if piv is None:
            return None
        a[col], a[piv] = a[piv], a[col]
        for i in range(n):
            if i != col and a[i][col] != 0:
                f = a[i][col] / a[col][col]
                a[i] = [x - f * y for x, y in zip(a[i], a[col])]
    return [a[i][n] / a[i][i] for i in range(n)]


def vertex_enumeration(c, A, b):
    """Maximum of c.x over {A x <= b, x >= 0} by trying every basis of tight constraints."""
    n = len(c)
    rows = [(list(A[i]), Fraction(b[i])) for i in range(len(A))]
    rows += [([-1 if k == j else 0 for k in range(n)], Fraction(0)) for j in range(n)]
    best = None
    for subset in itertools.combinations(range(len(rows)), n):
        x = solve_linear([rows[i][0] for i in subset], [rows[i][1] for i in subset])
        if x is None:
            continue
        if all(sum(g * xi for g, xi in zip(row, x)) <= h for row, h in rows):
            val = sum(ci * xi for ci, xi in zip(c, x))
            if best is None or val > best:
                best = val
    return best


def feasible(area, slack, p, r, U, w2):
    m = len(area)
    if any(not (0 <= p[i][j] <= slack[i][j]) for i in range(m) for j in range(m)):
        return False
    return max(window_densities(area, p, r, w2)) <= U


def test_one_tile_windows_closed_form():
    # With r = 1 every tile is a window, so each tile is filled as far as its slack and U allow.
    rng = random.Random(1)
    for trial in range(20):
        area, slack = random_instance(rng, 4, 9, 9)
        U = Fraction(rng.randint(5, 9), 9)
        if trial % 4:
            U = max(U, max(a for row in area for a in row) / 9)
        if any(a > 9 * U for row in area for a in row):
            assert lp_density_fill(area, slack, 1, U, 9) is None
            continue
        d, p = lp_density_fill(area, slack, 1, U, 9)
        expected = min(a + min(s, 9 * U - a) for ra, rs in zip(area, slack) for a, s in zip(ra, rs)) / 9
        assert d == expected
        assert feasible(area, slack, p, 1, U, 9)
        assert min(window_densities(area, p, 1, 9)) == d


def test_matches_vertex_enumeration():
    rng = random.Random(2)
    for trial in range(12):
        r = 1 + trial % 2
        area, slack = random_instance(rng, 2, 4, 8)
        U = Fraction(rng.randint(4, 8), 8)
        if lp_density_fill(area, slack, r, U, 4 * r * r) is None:
            continue
        c, A, b = build_lp(area, slack, r, U, 4 * r * r)
        value, x, _ = simplex_max(c, A, b)
        assert value == vertex_enumeration(c, A, b)


def test_dual_certificate_on_larger_grids():
    # A feasible x, a feasible dual y and equal objective values prove optimality,
    # independent of the pivoting that produced them.
    rng = random.Random(3)
    for m, r in [(5, 2), (5, 3), (6, 2)]:
        area, slack = random_instance(rng, m, 1, 10)
        U = Fraction(3, 4)
        w2 = r * r
        if lp_density_fill(area, slack, r, U, w2) is None:
            U = Fraction(1)
        c, A, b = build_lp(area, slack, r, U, w2)
        value, x, y = simplex_max(c, A, b)
        assert all(v >= 0 for v in x) and all(v >= 0 for v in y)
        for row, bi in zip(A, b):
            assert sum(a * v for a, v in zip(row, x)) <= bi
        for j in range(len(c)):
            assert sum(A[i][j] * y[i] for i in range(len(A))) >= c[j]
        assert sum(bi * yi for bi, yi in zip(b, y)) == value == sum(ci * xi for ci, xi in zip(c, x))
        d, p = lp_density_fill(area, slack, r, U, w2)
        assert feasible(area, slack, p, r, U, w2)
        assert min(window_densities(area, p, r, w2)) == d


def test_integer_fills_bracket_the_lp():
    # Brute force over integer fill amounts. The integer optimum is at most the LP
    # optimum, and rounding the LP fill down loses less than one unit per tile.
    rng = random.Random(4)
    for trial in range(6):
        m, r = 3, 2
        area = [[rng.randint(0, 3) for _ in range(m)] for _ in range(m)]
        slack = [[rng.randint(0, min(2, 4 - area[i][j])) for j in range(m)] for i in range(m)]
        U = Fraction(rng.randint(10, 14), 16)
        w2 = 16
        res = lp_density_fill(area, slack, r, U, w2)
        if res is None:
            continue
        d, p = res
        best = None
        for fill in itertools.product(*[range(slack[i][j] + 1) for i in range(m) for j in range(m)]):
            q = [[Fraction(fill[i * m + j]) for j in range(m)] for i in range(m)]
            dens = window_densities(area, q, r, w2)
            if max(dens) <= U and (best is None or min(dens) > best):
                best = min(dens)
        assert best <= d
        assert d - best < Fraction(r * r, w2)
        down = [[Fraction(int(v)) for v in row] for row in p]
        assert feasible(area, slack, down, r, U, w2)


def overlap(cell, x, y, w):
    cx, cy, h = cell
    dx = min(cx + h, x + w) - max(cx, x)
    dy = min(cy + h, y + w) - max(cy, y)
    return dx * dy if dx > 0 and dy > 0 else 0


def density(cells, x, y, w):
    return sum(overlap(c, x, y, w) for c in cells) / Fraction(w * w)


def test_floating_windows_within_fixed_bound():
    rng = random.Random(5)
    n, w = 8, 4
    h = Fraction(1, 2)
    for r in [1, 2, 4]:
        t = Fraction(w, r)
        cells = [(i * h, j * h, h) for i in range(16) for j in range(16) if rng.random() < 0.3]
        grid = [k * t for k in range(int((n - w) / t) + 1)]
        fixed = [density(cells, x, y, w) for x in grid for y in grid]
        lo, hi = min(fixed), max(fixed)
        e = floating_error(r)
        offsets = [Fraction(k, 4) for k in range(0, 17, 2)] + [Fraction(rng.randint(0, 400), 100) for _ in range(5)]
        for x in offsets:
            for y in offsets:
                d = density(cells, x, y, w)
                assert lo - e <= d <= hi + e


def test_floating_bound_is_attained():
    # Features fill the window at offset (t/2, t/2): every fixed window has density at
    # most (1 - 1/(2r))^2, while that floating window has density 1. The complement
    # layout attains the lower bound.
    for r in [1, 2, 3, 4]:
        w = 2 * r
        t = Fraction(w, r)
        n = 2 * w
        square = [(t / 2 + i, t / 2 + j, 1) for i in range(w) for j in range(w)]
        grid = [k * t for k in range(int((n - w) / t) + 1)]
        fixed = [density(square, x, y, w) for x in grid for y in grid]
        assert max(fixed) + floating_error(r) == 1 == density(square, t / 2, t / 2, w)
        half = [(i * Fraction(1, 2), j * Fraction(1, 2), Fraction(1, 2)) for i in range(2 * n) for j in range(2 * n)]
        hole = [c for c in half if overlap(c, t / 2, t / 2, w) == 0]
        fixed = [density(hole, x, y, w) for x in grid for y in grid]
        assert min(fixed) - floating_error(r) == 0 == density(hole, t / 2, t / 2, w)


def test_page_example():
    area = [[Fraction(k, 10) for k in row] for row in [[6, 2, 1], [5, 3, 0], [4, 1, 0]]]
    slack = [[Fraction(k, 10) for k in row] for row in [[1, 4, 5], [2, 3, 6], [3, 5, 2]]]
    assert window_densities(area, [[0] * 3] * 3, 2, 4) == [Fraction(2, 5), Fraction(3, 20), Fraction(13, 40), Fraction(1, 10)]
    d, p = lp_density_fill(area, slack, 2, Fraction(1, 2), 4)
    assert d == Fraction(19, 40)
    assert feasible(area, slack, p, 2, Fraction(1, 2), 4)
    mine = [[Fraction(k, 10) for k in row] for row in [[0, 1, 3], [0, 3, 6], [0, 4, 2]]]
    assert window_densities(area, mine, 2, 4) == [Fraction(1, 2), Fraction(19, 40), Fraction(1, 2), Fraction(19, 40)]
    assert lp_density_fill(area, slack, 2, Fraction(3, 10), 4) is None


def test_window_helpers():
    assert windows(3, 2) == [(0, 0), (0, 1), (1, 0), (1, 1)]
    assert window_tiles(1, 0, 2) == [(1, 0), (1, 1), (2, 0), (2, 1)]
    assert floating_error(1) == Fraction(3, 4)

History

Kahng, Robins, Singh, Wang and Zelikovsky stated the Filling and Slotting Problem in 1998 and proved the bound on the error of fixed dissections. In 1999 Kahng, Robins, Singh and Zelikovsky gave the min-variation linear program on a fixed dissection. Chen, Kahng, Robins and Zelikovsky followed with Monte Carlo, iterated and hierarchical methods from 2000 to scale to full chips, and Tian et al. gave min-fill and model-based linear programs.

References

  1. Andrew B. Kahng, Gabriel Robins, Anish Singh and Alexander Zelikovsky, Filling algorithms and analyses for layout density control, IEEE Transactions on Computer-Aided Design of Integrated Circuits and Systems 18(4), 445 to 462, April 1999, the filling problem for a fixed r-dissection, with a fill variable per tile bounded by the tile slack and the linear program that maximizes the minimum window density under the upper bound U
  2. Andrew B. Kahng, Gabriel Robins, Anish Singh, Huijuan Wang and Alexander Zelikovsky, Filling and slotting, analysis and algorithms, Proceedings of the International Symposium on Physical Design (ISPD), 95 to 102, 1998, Theorem 8, the bounds L - 1/r + 1/(4r^2) and U + 1/r - 1/(4r^2) on the density of any window when all windows of the fixed r-dissection satisfy [L, U], and their tightness
  3. Andrew B. Kahng and Kambiz Samadi, CMP fill synthesis, a survey of recent studies, IEEE Transactions on Computer-Aided Design of Integrated Circuits and Systems 27(1), 3 to 19, January 2008, Section IV-B, part 1 on LP-based and Monte Carlo methods, which restates the min-variation LP, the min-fill LP of Tian et al., and the Monte Carlo and greedy fill of Chen, Kahng, Robins and Zelikovsky

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.build
  • 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