Algorithm Search⌘K

Algorithmadvanced

SAT-based FPGA detailed routing

Also called Nam-Sakallah-Rutenbar routing.

Nam, Sakallah and Rutenbar's router that encodes the track choice of every net in every switch block as a SAT formula, proving routability or unroutability.

Time
O(W^2 (L + E) + W P) encodeO(2^(W L) W L (W^2 (L + E) + W P)) solve
Space
O(W^2 (L + E) + W P) total
Where
E = the number of edges of all route trees; L = the number of pairs of a net and a segment of its global route; P = the number of pairs of nets that share a segment (counted once per shared segment); W = the channel width
Properties
deterministicexactiterative
Origin
Gi Joon Nam, Karem A. Sakallah, Rob A. Rutenbar, 1999

SAT-based FPGA detailed routing is an exact method of FPGA CAD for the detailed routing of an island-style FPGA: with the global routing of every net fixed, it writes the choice of a track for each net in each channel segment as a formula in conjunctive normal form, and gives it to a SAT solver. A model of the formula is a legal detailed routing, and an unsatisfiable formula proves that no legal detailed routing exists for that global routing at that channel width. Nam, Sakallah and Rutenbar introduced the method in 1999 and 2002.

In plain words

After global routing, each net knows which stretches of channel it will use, but not which wire in each stretch. Two nets in the same stretch need different wires, and where a net turns a corner, its two wires must be joined by a switch in that corner.

A heuristic router tries choices and gives up after a while. When it gives up, nobody knows whether a routing exists.

The SAT approach writes every rule as a small logical statement: "this net uses one of these wires", "these two nets do not share this wire", "if the net is on this wire here, it is on a joined wire there". A SAT solver then either finds values that make all the statements true, which is a routing, or proves that no such values exist. The proof means that this global routing cannot be finished with this many wires.

The problem

