Algorithm Search⌘K

Algorithmadvanced

FLUTE

Also called fast lookup table Steiner tree.

Chu and Wong's rectilinear Steiner tree method that looks up optimal trees for nets of up to nine pins in precomputed tables and splits larger nets into smaller ones.

Time
O(n^2) worstO(1) table_lookup
Space
O(n) extra
Where
D = the largest degree with a table; n = the number of pins
Properties
deterministicnot exactrecursive
Origin
Chris Chu, Yiu Chung Wong, 2004

FLUTE (fast lookup table estimation) is a method of Chris Chu and Yiu-Chung Wong that builds rectilinear Steiner trees for the nets of a chip in electronic design automation (EDA). Most nets have few pins, and for a small net the optimal tree depends only on the order of the pins in xx and in yy and on the gaps between their coordinates. FLUTE stores, for every such order, a short list of wirelength vectors, each a formula for the length of a candidate tree in terms of the gaps, together with the tree. A lookup evaluates these few formulas and takes the shortest, which gives an optimal tree for nets of up to 9 pins in the published tables. Larger nets are broken into smaller ones until the tables apply, so for them the result is a heuristic. The method is used in placement and global routing tools, where millions of nets must be estimated many times.

In plain words

Take a net of four pins. Sort the pins from left to right, and note their order from bottom to top. This gives one of 4!=244! = 24 patterns. Two nets with the same pattern are stretched copies of each other.

For each pattern, the best wire can only have a few shapes. The length of each shape is a sum of the gaps between neighboring columns and rows, with some gaps counted twice. So for each pattern we write down a short list of formulas, once, before any chip is seen.

For a real net, find its pattern, put its gaps into the formulas, and take the smallest result. That is the length of the best tree.

A net with many pins has too many patterns for a table. Split it into smaller nets that share a pin, and join their trees.

The problem

The input is a net, a set PP of nn pins in the plane. The output is a rectilinear Steiner tree of PP, a tree of horizontal and vertical wires that joins all pins, possibly through extra Steiner points, of small total length. The optimum is the rectilinear Steiner minimal tree, and finding it is NP-hard for general nn, see the rectilinear Steiner tree problem.

Sort the pins by xx, with ties by yy, and sort them by yy, with ties by xx. The position sequence π\pi records, for the pin of xx rank ii, its yy rank π(i)\pi(i). Let x1≤⋯≤xnx_1 \le \cdots \le x_n and y1≤⋯≤yny_1 \le \cdots \le y_n be the sorted coordinates, and let the gaps be hi=xi+1−xih_i = x_{i+1} - x_i and vj=yj+1−yjv_j = y_{j+1} - y_j. Every pin lies on the n×nn \times n grid of these coordinates. By Hanan's theorem some optimal tree lies on this grid, so its length is

∑i=1n−1aihi+∑j=1n−1bjvj,\sum_{i=1}^{n-1} a_i h_i + \sum_{j=1}^{n-1} b_j v_j,

where aia_i and bjb_j count how many wires cross the column gap ii and the row gap jj. The integer vector (a,b)(a, b) is the wirelength vector of the tree. It depends only on the tree on the grid, and the same grid tree exists for every net with the sequence π\pi.

The algorithm

The tables are built once, offline. For each degree d≤Dd \le D and each position sequence π\pi of length dd, the table holds the wirelength vectors of trees on the grid that can be optimal for some gaps, and for each vector one tree. A vector that is at least another vector in every entry can never be the only best one, since the gaps are not negative, so it can be dropped.

  1. FLUTE(P, D)
  2. 1if |P| ≤ D then
  3. 2π ← the position sequence of P; g ← the gaps (h_1, …, h_{n−1}, v_1, …, v_{n−1})
  4. 3(a, S) ← the entry of table[π] with the least a · g
  5. 4return MST(P ∪ S), with the Steiner points S placed at their grid coordinates
  6. 5best ← none
  7. 6for each axis in {x, y} do
  8. 7split P at the pin of median rank on this axis into two nets that share that pin
  9. 8solve both nets by FLUTE(·, D); if their total length is less than that of best then best ← this pair
  10. 9return the union of the two trees of best