Input. A channel width WW, so that every channel segment has the tracks 0,…,W−10, \ldots, W - 1. A global routing: for each net nn, a set Seg(n)\mathrm{Seg}(n) of channel segments and a set of edges (s,s′,κ)(s, s', \kappa) that join them into a tree, where ss and s′s' meet at a switch block and κ\kappa names the two sides of that block, such as WN for west to north. A switch pattern: for each κ\kappa and track tt, the set P(κ,t)P(\kappa, t) of tracks of s′s' that a switch joins to track tt of ss (see FPGA switch block).

Output. A legal detailed routing: a track ρ(n,s)\rho(n, s) for each net nn and segment s∈Seg(n)s \in \mathrm{Seg}(n), such that two nets that share a segment use different tracks on it (exclusivity), and ρ(n,s′)∈P(κ,ρ(n,s))\rho(n, s') \in P(\kappa, \rho(n, s)) for each edge (connectivity). Or a proof that none exists.

The model takes the connection blocks to be full, so every pin reaches every track of its segment. The global routing is part of the input; finding it is a separate problem, global routing. The method reduces this decision problem to SAT.

The algorithm

Variable xn,s,tx_{n,s,t} says that net nn uses track tt of segment ss.

  1. SAT-ROUTE(nets with their route trees, W, P)
  2. 1make a variable x[n, s, t] for each net n, each segment s of its route and each track t
  3. 2for each pair (n, s): add the clause x[n,s,0] ∨ … ∨ x[n,s,W−1]
  4. 3for each pair (n, s) and tracks t < u: add the clause ¬x[n,s,t] ∨ ¬x[n,s,u]
  5. 4for each segment s, nets n ≠ m that use s, and track t: add ¬x[n,s,t] ∨ ¬x[m,s,t]
  6. 5for each edge (s, s', κ) of net n and track t: add ¬x[n,s,t] ∨ ⋁ over u in P(κ, t) of x[n,s',u]
  7. 6run a complete SAT solver on the clauses
  8. 7if it reports UNSAT: return "no detailed routing of this global routing at width W"
  9. 8return ρ(n, s) = the track t with x[n,s,t] true

Lines L2 and L3 say that the net uses exactly one track per segment; line L3 is the pairwise at-most-one encoding, and the sequential counter is a smaller alternative for large WW. Line L4 is exclusivity and line L5 is connectivity, which is already a clause, so no Tseitin transformation is needed. The solver of line L6 can be any complete solver, such as DPLL or CDCL; the implementation uses a small DPLL with unit propagation. To find the least width at which the global routing routes, run SAT-ROUTE for W=1,2,…W = 1, 2, \ldots until it succeeds.

With the disjoint switch block, P(κ,t)={t}P(\kappa, t) = \{t\}, so a net keeps one track number along its whole route, and the problem becomes graph coloring of the conflict graph: a vertex per net, and an edge between nets that share a segment.

Example

One switch block has segments on its west (W), north (N) and east (E) sides, with W=2W = 2 tracks each. Net A goes from W to N, net B from N to E, and net C from E to W, straight through. Each side carries two nets, so the channel density is 2.

Disjoint pattern. Each net keeps one track, and the three nets pairwise share a segment, so the conflict graph is a triangle. A triangle needs 3 colors, so the formula at W=2W = 2 is unsatisfiable, and the SAT solver proves that this global routing does not route at width 2. At W=3W = 3 it routes, with A, B and C on tracks 0, 1 and 2.

A twisted pattern. Change only the turn between W and N, so that track tt meets track 1−t1 - t. The formula has 3⋅2⋅2=123 \cdot 2 \cdot 2 = 12 variables and 24 clauses: 6 of line L2, 6 of line L3, 6 of line L4 and 6 of line L5. For net A, L5 gives ¬xA,W,0∨xA,N,1\neg x_{A,W,0} \vee x_{A,N,1} and ¬xA,W,1∨xA,N,0\neg x_{A,W,1} \vee x_{A,N,0}. The solver finds A on track 0 in W and track 1 in N, B on track 0 in N and E, and C on track 1 in E and W. Every side has two different tracks in use, and each net's tracks are joined by its switch. The same global routing that needs width 3 with the disjoint block routes at width 2 here. This is why switch blocks that change tracks, such as the universal switch block, can lower the width.

Correctness

The full proof proves the following, for a fixed global routing and width WW.

  • A model is a routing. If an assignment satisfies the clauses, then each pair (n,s)(n, s) has exactly one true variable, by L2 and L3, and the tracks they name meet exclusivity by L4 and connectivity by L5.
  • A routing is a model. Setting xn,s,tx_{n,s,t} true exactly when ρ(n,s)=t\rho(n, s) = t satisfies every clause when ρ\rho is legal.
  • One to one. These two maps are inverse to each other, so the models and the legal routings are in bijection. The tests check this by counting both on small instances.
  • UNSAT is a proof. A complete solver reports UNSAT only if no model exists, so no legal detailed routing of this global routing exists at width WW. It says nothing about other global routings of the same netlist.
  • The routing is a routing on the graph. A legal detailed routing gives vertex-disjoint trees in the routing resource graph, one per net.
  • Disjoint pattern. With P(κ,t)={t}P(\kappa, t) = \{t\}, routability at width WW is the WW-colorability of the conflict graph. Every graph is a conflict graph in the abstract model, so the problem is NP-complete for W=3W = 3 there.

The tests compare the router with exhaustive search over all track assignments: 60 satisfiable and 60 unsatisfiable seeded random instances agreed, with random switch patterns and widths 1 to 3. This is a check of the implementation, not a measure of speed.

Proof: The routing formula is satisfiable exactly when the fixed global routing has a legal detailed routing at width W, with models and routings in one-to-one correspondencefull

Setting

The width is W≥1W \ge 1, and every channel segment has the tracks 0,…,W−10, \ldots, W - 1. The global routing is fixed: net nn has a set Seg(n)\mathrm{Seg}(n) of distinct segments and a set E(n)\mathrm{E}(n) of edges (s,s′,κ)(s, s', \kappa) with s,s′∈Seg(n)s, s' \in \mathrm{Seg}(n), where κ\kappa names the two sides of the switch block at which ss and s′s' meet. The switch pattern gives, for each κ\kappa and each track tt, a set P(κ,t)⊆{0,…,W−1}P(\kappa, t) \subseteq \{0, \ldots, W - 1\} of tracks of s′s' that a switch joins to track tt of ss. The pins reach every track of their segments (the connection blocks are full), so the pins add no constraint.

A detailed routing is a map ρ\rho from the pairs (n,s)(n, s) with s∈Seg(n)s \in \mathrm{Seg}(n) to tracks. It is legal when

  1. (exclusivity) ρ(n,s)≠ρ(m,s)\rho(n, s) \ne \rho(m, s) for all nets n≠mn \ne m that both use ss, and
  2. (connectivity) ρ(n,s′)∈P(κ,ρ(n,s))\rho(n, s') \in P(\kappa, \rho(n, s)) for every edge (s,s′,κ)∈E(n)(s, s', \kappa) \in \mathrm{E}(n).

The formula FF has a variable xn,s,tx_{n,s,t} for each pair (n,s)(n, s) and each track tt, and these clauses:

  • (L2) ⋁txn,s,t\bigvee_t x_{n,s,t} for each pair (n,s)(n, s);
  • (L3) ¬xn,s,t∨¬xn,s,u\neg x_{n,s,t} \vee \neg x_{n,s,u} for each pair (n,s)(n, s) and tracks t<ut < u;
  • (L4) ¬xn,s,t∨¬xm,s,t\neg x_{n,s,t} \vee \neg x_{m,s,t} for each segment ss, nets n≠mn \ne m that use ss, and track tt;
  • (L5) ¬xn,s,t∨⋁u∈P(κ,t)xn,s′,u\neg x_{n,s,t} \vee \bigvee_{u \in P(\kappa, t)} x_{n,s',u} for each edge (s,s′,κ)∈E(n)(s, s', \kappa) \in \mathrm{E}(n) and track tt.

These are the clauses that encode builds, line by line.

The correspondence

For a detailed routing ρ\rho, let αρ\alpha_\rho be the assignment with xn,s,tx_{n,s,t} true exactly when ρ(n,s)=t\rho(n, s) = t. For an assignment α\alpha that satisfies the clauses L2 and L3, let ρα(n,s)\rho_\alpha(n, s) be the one track tt with xn,s,tx_{n,s,t} true; L2 says there is at least one and L3 says there is at most one.

Lemma 1. If ρ\rho is legal, then αρ\alpha_\rho satisfies FF.

Proof. Take each clause in turn. L2: xn,s,ρ(n,s)x_{n,s,\rho(n,s)} is true. L3: at most one of xn,s,tx_{n,s,t} and xn,s,ux_{n,s,u} with t≠ut \ne u equals ρ(n,s)\rho(n, s), so one of the negations is true. L4: if both xn,s,tx_{n,s,t} and xm,s,tx_{m,s,t} were true, then ρ(n,s)=t=ρ(m,s)\rho(n, s) = t = \rho(m, s), against exclusivity. L5: if xn,s,tx_{n,s,t} is false the clause holds; otherwise t=ρ(n,s)t = \rho(n, s), and by connectivity u=ρ(n,s′)∈P(κ,t)u = \rho(n, s') \in P(\kappa, t), so xn,s′,ux_{n,s',u} is a true literal of the clause. □\square

Lemma 2. If α\alpha satisfies FF, then ρα\rho_\alpha is legal.

Proof. ρα\rho_\alpha is well defined by L2 and L3. Exclusivity: if ρα(n,s)=ρα(m,s)=t\rho_\alpha(n, s) = \rho_\alpha(m, s) = t for n≠mn \ne m, then xn,s,tx_{n,s,t} and xm,s,tx_{m,s,t} are both true, and the L4 clause for (s,n,m,t)(s, n, m, t) is false, a contradiction. Connectivity: for an edge (s,s′,κ)(s, s', \kappa) of net nn, let t=ρα(n,s)t = \rho_\alpha(n, s). Then xn,s,tx_{n,s,t} is true, so the L5 clause for this edge and tt needs some true xn,s′,ux_{n,s',u} with u∈P(κ,t)u \in P(\kappa, t). The only true variable of the pair (n,s′)(n, s') is the one with u=ρα(n,s′)u = \rho_\alpha(n, s'), so ρα(n,s′)∈P(κ,t)\rho_\alpha(n, s') \in P(\kappa, t). □\square

Theorem 3. FF is satisfiable if and only if the global routing has a legal detailed routing at width WW. The maps ρ↦αρ\rho \mapsto \alpha_\rho and α↦ρα\alpha \mapsto \rho_\alpha are inverse bijections between the legal detailed routings and the models of FF.

Proof. Lemmas 1 and 2 give both directions of the equivalence. For the bijection: ραρ=ρ\rho_{\alpha_\rho} = \rho, since in αρ\alpha_\rho the true variable of the pair (n,s)(n, s) is the one of track ρ(n,s)\rho(n, s). And αρα=α\alpha_{\rho_\alpha} = \alpha for every model α\alpha, since L2 and L3 make xn,s,tx_{n,s,t} true exactly for t=ρα(n,s)t = \rho_\alpha(n, s), and FF has no other variables. □\square

Corollary 4 (what UNSAT proves). If a complete SAT solver reports that FF is unsatisfiable, then no legal detailed routing exists for this global routing at width WW.

Proof. A complete solver reports unsatisfiable only when FF has no model; by Theorem 3 no legal detailed routing exists. □\square

The corollary is about the fixed global routing only. Another global routing of the same netlist may route at width WW, so UNSAT does not prove that the circuit is unroutable on the device at width WW. If a solver returns a model, line L8 reads ρα\rho_\alpha from it, and Lemma 2 shows that it is legal.

Let the routing resource graph have a node for each track of each segment and an edge for each switch. For net nn, the nodes (s,ρ(n,s))(s, \rho(n, s)) with s∈Seg(n)s \in \mathrm{Seg}(n) are joined by the switches of the edges of E(n)\mathrm{E}(n), by connectivity; if these edges form a tree over Seg(n)\mathrm{Seg}(n), so do the chosen nodes. By exclusivity, two nets never use the same node. So a legal detailed routing gives vertex-disjoint trees, one per net, which is a legal routing on that graph, and the pins reach the trees because the connection blocks are full.

The disjoint pattern

Theorem 5. Let P(κ,t)={t}P(\kappa, t) = \{t\} for all κ\kappa and tt, and let the edges of every net connect its segments. Build the conflict graph GG with a vertex per net and an edge between two nets that share a segment. Then the global routing has a legal detailed routing at width WW if and only if GG has a proper coloring with WW colors.

Proof. If ρ\rho is legal, connectivity gives ρ(n,s′)=ρ(n,s)\rho(n, s') = \rho(n, s) along each edge of net nn, and since the edges connect Seg(n)\mathrm{Seg}(n), net nn has one track c(n)c(n) on all its segments. Two nets that share a segment ss have c(n)=ρ(n,s)≠ρ(m,s)=c(m)c(n) = \rho(n, s) \ne \rho(m, s) = c(m) by exclusivity, so cc is a proper coloring. Conversely, a proper coloring cc with colors 0,…,W−10, \ldots, W - 1 gives ρ(n,s)=c(n)\rho(n, s) = c(n), which satisfies connectivity because the track never changes and exclusivity because nets that share a segment have different colors. □\square

In the abstract model of this page, where a route is any connected set of segments, every graph is a conflict graph: give each edge {u,v}\{u, v\} of the graph its own segment, and let net uu use the segments of its edges, joined in a path. So with the disjoint pattern and W=3W = 3, deciding whether a legal detailed routing exists is NP-complete by the NP-completeness of 3-coloring. This does not say which graphs arise from the geometry of a real FPGA. ■\blacksquare

Complexity

Let LL be the number of pairs of a net and a segment, EE the number of route edges and PP the number of pairs of nets that share a segment. The formula has WLW L variables. Line L2 gives LL clauses of WW literals, line L3 gives LW(W−1)/2L W (W - 1) / 2 clauses of 2, line L4 gives PWP W clauses of 2, and line L5 gives EWE W clauses of at most W+1W + 1. So encoding takes O(W2(L+E)+WP)O(W^2 (L + E) + W P) time and space.

SAT is NP-complete, and this restricted form is NP-complete too by the coloring result, so no polynomial bound on the solve is known. The small DPLL of the implementation explores at most 2WL2^{W L} partial assignments, with unit propagation in O(WL)O(W L) passes over the formula at each, which gives the bound in the front matter. Modern CDCL solvers are far faster on the formulas of real routing problems, but that is measured, not proved.

Properties

  • Exact. The router succeeds whenever a detailed routing of the given global routing exists, and its failure is a proof.
  • Only detailed routing. It does not change the global routing. An UNSAT answer may be fixed by a new global routing, which the method does not search.
  • Pattern-independent. Any switch block that the sets P(κ,t)P(\kappa, t) describe fits the same encoding; only the clauses of line L5 change.
  • All nets at once. Unlike a router that routes one net at a time, the solver decides all tracks together, so it does not get stuck on an early bad choice.

Variants and improvements

  • Route-based formulation. Nam, Aloul, Sakallah and Rutenbar (2001, 2004) compared the track-based formulation with one that has a variable per candidate detailed route of a net, and found the route-based one better on their benchmarks.
  • Symmetry breaking. With the disjoint pattern, the track numbers can be permuted in any solution, so clauses that fix the track of one net cut the search; see symmetry breaking.
  • Incremental width search. When the width search tries W,W+1,…W, W + 1, \ldots, an incremental SAT solver can keep learned clauses between calls.
  • Smaller at-most-one clauses. For large WW, a sequential counter or a log encoding of the track number replaces the W2/2W^2 / 2 clauses of line L3.

When to use it

Use a SAT router when a proof matters: to show that a global routing cannot be completed at a width, to check the routability of a small architecture, or to finish the last few nets that a heuristic router cannot place. For whole designs, use PathFinder, which routes globally and in detail at once and scales to large designs, but which cannot prove that a routing does not exist.

Pitfalls

  • Reading UNSAT as "the circuit is unroutable". UNSAT is about one global routing at one width. A different global route can succeed.
  • Leaving out at-most-one. Without line L3 a model may put a net on two tracks of a segment. A routing can still be read from such a model, but the bijection with routings is lost and the decoder must pick one track.
  • One direction of a switch. Line L5 constrains the track of s′s' from that of ss. With at-most-one in place one direction is enough, but the sets P(κ,t)P(\kappa, t) must be those of the real switch block on that pair of sides.
  • Assuming full connection blocks. With sparse connection blocks, a pin reaches only some tracks, and the formula needs clauses for the pins too.

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.

sat_based_fpga_routing.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sat-based-fpga-routing/. The authors are listed in prov/1K07JP.jsonl.

"""SAT-based detailed routing for an island-style FPGA, after Nam, Sakallah and Rutenbar.

The global routing is fixed. Each net is a route tree over channel segments:
a list of segments and a list of edges (s, s2, kind), where s and s2 meet at a
switch block and kind names the two sides of the switch block that the edge
joins, such as "WN" for west to north or "EW" for east to west. Every
channel segment has W tracks 0..W-1. The switch pattern is a function
pattern(kind, t, W) that returns the set of tracks of s2 that a switch joins
to track t of s.

A legal detailed routing gives each net one track on each segment of its
route, such that two nets that share a segment use different tracks there, and
the two tracks of every edge are joined by a switch.
"""

import itertools

from small_dpll import solve


def disjoint_pattern(kind: str, t: int, w: int) -> set[int]:
    """Track t meets only track t (the subset switch block)."""
    return {t}


def twisted_pattern(kind: str, t: int, w: int) -> set[int]:
    """Like the disjoint pattern, but the turn between the west and north sides joins track t to track w - 1 - t."""
    return {w - 1 - t} if kind in ("WN", "NW") else {t}


def encode(nets, w: int, pattern):
    """Return (number of variables, clauses, var) where var[(n, s, t)] is the variable of net n on track t of s."""
    var: dict[tuple[int, int, int], int] = {}
    for n, (segs, _) in enumerate(nets):  # @line L1
        for s in segs:
            for t in range(w):
                var[(n, s, t)] = len(var) + 1
    clauses: list[list[int]] = []
    for n, (segs, _) in enumerate(nets):
        for s in segs:
            clauses.append([var[(n, s, t)] for t in range(w)])  # @line L2
            for t, u in itertools.combinations(range(w), 2):
                clauses.append([-var[(n, s, t)], -var[(n, s, u)]])  # @line L3
    users: dict[int, list[int]] = {}
    for n, (segs, _) in enumerate(nets):
        for s in segs:
            users.setdefault(s, []).append(n)
    for s, ns in users.items():
        for n, m in itertools.combinations(ns, 2):
            for t in range(w):
                clauses.append([-var[(n, s, t)], -var[(m, s, t)]])  # @line L4
    for n, (segs, edges) in enumerate(nets):
        for s, s2, kind in edges:
            for t in range(w):
                clauses.append([-var[(n, s, t)]] + [var[(n, s2, u)] for u in sorted(pattern(kind, t, w))])  # @line L5
    return len(var), clauses, var


def sat_route(nets, w: int, pattern):
    """Return {(net, segment): track} for a legal detailed routing, or None if none exists at width w."""
    if w < 1:
        return None if any(segs for segs, _ in nets) else {}
    n_vars, clauses, var = encode(nets, w, pattern)
    model = solve(n_vars, clauses)  # @line L6
    if model is None:
        return None  # @line L7
    return {(n, s): t for (n, s, t), v in var.items() if model[v]}  # @line L8


def is_legal(nets, w: int, pattern, tracks) -> bool:
    for n, (segs, edges) in enumerate(nets):
        for s in segs:
            if not (0 <= tracks.get((n, s), -1) < w):
                return False
        for s, s2, kind in edges:
            if tracks[(n, s2)] not in pattern(kind, tracks[(n, s)], w):
                return False
    used: set[tuple[int, int]] = set()
    for n, (segs, _) in enumerate(nets):
        for s in segs:
            if (s, tracks[(n, s)]) in used:
                return False
            used.add((s, tracks[(n, s)]))
    return True


def exhaustive_route(nets, w: int, pattern):
    """Reference: try every assignment of tracks to the (net, segment) pairs."""
    keys = [(n, s) for n, (segs, _) in enumerate(nets) for s in segs]
    for choice in itertools.product(range(w), repeat=len(keys)):
        tracks = dict(zip(keys, choice))
        if is_legal(nets, w, pattern, tracks):
            return tracks
    return None


def min_width(nets, pattern, w_max: int):
    """Least w in 1..w_max at which the global routing has a legal detailed routing, or None."""
    for w in range(1, w_max + 1):
        if sat_route(nets, w, pattern) is not None:
            return w
    return None
small_dpll.py 68 lines
# SPDX-License-Identifier: MIT
# Shared helper of the fa1 eda pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""A small complete SAT solver: DPLL with unit propagation, for the tests and the examples.

A clause is a list of nonzero ints in DIMACS style. solve(n, clauses) returns
a list model with model[v] True or False for v = 1..n (model[0] is unused),
or None when the formula has no model.
"""


def solve(n: int, clauses):
    clauses = [list(dict.fromkeys(c)) for c in clauses]
    value: list = [None] * (n + 1)
    trail: list[int] = []

    def lit_value(lit: int):
        v = value[abs(lit)]
        return None if v is None else (v if lit > 0 else not v)

    def propagate() -> bool:
        changed = True
        while changed:
            changed = False
            for c in clauses:
                free = None
                n_free = 0
                sat = False
                for lit in c:
                    val = lit_value(lit)
                    if val is True:
                        sat = True
                        break
                    if val is None:
                        n_free += 1
                        free = lit
                if sat:
                    continue
                if n_free == 0:
                    return False
                if n_free == 1:
                    value[abs(free)] = free > 0
                    trail.append(abs(free))
                    changed = True
        return True

    def undo(mark: int) -> None:
        while len(trail) > mark:
            value[trail.pop()] = None

    def search() -> bool:
        if not propagate():
            return False
        var = next((v for v in range(1, n + 1) if value[v] is None), None)
        if var is None:
            return True
        for choice in (True, False):
            mark = len(trail)
            value[var] = choice
            trail.append(var)
            if search():
                return True
            undo(mark)
        return False

    if not search():
        return None
    return [False] + [bool(value[v]) for v in range(1, n + 1)]
test_sat_based_fpga_routing.py 129 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sat-based-fpga-routing/. The authors are listed in prov/1K07JP.jsonl.

import itertools
import random

from sat_based_fpga_routing import (
    disjoint_pattern,
    encode,
    exhaustive_route,
    is_legal,
    min_width,
    sat_route,
    twisted_pattern,
)
from small_dpll import solve

KINDS = ["WN", "NE", "ES", "SW", "EW", "NS"]
W_SIDE, N_SIDE, E_SIDE = 0, 1, 2
PAGE_NETS = [
    ([W_SIDE, N_SIDE], [(W_SIDE, N_SIDE, "WN")]),
    ([N_SIDE, E_SIDE], [(N_SIDE, E_SIDE, "NE")]),
    ([E_SIDE, W_SIDE], [(E_SIDE, W_SIDE, "EW")]),
]


def random_nets(rng, n_segments, n_nets, max_len):
    nets = []
    for _ in range(n_nets):
        segs = rng.sample(range(n_segments), rng.randint(1, max_len))
        edges = [(segs[rng.randrange(i)], segs[i], rng.choice(KINDS)) for i in range(1, len(segs))]
        nets.append((segs, edges))
    return nets


def random_pattern(rng, w):
    table = {(k, t): set(rng.sample(range(w), rng.randint(1, w))) for k in KINDS for t in range(w)}
    return lambda kind, t, width: table[(kind, t)]


def brute_sat(n, clauses):
    for bits in itertools.product([False, True], repeat=n):
        if all(any(bits[abs(l) - 1] == (l > 0) for l in c) for c in clauses):
            return True
    return False


def test_small_dpll_matches_truth_tables():
    rng = random.Random(9)
    for _ in range(300):
        n = rng.randint(1, 7)
        clauses = [[rng.choice([-1, 1]) * rng.randint(1, n) for _ in range(rng.randint(1, 3))] for _ in range(rng.randint(1, 20))]
        model = solve(n, clauses)
        assert (model is not None) == brute_sat(n, clauses)
        if model is not None:
            assert all(any(model[abs(l)] == (l > 0) for l in c) for c in clauses)


def test_page_example():
    n_vars, clauses, _ = encode(PAGE_NETS, 2, twisted_pattern)
    assert (n_vars, len(clauses)) == (12, 24)
    assert sat_route(PAGE_NETS, 2, disjoint_pattern) is None
    assert exhaustive_route(PAGE_NETS, 2, disjoint_pattern) is None
    assert min_width(PAGE_NETS, disjoint_pattern, 4) == 3
    tracks = sat_route(PAGE_NETS, 2, twisted_pattern)
    assert tracks is not None and is_legal(PAGE_NETS, 2, twisted_pattern, tracks)
    assert min_width(PAGE_NETS, twisted_pattern, 4) == 2


def test_agrees_with_exhaustive_search():
    rng = random.Random(1)
    sat = unsat = 0
    while sat < 60 or unsat < 60:
        w = rng.randint(1, 3)
        nets = random_nets(rng, 4, rng.randint(1, 4), 3)
        keys = sum(len(segs) for segs, _ in nets)
        if w ** keys > 5000:
            continue
        pattern = random_pattern(rng, w)
        got = sat_route(nets, w, pattern)
        want = exhaustive_route(nets, w, pattern)
        assert (got is None) == (want is None)
        if got is None:
            unsat += 1
        else:
            assert is_legal(nets, w, pattern, got)
            sat += 1


def test_models_correspond_one_to_one_to_routings():
    """The number of models of the CNF equals the number of legal detailed routings."""
    rng = random.Random(3)
    for _ in range(40):
        w = rng.randint(1, 3)
        nets = random_nets(rng, 3, rng.randint(1, 3), 2)
        pattern = random_pattern(rng, w)
        n_vars, clauses, _ = encode(nets, w, pattern)
        if n_vars > 14:
            continue
        models = sum(
            all(any(bits[abs(l) - 1] == (l > 0) for l in c) for c in clauses)
            for bits in itertools.product([False, True], repeat=n_vars)
        )
        keys = [(n, s) for n, (segs, _) in enumerate(nets) for s in segs]
        routings = sum(
            is_legal(nets, w, pattern, dict(zip(keys, choice))) for choice in itertools.product(range(w), repeat=len(keys))
        )
        assert models == routings


def test_disjoint_pattern_is_graph_coloring():
    """With the disjoint pattern a net keeps one track, so routability is W-colorability of the conflict graph."""
    rng = random.Random(2)
    for _ in range(150):
        nets = random_nets(rng, 5, rng.randint(2, 6), 3)
        conflicts = [(a, b) for a, b in itertools.combinations(range(len(nets)), 2) if set(nets[a][0]) & set(nets[b][0])]
        for w in (1, 2, 3):
            colorable = any(
                all(col[a] != col[b] for a, b in conflicts) for col in itertools.product(range(w), repeat=len(nets))
            )
            assert (sat_route(nets, w, disjoint_pattern) is not None) == colorable


def test_min_width_matches_exhaustive():
    rng = random.Random(4)
    for _ in range(40):
        nets = random_nets(rng, 3, rng.randint(1, 3), 2)
        want = next(w for w in range(1, 5) if exhaustive_route(nets, w, disjoint_pattern) is not None)
        assert min_width(nets, disjoint_pattern, 4) == want

History

Wood and Rutenbar (1998) wrote FPGA routing as a Boolean function and solved it with binary decision diagrams. Nam, Sakallah and Rutenbar (1999) wrote the routing constraints of a fixed global routing in conjunctive normal form and solved them with a search-based SAT solver instead, so that a failure became a proof of unroutability for that global routing; the journal version appeared in 2002. With Aloul, they compared track-based and route-based formulations in 2001 and 2004. Later work used SAT for other exact layout tasks, while production FPGA routers stayed with negotiated congestion.

References

  1. Gi-Joon Nam, Karem A. Sakallah and Rob A. Rutenbar, A new FPGA detailed routing approach via search-based Boolean satisfiability, IEEE Transactions on Computer-Aided Design of Integrated Circuits and Systems 21(6), 674 to 684, 2002, the routing constraints as a Boolean function (connectivity and exclusivity), their CNF form, and routability and unroutability results for a fixed global routing
  2. Gi-Joon Nam, Karem A. Sakallah and Rob A. Rutenbar, Satisfiability-based layout revisited, detailed routing of complex FPGAs via search-based Boolean SAT, Proceedings of the ACM/SIGDA International Symposium on Field Programmable Gate Arrays (FPGA '99), 167 to 175, 1999, the first version of the method
  3. Gi-Joon Nam, Fadi Aloul, Karem A. Sakallah and Rob A. Rutenbar, A comparative study of two Boolean formulations of FPGA detailed routing constraints, Proceedings of the International Symposium on Physical Design (ISPD), 2001; journal version in IEEE Transactions on Computers 53(6), 2004, the track-based and the route-based formulations and their comparison (general locator)
  4. R. Glenn Wood and Rob A. Rutenbar, FPGA routing and routability estimation via Boolean satisfiability, IEEE Transactions on Very Large Scale Integration Systems, 1998, the earlier Boolean formulation of FPGA routing, solved with binary decision diagrams (general locator)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.encode
  • a full proof of time.solve
  • a full proof of space.total
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