The implementation on this page builds its own tables for D=4D = 4 with the Dreyfus-Wagner recursion of the Steiner tree problem in graphs, run on the d×dd \times d grid, where costs are vectors instead of numbers and each set of vectors is cut down to the vectors that no other vector is at most in every entry, its Pareto minima. For degree 4 this gives 40 vectors over the 24 position sequences: 8 sequences have one vector and 16 have two. The published FLUTE tables go to D=9D = 9 and come with their own generation method. The net breaking of lines L5 to L9 is a simplified form: FLUTE chooses the breaking pin by a score and has an accuracy parameter that tries more ways to break the net.

Example

Take the four pins (0,0)(0, 0), (2,4)(2, 4), (3,1)(3, 1) and (6,5)(6, 5). In order of xx their yy ranks are 0,2,1,30, 2, 1, 3, so π=(0,2,1,3)\pi = (0, 2, 1, 3). The gaps are h=(2,1,3)h = (2, 1, 3) and v=(1,3,1)v = (1, 3, 1). The table for this sequence has two vectors.

vector (a;b)(a; b) meaning length here
(1,2,1; 1,1,1)(1, 2, 1;\ 1, 1, 1) the middle column gap is crossed twice 2+2+3+1+3+1=122 + 2 + 3 + 1 + 3 + 1 = 12
(1,1,1; 1,2,1)(1, 1, 1;\ 1, 2, 1) the middle row gap is crossed twice 2+1+3+1+6+1=142 + 1 + 3 + 1 + 6 + 1 = 14

The first vector wins. Its tree has one Steiner point at the grid point of column 1 and row 1, which is (2,1)(2, 1), and the edges (0,0)(0,0) to (2,1)(2,1) of length 3, (2,1)(2,1) to (3,1)(3,1) of 1, (2,1)(2,1) to (2,4)(2,4) of 3 and (2,4)(2,4) to (6,5)(6,5) of 5, total 12. The half perimeter of the bounding box is 6+5=116 + 5 = 11, and every tree here must pay one gap more, the smaller of h2=1h_2 = 1 and v2=3v_2 = 3.

Now stretch the same pattern: the pins (0,0)(0, 0), (1,3)(1, 3), (5,2)(5, 2) and (6,5)(6, 5) have the same π\pi, with h=(1,4,1)h = (1, 4, 1) and v=(2,1,2)v = (2, 1, 2). The first vector gives 1+8+1+5=151 + 8 + 1 + 5 = 15 and the second gives 6+2+2+2=126 + 2 + 2 + 2 = 12, so now the second tree wins, with its Steiner point at (1,2)(1, 2). The same two formulas cover every net with this pattern.

On the five pins (0,0)(0, 0), (4,1)(4, 1), (1,4)(1, 4), (5,5)(5, 5) and (2,3)(2, 3) the implementation breaks the net and returns length 13, the optimum, with Steiner points (1,3)(1, 3) and (4,3)(4, 3).

Correctness

The proof shows the following.

  • Lengths are linear in the gaps. Every tree on the grid of a sequence π\pi has a length a⋅ga \cdot g for an integer vector that does not depend on the gaps.
  • The table gives the optimum. For a net with n≤Dn \le D pins, the least a⋅ga \cdot g over the table is the length of a rectilinear Steiner minimal tree. This uses Hanan's theorem and the fact that dropping a vector that another vector is at most in every entry never loses the minimum when g≥0g \ge 0. Repeated coordinates give zero gaps and are covered by the same formula.
  • The vector recursion is right. The Dreyfus-Wagner recursion with sets of vectors gives, for every g≥0g \ge 0 at once, the optimal Steiner tree length in the grid graph, because each step is a sum or a minimum and both commute with the linear map a↦a⋅ga \mapsto a \cdot g.
  • Net breaking gives a tree. Two trees that share a pin form one tree that spans all pins, and its length is the sum of the two. It is an upper bound, not the optimum.
Proof: The table lookup of FLUTE gives a rectilinear Steiner minimal tree for small nets, and net breaking gives a valid treefull

Let PP be a net of nn pins with position sequence π\pi, sorted coordinates x1≤⋯≤xnx_1 \le \cdots \le x_n and y1≤⋯≤yny_1 \le \cdots \le y_n, and gaps g=(h1,…,hn−1,v1,…,vn−1)≥0g = (h_1, \ldots, h_{n-1}, v_1, \ldots, v_{n-1}) \ge 0. The grid graph Γπ\Gamma_\pi has the nodes (i,j)(i, j) for 0≤i,j<n0 \le i, j < n, and an edge between nodes that differ by one in one index. Pin kk in xx order is the node (k,π(k))(k, \pi(k)). Under the gaps gg, the horizontal edge between columns ii and i+1i + 1 has length hi+1h_{i+1}, and the vertical edge between rows jj and j+1j + 1 has length vj+1v_{j+1}, with indices from 1 for the gaps.

Lemma 1 (lengths are linear in the gaps). For every subgraph TT of Γπ\Gamma_\pi there is a vector w(T)∈Z≥02(n−1)w(T) \in \mathbb{Z}_{\ge 0}^{2(n-1)} that does not depend on gg, such that the length of TT under gg is w(T)⋅gw(T) \cdot g. A grid tree for π\pi is a tree for every net with the sequence π\pi.

Proof. Let w(T)iw(T)_i be the number of horizontal edges of TT between columns i−1i - 1 and ii, and w(T)n−1+jw(T)_{n-1+j} the number of vertical edges between rows j−1j - 1 and jj. Each edge contributes its gap once, so the length is w(T)⋅gw(T) \cdot g. The nodes that are pins depend only on π\pi, so the same subgraph spans the pins of every net with this sequence. □\square

Lemma 2 (the optimum is a minimum of linear forms). Let WπW_\pi be the set of vectors w(T)w(T) of the trees TT in Γπ\Gamma_\pi that contain all pin nodes. Then the length of a rectilinear Steiner minimal tree of PP is min⁡w∈Wπw⋅g\min_{w \in W_\pi} w \cdot g.

Proof. First let all xx values be distinct and all yy values be distinct. Each tree in Γπ\Gamma_\pi maps to a rectilinear Steiner tree of PP with the same length, by placing node (i,j)(i, j) at (xi+1,yj+1)(x_{i+1}, y_{j+1}), so the minimum is at least the optimum. By Hanan's theorem there is an optimal tree whose Steiner points lie on the grid of lines through the pins, and whose edges can be drawn as L shapes along these lines without changing the length. Split its edges at every grid point they pass. The result is a connected subgraph of the drawn grid that contains the pins, of the same length, and a spanning tree of it is a tree in Γπ\Gamma_\pi that is no longer. So the minimum is at most the optimum.

If some coordinates are equal, some gaps are 0. The optimal length is a continuous function of the coordinates, since moving one pin by δ\delta in L1 changes it by at most δ\delta. Both sides of the formula are continuous in gg and agree for all gaps that are positive, so they agree in the limit. □\square

Lemma 3 (pruning is safe). Let WW be a finite set of vectors and let W′W' be the set of its Pareto minima, the vectors a∈Wa \in W such that no other b∈Wb \in W has b≤ab \le a in every entry. Then min⁡a∈W′a⋅g=min⁡a∈Wa⋅g\min_{a \in W'} a \cdot g = \min_{a \in W} a \cdot g for every g≥0g \ge 0.

Proof. Let a∈Wa \in W. The relation "at most in every entry" is a partial order on the finite set WW, so there is a minimal element b≤ab \le a, and b∈W′b \in W'. Since g≥0g \ge 0, b⋅g≤a⋅gb \cdot g \le a \cdot g. So the minimum over W′W' is at most the minimum over WW, and it is not less, since W′⊆WW' \subseteq W. □\square

Lemma 4 (the vector recursion). For a set XX of pins and a node vv, let F(X,v)F(X, v) be the set computed by the recursion

  • F({k},v)={box(k,v)}F(\{k\}, v) = \{\mathrm{box}(k, v)\}, the vector of the gaps between pin kk and vv,
  • G(X,u)=Pareto{a+b:a∈F(X′,u), b∈F(X∖X′,u), ∅≠X′⊊X}G(X, u) = \mathrm{Pareto}\{a + b : a \in F(X', u),\ b \in F(X \setminus X', u),\ \emptyset \ne X' \subsetneq X\},
  • F(X,v)=Pareto{a+box(u,v):u a node, a∈G(X,u)}F(X, v) = \mathrm{Pareto}\{a + \mathrm{box}(u, v) : u \text{ a node},\ a \in G(X, u)\}.

Then for every g≥0g \ge 0, min⁡a∈F(X,v)a⋅g\min_{a \in F(X, v)} a \cdot g is the length of a shortest Steiner tree of X∪{v}X \cup \{v\} in Γπ\Gamma_\pi under gg.

Proof. Fix g≥0g \ge 0 and write c(A)=min⁡a∈Aa⋅gc(A) = \min_{a \in A} a \cdot g for a set of vectors AA. The map a↦a⋅ga \mapsto a \cdot g is linear, so c({a+b:a∈A,b∈B})=c(A)+c(B)c(\{a + b : a \in A, b \in B\}) = c(A) + c(B) and c(A∪B)=min⁡(c(A),c(B))c(A \cup B) = \min(c(A), c(B)), and c(Pareto(A))=c(A)c(\mathrm{Pareto}(A)) = c(A) by Lemma 3. The vector box(u,v)\mathrm{box}(u, v) has a 1 for each gap between the columns of uu and vv and between their rows, so box(u,v)⋅g\mathrm{box}(u, v) \cdot g is the shortest path length from uu to vv in Γπ\Gamma_\pi. Applying cc to the recursion therefore gives exactly the Dreyfus-Wagner recursion for the Steiner tree problem in the graph Γπ\Gamma_\pi with these lengths, which computes shortest Steiner trees. The restriction that X′X' contains the lowest pin of XX, used by the implementation, only skips splits that are the same as another split with the parts exchanged. □\square

Theorem 1 (lookup gives the optimum). For a net with 2≤n≤D2 \le n \le D pins, the least a⋅ga \cdot g over the table entry of π\pi is the length of a rectilinear Steiner minimal tree, and the tree stored with it, placed on the coordinates, has this length.

Proof. The entry is F(all pins but the last,the last pin)F(\text{all pins but the last}, \text{the last pin}), so by Lemma 4 its least value is the shortest Steiner tree of all pins in Γπ\Gamma_\pi, which is min⁡w∈Wπw⋅g\min_{w \in W_\pi} w \cdot g. By Lemma 2 this is the optimal length. Each vector in the entry comes from a tree in Γπ\Gamma_\pi whose branch nodes are recorded with it. Placing these nodes at their coordinates and joining the pins and these points by their L1 minimum spanning tree gives a tree no longer than the grid tree, since the grid tree is a connected graph on these points whose edges are at least the L1 distances of their ends. For n≤1n \le 1 the length is 0. □\square

Lemma 5 (net breaking). If T1T_1 is a tree that spans P1P_1 and T2T_2 is a tree that spans P2P_2, with P1∪P2=PP_1 \cup P_2 = P, P1∩P2={p}P_1 \cap P_2 = \{p\}, and the Steiner points of the two trees kept apart, then T1∪T2T_1 \cup T_2 is a rectilinear Steiner tree of PP of length ∣T1∣+∣T2∣|T_1| + |T_2|.

Proof. The union is connected, since both trees contain pp. Its number of edges is (∣V1∣−1)+(∣V2∣−1)=∣V1∪V2∣−1(|V_1| - 1) + (|V_2| - 1) = |V_1 \cup V_2| - 1, since the vertex sets meet only in pp. A connected graph with one edge fewer than vertices is a tree. Its length is the sum. Two drawn wires may overlap in the plane, in which case the drawn length is at most the sum. □\square

For n>Dn > D the median split gives two nets of ⌊n/2⌋+1\lfloor n/2 \rfloor + 1 and ⌈n/2⌉\lceil n/2 \rceil pins, both less than nn when n≥3n \ge 3, so the recursion ends, and by Lemma 5 and induction the output is a valid tree. No bound on its ratio to the optimum is claimed. □\square

Complexity

  • Lookup. For n≤Dn \le D the work is two sorts of nn pins and one dot product of length 2(n−1)2(n - 1) per table entry. For a fixed DD this is O(1)O(1), and for small nets it is about as fast as a rectilinear minimum spanning tree.
  • Net breaking here. The simple breaking of this page solves four nets of about half the size at each level, two per axis, so T(n)=4T(n/2+1)+O(nlog⁡n)T(n) = 4T(n/2 + 1) + O(n \log n), which is O(n2)O(n^2). FLUTE breaks nets with its own scores, and its paper reports run times close to those of a fast rectilinear MST code on the ISPD98 circuits.
  • Tables. A table of degree dd has d!d! position sequences. The size grows fast with dd, which is one reason why the published tables stop at d=9d = 9. The construction here builds the table of one sequence when it is first needed and caches it.

Properties

  • What is proved. For nets of at most DD pins the result is optimal. For larger nets the result is a valid rectilinear Steiner tree, with no proved bound on its ratio to the optimum.
  • What the authors report. The 2008 paper says that FLUTE is optimal up to degree 9 in its implementation, and very accurate up to degree 100, and that with the default accuracy it was more accurate than the batched form of iterated 1-Steiner and almost as fast as Prim's rectilinear MST on the nets of 18 ISPD98 circuits.
  • What is measured here. With tables only up to D=4D = 4 and the simple breaking, on random nets with coordinates from 0 to 99 (Python random.Random(2026)), compared with the brute-force optimum: for 200 nets of 5 pins the mean ratio was 1.0476, the worst 1.3396, and 105 nets were optimal; for 25 nets of 6 pins the mean was 1.0457, the worst 1.20, and 13 were optimal. These are toy inputs, not benchmark results, and they are much worse than FLUTE itself, because real FLUTE looks up nets of 5 to 9 pins in its tables.
  • Deterministic. Ties in the table go to the first entry, and ties in the breaking go to the xx axis.

Variants and improvements

  • Accuracy parameter. FLUTE has a parameter that controls how many ways a large net is broken and which result is kept, a tradeoff between time and length set by the user.
  • Wirelength only. The first form of 2004 was aimed at wirelength estimation, which is what a placement tool needs most of the time. The trees themselves are needed for routing.
  • Larger nets. Later work extended the method to nets with many pins, with other ways to break the net and to improve the joined trees.
  • Other tools. Placement tools that want a cheaper estimate use the half-perimeter wirelength, which is exact only for nets of up to 3 pins.

When to use it

  • When the Steiner tree length of millions of small nets is needed over and over, in placement and global routing.
  • When most nets have fewer than 10 pins, which is common in chips.

For one large net where the length matters more than the time, iterated 1-Steiner or an exact solver can do better. When only a bound is needed, the rectilinear minimum spanning tree is simpler.

Pitfalls

  • Ties in coordinates. Pins that share an xx or a yy value need a fixed rule for their ranks. The formula still holds with zero gaps, but the code must map the grid points of the tree back to coordinates with the sorted lists, not with the pin index.
  • Steiner points on pins. With zero gaps, a grid Steiner point can fall on a pin. Remove such points before building the tree.
  • Calling the breaking exact. The result for a net larger than DD is a heuristic. Two halves that are each optimal do not make an optimal whole.
  • Table size. Building tables for large dd is expensive in time and memory, since there are d!d! sequences. Use symmetry, or ship the precomputed tables.

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.

flute.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/flute/. The authors are listed in prov/Q78Z3D.jsonl.

from functools import lru_cache
from itertools import permutations
from typing import Sequence

Point = tuple[int, int]
Edge = tuple[int, int]  # indices into the point list
Vec = tuple[int, ...]

TABLE_DEGREE = 4  # FLUTE ships tables up to degree 9; this code builds them up to 4


def pareto(items: dict[Vec, frozenset]) -> dict[Vec, frozenset]:
    """Keep the vectors that no other vector is at most in every coordinate."""
    vecs = sorted(items, key=sum)
    keep: list[Vec] = []
    for a in vecs:
        if not any(all(x <= y for x, y in zip(b, a)) for b in keep):
            keep.append(a)
    return {a: items[a] for a in keep}


@lru_cache(maxsize=None)
def powv_table(pi: tuple[int, ...]) -> tuple[tuple[Vec, frozenset], ...]:
    """Wirelength vectors for the position sequence pi, with Steiner nodes for each.

    Pin i has x rank i and y rank pi[i]. A vector (a_1..a_{d-1}, b_1..b_{d-1})
    stands for the length sum a_i h_i + sum b_j v_j, where h_i and v_j are the
    gaps between consecutive x and y values. For every choice of gaps >= 0, the
    least of these sums is the length of a rectilinear Steiner minimal tree.
    Built by a Dreyfus-Wagner recursion over the d x d grid with vector costs.
    """
    d = len(pi)
    nodes = [(i, j) for i in range(d) for j in range(d)]
    term = [(i, pi[i]) for i in range(d)]

    def box(u: tuple[int, int], v: tuple[int, int]) -> Vec:
        vec = [0] * (2 * (d - 1))
        for k in range(min(u[0], v[0]), max(u[0], v[0])):
            vec[k] = 1
        for k in range(min(u[1], v[1]), max(u[1], v[1])):
            vec[d - 1 + k] = 1
        return tuple(vec)

    def add(a: Vec, b: Vec) -> Vec:
        return tuple(x + y for x, y in zip(a, b))

    full = (1 << d) - 1
    F: dict[tuple[int, tuple[int, int]], dict[Vec, frozenset]] = {}
    for k in range(d):
        for v in nodes:
            F[(1 << k, v)] = {box(term[k], v): frozenset()}
    for mask in sorted(range(1, full + 1), key=lambda m: bin(m).count("1")):
        if bin(mask).count("1") < 2:
            continue
        low = mask & -mask
        G: dict[tuple[int, int], dict[Vec, frozenset]] = {}
        for u in nodes:
            acc: dict[Vec, frozenset] = {}
            sub = (mask - 1) & mask
            while sub:
                if sub & low:
                    for a, sa in F[(sub, u)].items():
                        for b, sb in F[(mask ^ sub, u)].items():
                            c = add(a, b)
                            if c not in acc:
                                acc[c] = sa | sb | {u}
                sub = (sub - 1) & mask
            G[u] = pareto(acc)
        for v in nodes:
            acc = {}
            for u in nodes:
                bu = box(u, v)
                for a, sa in G[u].items():
                    c = add(a, bu)
                    if c not in acc:
                        acc[c] = sa
            F[(mask, v)] = pareto(acc)
    last = d - 1
    ans = F[(full ^ (1 << last), term[last])] if d > 1 else {(): frozenset()}
    tset = set(term)
    return tuple((vec, frozenset(s for s in st if s not in tset)) for vec, st in ans.items())


def all_tables(d: int) -> dict[tuple[int, ...], tuple[tuple[Vec, frozenset], ...]]:
    """The whole lookup table for degree d, one entry per position sequence."""
    return {pi: powv_table(pi) for pi in permutations(range(d))}


def l1(p: Point, q: Point) -> int:
    return abs(p[0] - q[0]) + abs(p[1] - q[1])


def mst_edges(pts: Sequence[Point]) -> list[Edge]:
    """Prim's algorithm on the complete L1 graph, O(k^2) for k points."""
    k = len(pts)
    if k == 0:
        return []
    best = [(l1(pts[0], p), 0) for p in pts]
    used = [False] * k
    used[0] = True
    out = []
    for _ in range(k - 1):
        j = min((i for i in range(k) if not used[i]), key=lambda i: best[i][0])
        used[j] = True
        out.append((best[j][1], j))
        for i in range(k):
            if not used[i] and l1(pts[j], pts[i]) < best[i][0]:
                best[i] = (l1(pts[j], pts[i]), j)
    return out


def lookup(pins: Sequence[Point]) -> tuple[int, list[Point]]:
    """Table lookup for a net of degree at most TABLE_DEGREE: (length, Steiner points)."""
    d = len(pins)
    if d <= 1:
        return 0, []
    by_x = sorted(range(d), key=lambda i: (pins[i][0], pins[i][1]))
    by_y = sorted(range(d), key=lambda i: (pins[i][1], pins[i][0]))
    yrank = {p: r for r, p in enumerate(by_y)}
    pi = tuple(yrank[i] for i in by_x)
    xs = [pins[i][0] for i in by_x]
    ys = [pins[i][1] for i in by_y]
    gaps = [xs[k + 1] - xs[k] for k in range(d - 1)] + [ys[k + 1] - ys[k] for k in range(d - 1)]  # @line L2
    best = None
    for vec, st in powv_table(pi):
        w = sum(a * g for a, g in zip(vec, gaps))  # @line L3
        if best is None or w < best[0]:
            best = (w, st)
    w, st = best
    pinset = set(pins)
    return w, sorted({(xs[i], ys[j]) for i, j in st} - pinset)


def flute(pins: Sequence[Point]) -> tuple[int, list[Point], list[Edge]]:
    """Rectilinear Steiner tree of the pins in the style of FLUTE.

    Returns (length, points, edges): points are the pins followed by Steiner
    points, and edges join point indices. For at most TABLE_DEGREE pins the
    length is the optimum. Larger nets are split at a pin of median x rank or
    median y rank, recursively, and the shorter result is kept.
    """
    pins = list(pins)
    d = len(pins)
    if d <= TABLE_DEGREE:  # @line L1
        w, st = lookup(pins)
        pts = pins + st
        edges = mst_edges(pts)  # @line L4
        return sum(l1(pts[a], pts[b]) for a, b in edges), pts, edges
    best = None  # @line L5
    for axis in (0, 1):  # @line L6
        order = sorted(range(d), key=lambda i: (pins[i][axis], pins[i][1 - axis]))
        r = d // 2
        left = [pins[i] for i in order[: r + 1]]  # @line L7
        right = [pins[i] for i in order[r:]]
        wl, pl, el = flute(left)  # @line L8
        wr, pr, er = flute(right)
        if best is None or wl + wr < best[0]:
            best = (wl + wr, (order, r, pl, el, pr, er))
    total, (order, r, pl, el, pr, er) = best
    # Join the two trees at the shared pin order[r]; pins keep their input indices.
    idx_left = order[: r + 1] + [d + k for k in range(len(pl) - r - 1)]
    nl = len(pl) - r - 1
    idx_right = order[r:] + [d + nl + k for k in range(len(pr) - (d - r))]
    pts = pins + pl[r + 1:] + pr[d - r:]
    edges = [(idx_left[a], idx_left[b]) for a, b in el] + [(idx_right[a], idx_right[b]) for a, b in er]
    return total, pts, edges  # @line L9
test_flute.py 84 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/flute/. The authors are listed in prov/Q78Z3D.jsonl.

import random
from itertools import combinations

from flute import all_tables, flute, l1, lookup, mst_edges, powv_table


def mst_length(pts: list[tuple[int, int]]) -> int:
    return sum(l1(pts[a], pts[b]) for a, b in mst_edges(pts))


def exact_rsmt(pins: list[tuple[int, int]]) -> int:
    """Brute force: the least MST length over pins plus at most n - 2 points of the Hanan grid."""
    xs = sorted({p[0] for p in pins})
    ys = sorted({p[1] for p in pins})
    cand = [(x, y) for x in xs for y in ys if (x, y) not in set(pins)]
    best = mst_length(pins)
    for k in range(1, max(len(pins) - 1, 1)):
        for extra in combinations(cand, k):
            best = min(best, mst_length(pins + list(extra)))
    return best


def is_tree(pts: list[tuple[int, int]], edges: list[tuple[int, int]], npins: int) -> bool:
    n = len(pts)
    if len(edges) != max(n - 1, 0):
        return False
    parent = list(range(n))

    def find(a: int) -> int:
        while parent[a] != a:
            a = parent[a]
        return a

    for a, b in edges:
        if find(a) == find(b):
            return False
        parent[find(a)] = find(b)
    return n >= npins


def test_tables() -> None:
    assert powv_table((0, 1)) == (((1, 1), frozenset()),)
    for pi, entry in all_tables(3).items():
        assert [v for v, _ in entry] == [(1, 1, 1, 1)]
    assert [v for v, _ in powv_table((1, 0, 3, 2))] == [(1, 1, 1, 1, 1, 1)]
    assert {v for v, _ in powv_table((0, 2, 1, 3))} == {(1, 2, 1, 1, 1, 1), (1, 1, 1, 1, 2, 1)}
    assert sum(len(e) for e in all_tables(4).values()) == 40


def test_plus() -> None:
    pins = [(1, 0), (0, 1), (2, 1), (1, 2)]
    w, st = lookup(pins)
    assert w == 4 and st == [(1, 1)]
    total, pts, edges = flute(pins)
    assert total == 4 and is_tree(pts, edges, 4)


def test_edges() -> None:
    assert flute([]) == (0, [], [])
    assert flute([(3, 4)]) == (0, [(3, 4)], [])
    assert flute([(0, 0), (2, 5)])[0] == 7
    assert flute([(0, 0), (4, 0), (2, 3)])[0] == 7
    assert flute([(1, 1), (1, 1), (1, 1)])[0] == 0


def test_against_exact(seed: int = 29) -> None:
    rng = random.Random(seed)
    for _ in range(300):
        n = rng.randint(2, 4)
        pins = [(rng.randint(0, 8), rng.randint(0, 8)) for _ in range(n)]
        total, pts, edges = flute(pins)
        assert pts[:n] == pins and is_tree(pts, edges, n)
        assert total == sum(l1(pts[a], pts[b]) for a, b in edges)
        assert total == lookup(pins)[0] == exact_rsmt(list(dict.fromkeys(pins)))
    for _ in range(40):
        n = rng.randint(5, 6) if _ < 8 else 5
        pins = list(dict.fromkeys((rng.randint(0, 12), rng.randint(0, 12)) for _ in range(n)))
        total, pts, edges = flute(pins)
        assert pts[: len(pins)] == pins and is_tree(pts, edges, len(pins))
        assert total == sum(l1(pts[a], pts[b]) for a, b in edges)
        assert exact_rsmt(pins) <= total

History

M. Hanan showed in 1966 that the grid of lines through the pins contains an optimal rectilinear Steiner tree, which makes the set of tree shapes for a net finite and dependent only on the order of the pins. Chris Chu presented FLUTE at ICCAD 2004 as a fast and accurate way to estimate the wirelength of nets in placement, with lookup tables of wirelength vectors for small nets. Chu and Yiu-Chung Wong turned it into a Steiner tree algorithm at ISPD 2005. The journal version of 2008 added a new net breaking method and a parameter that trades time for accuracy. FLUTE became a standard Steiner tree routine inside academic placers and global routers.

References

  1. Chris Chu and Yiu-Chung Wong, FLUTE, fast lookup table based rectilinear Steiner minimal tree algorithm for VLSI design, IEEE Transactions on Computer-Aided Design of Integrated Circuits and Systems 27(1), 70 to 83, 2008, the position sequence, the wirelength vectors, the lookup tables up to degree 9, the net breaking and the accuracy parameter
  2. Chris Chu, FLUTE, fast lookup table based wirelength estimation technique, Proceedings of ICCAD 2004, 696 to 701, the first form of the lookup tables, for wirelength estimation
  3. Chris Chu and Yiu-Chung Wong, Fast and accurate rectilinear Steiner minimal tree algorithm for VLSI design, Proceedings of ISPD 2005, the conference version of the Steiner tree algorithm
  4. M. Hanan, On Steiner's problem with rectilinear distance, SIAM Journal on Applied Mathematics 14(2), 255 to 265, 1966, the theorem that some optimal tree lies on the grid of lines through the pins

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