Algorithm Search⌘K

Data structurecore

Routing resource graph

Also called RR graph.

A directed graph whose nodes are the wires and pins of an FPGA and whose edges are its programmable switches, on which FPGA routers search for paths.

Time
O(V + E) buildO(1) outO(k (V + E)) route_net
Space
O(V + E) graph
Where
E = the number of edges; V = the number of nodes; k = the number of sinks of a net
Properties
not concurrentnot externalnot persistent
Origin
Vaughn Betz, Jonathan Rose, 1997

A routing resource graph is a directed graph that holds every routing resource of an FPGA: each wire segment, each pin, and each source and sink of a logic block is a node, and each programmable switch that can drive one resource from another is a directed edge. Each node has a capacity, 1 for a wire or a pin, so a legal routing gives each net its own nodes. A router finds the route of a net as a tree in this graph and never needs to know the grid of the island-style FPGA, the switch block pattern or the connection block pattern. The structure belongs to the FPGA CAD topic of this sub-area.

In plain words

Think of every wire piece and every pin of the chip as a stop on a map, and of every switch as a one-way road from one stop to the next. A signal starts at the output of one block and must reach the inputs of other blocks by following roads.

Routing a net then means picking a set of stops that starts at the output and reaches every input the net needs, without two nets ever using the same stop. If two nets met on one wire, they would short each other.

The map hides how the chip is drawn. The same search code works whether the chip has short or long wires, or one switch pattern or another, because all of that is already in the roads.

The abstract type

The graph G=(V,E)G = (V, E) is built once from the architecture and then only read. Each node vv has a kind, a position, a track number when it is a wire, and a capacity c(v)≥1c(v) \ge 1. The kinds are:

  • SOURCE and SINK: the logical start of the output of a block and the logical end of one of its inputs.
  • OPIN and IPIN: an output pin and an input pin of a block.
  • CHANX and CHANY: one wire segment in a horizontal or a vertical channel.

The edges follow the electrical paths: SOURCE to OPIN, OPIN to wires through the output connection block, wire to wire through switch blocks, wire to IPIN through the input connection block, and IPIN to SINK.

A net ii is a source node sis_i and a set KiK_i of sink nodes. A route of net ii is a subgraph RiR_i of GG in which every node of KiK_i is reachable from sis_i. A routing of the nets is legal when no node is in more than c(v)c(v) of the routes; with all capacities 1, the node sets of the routes are pairwise disjoint. A route is minimal when no edge can be removed from it with all sinks still reachable from sis_i.

The operations are BUILD, OUT(v) (the list of edges that leave vv), and ROUTE-NET, the search that the routers of this page and of negotiated congestion routing run on it.

Representation

Nodes are numbered 00 to ∣V∣−1|V| - 1. Arrays give the kind, the position and the track of each node, and a hash map gives the number of a node from its key, such as (CHANX, xx, yy, tt). Each node keeps the list of its out-edges, which is an adjacency list. A real tool also stores the resistance and capacitance of each wire and the switch type of each edge, for the delays, and the base cost of each node for the router.

In the implementation, the array has nx×nyn_x \times n_y blocks, each with one output pin and PP input pins. All segments have length 1. The output pin drives tracks 00 to Fout−1F_{out} - 1 on each of the four sides of the block. Input pin pp reads the FinF_{in} tracks p,p+1,…p, p + 1, \ldots (mod WW) of the channel on side p mod 4p \bmod 4. Each switch block joins track tt on side aa to track πab(t)\pi_{ab}(t) on side bb, for each pair of sides that exist, in both directions. The patterns are the subset pattern ($\pi = $ identity), the pattern of the universal switch block, and an illustrative pattern in which turns change the track.

Operations

  1. BUILD(n_x, n_y, W, P, F_in, F_out, π)
  2. 1for each block (x, y): add SOURCE, OPIN, P IPIN and P SINK nodes, the edge SOURCE → OPIN and the edges IPIN_p → SINK_p
  3. 2for each channel piece and each track t: add one CHANX or CHANY node
  4. 3for each block and each of its 4 sides: add edges OPIN → tracks 0 to F_out − 1 of the channel piece on that side
  5. 4for each block and pin p: add edges from tracks p to p + F_in − 1 (mod W) of the piece on side p mod 4 → IPIN_p
  6. 5for each switch block, each pair of its sides (a, b) and each track t: add the edges (a, t) → (b, π_ab(t)) and back
  7. ROUTE-NET(G, s, K, used)
  8. 6tree ← {s}; route ← no edges
  9. 7for each sink k in K, in order:
  10. 8breadth-first search from all nodes of tree at once, entering only nodes that are in neither used nor tree, until k is found
  11. 9if k is not found then return FAIL
  12. 10follow the search links back from k to the first node of tree; add the path's nodes to tree and its edges to route
  13. 11return tree, route

ROUTE-NET is a maze search on the graph, the FPGA form of Lee's algorithm. With unit node costs, breadth-first search gives a path with the fewest edges; a router with costs uses Dijkstra's algorithm in line L8 instead. The caller adds the nodes of a returned tree to used, which reserves them for the net.

Example

Take nx=2n_x = 2, ny=1n_y = 1, W=2W = 2, P=1P = 1, Fin=2F_{in} = 2, Fout=1F_{out} = 1. The two blocks give 2⋅4=82 \cdot 4 = 8 pin, source and sink nodes, and the channels give 2(2⋅2+1⋅3)=142 (2 \cdot 2 + 1 \cdot 3) = 14 track nodes, so ∣V∣=22|V| = 22 and ∣E∣=56|E| = 56. Pin 0 of each block reads both tracks of the channel above it, and the output pin drives track 0 on all four sides.

Net aa goes from block (1,1)(1,1) to the input of block (2,1)(2,1), and net bb from block (2,1)(2,1) to the input of block (1,1)(1,1). They are routed in this order.

  • Net aa: SOURCE(1,1)(1,1), OPIN(1,1)(1,1), CHANX(1,1,0)(1,1,0), CHANX(2,1,0)(2,1,0), IPIN(2,1,0)(2,1,0), SINK(2,1,0)(2,1,0). The top channel goes straight across the switch block between the two blocks. The tree has 5 edges.
  • Net bb with the universal pattern: SOURCE(2,1)(2,1), OPIN(2,1)(2,1), CHANY(1,1,0)(1,1,0), CHANX(1,1,1)(1,1,1), IPIN(1,1,0)(1,1,0), SINK(1,1,0)(1,1,0). The vertical wire between the blocks turns left into the top channel, and the turn from the bottom side to the left side swaps track 0 to track 1, which is free.
  • Net bb with the subset pattern: FAIL. Every track that the output of block (2,1)(2,1) reaches is track 0, and the input of block (1,1)(1,1) can only be reached from track 0 through CHANX(1,1,0)(1,1,0), which net aa holds.

With the subset pattern, the reverse order fails too. Yet a legal routing exists: net aa goes around the bottom, through CHANX(1,0,0)(1,0,0), CHANX(2,0,0)(2,0,0), CHANY(2,1,0)(2,1,0) and CHANX(2,1,0)(2,1,0), and net bb takes CHANY(1,1,0)(1,1,0) and CHANX(1,1,0)(1,1,0). A shortest path for one net can block the next one, which is why routers rip up and reroute.

Correctness

The full proof shows the following.

  • Routings are disjoint trees. With capacity 1 on every node, a family of minimal routes is a legal routing if and only if it is a family of pairwise vertex-disjoint out-trees, one rooted at each source sis_i, each holding all of KiK_i and with only sinks as leaves. So searching for trees loses nothing.
  • ROUTE-NET is right. If it returns, the result is such a tree and avoids every node of used. It returns FAIL if and only if some sink of the net is not reachable from ss through nodes outside used, so the failure is real for that set of used nodes.
  • Shortest steps. Each path that line L10 adds has the fewest edges among the paths from the current tree to that sink through free nodes.

The router of one net is exact. Routing the nets one by one is not: as the example shows, a net can fail although a legal routing of all nets exists.

Proof: Minimal legal routings on a routing resource graph are exactly families of vertex-disjoint out-trees, and ROUTE-NET finds such a tree whenever one existsfull

Let G=(V,E)G = (V, E) be a routing resource graph with capacity 1 on every node. A net ii has a source sis_i and a nonempty set KiK_i of sinks, si∉Kis_i \notin K_i. An out-tree rooted at rr is a subgraph in which rr has in-degree 0, every other node has in-degree 1, and every node is reachable from rr; it has one edge fewer than it has nodes and no cycle. We take a subgraph to be its edge set together with its root, so its node set is {si}\{s_i\} and the ends of its edges.

Lemma 1. Let RR be a subgraph of GG with root ss in which every sink of KK is reachable from ss. Then RR is minimal (no edge can be removed with every sink of KK still reachable from ss) if and only if RR is an out-tree rooted at ss whose leaves are all in KK.

Proof. (⇐\Leftarrow) Let RR be such an out-tree and (u,v)(u, v) one of its edges. The subtree below vv is finite and nonempty, so it has a leaf, which is a sink kk. In an out-tree the only path from ss to kk passes through the unique in-edge of vv, since every node other than ss has exactly one in-edge. So removing (u,v)(u, v) makes kk unreachable, and no edge is removable.

(⇒\Rightarrow) Let RR be minimal. First, every edge (u,v)(u, v) of RR has uu reachable from ss in RR: otherwise no path from ss uses the edge, and it could be removed. So every node of RR is reachable. Take a breadth-first search tree AA of RR from ss: it is an out-tree rooted at ss, it uses only edges of RR, and it reaches every node of RR, in particular every sink. If RR had an edge outside AA, removing it would keep AA and so keep every sink reachable, against minimality. So R=AR = A is an out-tree. If a leaf vv of it were not a sink, its in-edge could be removed: only vv becomes unreachable, and v∉Kv \notin K. So every leaf is in KK. □\square

Theorem 2 (routings are disjoint trees). A family of minimal routes R1,…,RmR_1, \ldots, R_m is a legal routing if and only if the RiR_i are pairwise vertex-disjoint out-trees, RiR_i rooted at sis_i, holding all of KiK_i, with only sinks of KiK_i as leaves.

Proof. By Lemma 1, each minimal route is an out-tree of this kind, and each such out-tree is a minimal route. With capacity 1, the routing is legal exactly when no node is in two routes, that is, when the node sets are pairwise disjoint. □\square

The theorem also says that any legal routing contains a legal routing by such trees: removing edges from a route one at a time, while every sink stays reachable, ends in a minimal route after at most ∣E∣|E| steps, and removing edges never makes two node sets meet.

Lemma 3 (one search step). At line L8, let TT be the current tree, UU the set used, and F=V∖UF = V \setminus U the free nodes. The search finds kk if and only if kk is reachable from some node of TT by a path whose nodes after the first are in F∖TF \setminus T. When it finds kk, the path that line L10 follows back has the fewest edges among such paths, its first node is in TT, and its other nodes are not in TT.

Proof. Add a new node zz with an edge to each node of TT. The search of line L8 is a breadth-first search from zz in the graph induced on {z}∪T∪(F∖T)\{z\} \cup T \cup (F \setminus T), in which the nodes of TT are at distance 1 and are never entered again. Breadth-first search reaches exactly the nodes reachable from zz, and its search links give paths with the fewest edges (breadth-first search). A node of TT never gets a search link, since it is marked seen at the start. So the walk back from kk stops at the first node of TT that it meets, and every node before it is outside TT. □\square

Theorem 4 (ROUTE-NET). Let s∉Us \notin U. If ROUTE-NET(G,s,K,U)(G, s, K, U) returns, it returns an out-tree rooted at ss that holds KK, has only sinks of KK as leaves, and has no node in UU. It returns FAIL if and only if some k∈Kk \in K is not reachable from ss in the subgraph induced by F=V∖UF = V \setminus U.

Proof. The invariant of the loop of line L7 is: tree and route form an out-tree rooted at ss, every node of it is in FF, every leaf is a sink of KK, and every node of it is reachable from ss in FF. It holds at the start, with the single node s∈Fs \in F. By Lemma 3, a step adds a path whose first node is in the tree and whose other nodes are new and free. Adding such a path to an out-tree keeps an out-tree: each new node gets one in-edge, and it is reachable through the first node. The only new leaf is kk, and the first node of the path, if it was a leaf, now has an out-edge. So the invariant holds after line L10, and when the loop ends, every k∈Kk \in K is in the tree.

If the search fails for some kk, Lemma 3 says that no path from the tree to kk runs through free nodes outside the tree. Suppose kk were reachable from ss in FF, by a path PP. The path starts in the tree. Let uu be its last node in the tree; the rest of PP after uu avoids the tree, is free, and ends at kk, a contradiction. So kk is not reachable from ss in FF. Conversely, if every kk is reachable from ss in FF, then at each step kk is reachable from the tree by the same argument, so the search finds it, and the procedure does not fail. □\square

Corollary 5. Route the nets one by one with ROUTE-NET, adding the nodes of each returned tree to UU. The returned trees form a legal routing of the nets that did not fail, and each tree is minimal for its net.

Proof. Each tree avoids the UU of its call, which holds all earlier trees, so the trees are pairwise disjoint. By Theorem 4 each is an out-tree of the right kind, and by Lemma 1 it is minimal. Theorem 2 then gives legality. ■\blacksquare

Complexity

  • Size. With unit-length segments, the implementation has ∣V∣=nxny(2+2P)+W(nx(ny+1)+ny(nx+1))|V| = n_x n_y (2 + 2P) + W (n_x (n_y + 1) + n_y (n_x + 1)) nodes. A switch block with ss sides adds Ws(s−1)W s (s - 1) directed edges, and each block adds 1+P+4Fout+PFin1 + P + 4 F_{out} + P F_{in} more. The test checks these closed forms.
  • BUILD adds each node and edge once, in O(∣V∣+∣E∣)O(|V| + |E|) time and space.
  • OUT(v) is a list, so a search reads each edge in O(1)O(1).
  • ROUTE-NET runs one breadth-first search per sink, each in O(∣V∣+∣E∣)O(|V| + |E|), so O(k(∣V∣+∣E∣))O(k (|V| + |E|)) for kk sinks. With Dijkstra's algorithm and a binary heap, each search takes O(∣E∣log⁡∣V∣)O(|E| \log |V|).

For a square array of nn blocks, ∣V∣|V| and ∣E∣|E| grow as Θ(nW)\Theta(n W) for fixed PP, FinF_{in} and FoutF_{out}, so the graph of a large FPGA has millions of nodes, and memory is a real limit of the method.

Variants

  • Longer segments. A node of a segment of length LL spans LL blocks. Switch blocks then join segment ends and, in some patterns, the middle of a segment.
  • Single-driver wires. Each segment is driven by one multiplexer at its start, so the edges into a node are the inputs of its multiplexer. The graph stays the same kind of object.
  • Equivalent pins. When the inputs of a cluster are logically equivalent, as with a full local crossbar, VPR uses one SINK node per block with capacity equal to the number of equivalent pins. The disjoint tree statement then holds for every node except such sinks.
  • Edges with switches as nodes. Some tools make each switch a node too, so that switches can have their own cost and capacity.
  • Inside the cluster. The local crossbar of a logic cluster can be added as more nodes and edges, which is what an architecture-aware packer routes on.

When to use it

Use a routing resource graph whenever a router must work on more than one FPGA architecture, or on an architecture with irregular parts such as memory columns and long wires. Routers such as negotiated congestion routing and the binary search for the minimum channel width all work on it. For a fixed regular array with one pattern, a direct grid model is smaller, but it ties the router to that array. Exact methods such as SAT-based FPGA routing need fewer variables when they work on the tracks of a fixed global routing instead of the whole graph.

Pitfalls

  • Edges in one direction only. A switch between two bidirectional wires needs two directed edges. With one edge, the router misses half of the paths.
  • Capacity on edges. In an FPGA, nets conflict on wires, not on switches. A model with capacities on edges lets two nets share a wire. Put the capacity on nodes.
  • Routing through a pin. IPIN nodes lead only to their SINK, and SOURCE nodes have no in-edges, so no route can pass through another block. A graph that joins pins in other ways can make routes that pass through a block.
  • Sharing a node inside one net. A net uses a node once even when two of its sinks pass through it. Count usage per net, not per path.
  • Order of nets. A router that routes the nets once, in a fixed order, can fail on a routable instance, as in the example.

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.

routing_resource_graph.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/routing-resource-graph/. The authors are listed in prov/4ASKQ1.jsonl.

"""Routing resource graph of a small island-style FPGA.

The array has nx * ny logic blocks at (x, y), 1 <= x <= nx, 1 <= y <= ny.
Each block has one output pin and `pins` input pins. Each channel piece has
W tracks, and every wire segment has length 1. A node is a pin, a source, a
sink or a track segment, and each node has capacity 1. A directed edge is a
switch that can drive the head from the tail.

Node keys:
  ("SOURCE", x, y), ("OPIN", x, y), ("IPIN", x, y, p), ("SINK", x, y, p),
  ("CHANX", x, y, t) for 1 <= x <= nx, 0 <= y <= ny (above row y),
  ("CHANY", x, y, t) for 0 <= x <= nx, 1 <= y <= ny (right of column x).
"""

from collections import deque
from typing import Optional

# The four sides of a switch block, and its six pairs of sides.
PAIRS = [("T", "R"), ("T", "B"), ("T", "L"), ("R", "B"), ("R", "L"), ("B", "L")]


def track_map(pattern: str, a: str, b: str, t: int, w: int) -> int:
    """Track on side b that the switch block joins to track t on side a.

    (a, b) is one of PAIRS. Each map is a permutation of range(w).
    """
    if pattern == "subset":
        return t
    if pattern == "universal":
        # Pairs of tracks {2q, 2q + 1}; the turns T-R and B-L swap inside a pair.
        if (a, b) in (("T", "R"), ("B", "L")) and t < 2 * (w // 2):
            return t ^ 1
        return t
    if pattern == "turning":
        # An illustrative pattern in which turns change the track.
        if (a, b) in (("T", "B"), ("R", "L")):
            return t
        if (a, b) in (("T", "R"), ("B", "L")):
            return (t + 1) % w
        return w - 1 - t
    raise ValueError("unknown pattern " + pattern)


class RoutingResourceGraph:
    """A directed graph of the routing resources, built once, then read."""

    def __init__(
        self,
        nx: int,
        ny: int,
        w: int,
        pins: int,
        fc_in: int,
        fc_out: int,
        pattern: str = "universal",
    ) -> None:
        if not (1 <= fc_in <= w and 1 <= fc_out <= w):
            raise ValueError("need 1 <= fc <= W")
        self.nx, self.ny, self.w, self.pins = nx, ny, w, pins
        self.fc_in, self.fc_out, self.pattern = fc_in, fc_out, pattern
        self.keys: list[tuple] = []
        self.index: dict[tuple, int] = {}
        self.out: list[list[int]] = []
        self._build()

    # Building blocks.

    def _add_node(self, key: tuple) -> int:
        self.index[key] = len(self.keys)
        self.keys.append(key)
        self.out.append([])
        return self.index[key]

    def _add_edge(self, a: tuple, b: tuple) -> None:
        self.out[self.index[a]].append(self.index[b])

    def _side_channel(self, x: int, y: int, side: int, t: int) -> tuple:
        """Track t of the channel piece on side 0 top, 1 right, 2 bottom, 3 left of block (x, y)."""
        if side == 0:
            return ("CHANX", x, y, t)
        if side == 1:
            return ("CHANY", x, y, t)
        if side == 2:
            return ("CHANX", x, y - 1, t)
        return ("CHANY", x - 1, y, t)

    def _sb_sides(self, i: int, j: int) -> dict[str, tuple]:
        """The channel pieces that meet at switch block (i, j), by side, as key prefixes."""
        sides = {}
        if j + 1 <= self.ny:
            sides["T"] = ("CHANY", i, j + 1)
        if j >= 1:
            sides["B"] = ("CHANY", i, j)
        if i >= 1:
            sides["L"] = ("CHANX", i, j)
        if i + 1 <= self.nx:
            sides["R"] = ("CHANX", i + 1, j)
        return sides

    def _build(self) -> None:
        nx, ny, w, pins = self.nx, self.ny, self.w, self.pins
        blocks = [(x, y) for y in range(1, ny + 1) for x in range(1, nx + 1)]
        for x, y in blocks:  # @line L1
            self._add_node(("SOURCE", x, y))
            self._add_node(("OPIN", x, y))
            self._add_edge(("SOURCE", x, y), ("OPIN", x, y))
            for p in range(pins):
                self._add_node(("IPIN", x, y, p))
                self._add_node(("SINK", x, y, p))
                self._add_edge(("IPIN", x, y, p), ("SINK", x, y, p))
        for t in range(w):  # @line L2
            for y in range(ny + 1):
                for x in range(1, nx + 1):
                    self._add_node(("CHANX", x, y, t))
            for x in range(nx + 1):
                for y in range(1, ny + 1):
                    self._add_node(("CHANY", x, y, t))
        for x, y in blocks:  # @line L3
            for side in range(4):
                for t in range(self.fc_out):
                    self._add_edge(("OPIN", x, y), self._side_channel(x, y, side, t))
        for x, y in blocks:  # @line L4
            for p in range(pins):
                for j in range(self.fc_in):
                    t = (p + j) % w
                    self._add_edge(self._side_channel(x, y, p % 4, t), ("IPIN", x, y, p))
        for i in range(nx + 1):  # @line L5
            for j in range(ny + 1):
                sides = self._sb_sides(i, j)
                for a, b in PAIRS:
                    if a in sides and b in sides:
                        for t in range(w):
                            u = sides[a] + (t,)
                            v = sides[b] + (track_map(self.pattern, a, b, t, w),)
                            self._add_edge(u, v)
                            self._add_edge(v, u)

    # Queries.

    def num_nodes(self) -> int:
        return len(self.keys)

    def num_edges(self) -> int:
        return sum(len(o) for o in self.out)

    def node(self, key: tuple) -> int:
        return self.index[key]

    def edges(self) -> set[tuple[int, int]]:
        return {(u, v) for u in range(len(self.out)) for v in self.out[u]}

    def check_invariant(self) -> None:
        """Raise AssertionError if the graph breaks the rules of its node kinds."""
        allowed = {
            "SOURCE": {"OPIN"},
            "OPIN": {"CHANX", "CHANY"},
            "CHANX": {"CHANX", "CHANY", "IPIN"},
            "CHANY": {"CHANX", "CHANY", "IPIN"},
            "IPIN": {"SINK"},
            "SINK": set(),
        }
        es = self.edges()
        assert len(es) == self.num_edges(), "parallel edge"
        for u, v in es:
            ku, kv = self.keys[u][0], self.keys[v][0]
            assert kv in allowed[ku], (self.keys[u], self.keys[v])
            if ku in ("CHANX", "CHANY") and kv in ("CHANX", "CHANY"):
                assert (v, u) in es, "a switch between tracks must work both ways"
        for k, i in self.index.items():
            assert self.keys[i] == k

    # Routing of one net on the graph.

    def route_net(
        self, source: int, sinks: list[int], used: set[int]
    ) -> Optional[tuple[set[int], list[tuple[int, int]]]]:
        """Grow a tree from source to every sink through nodes not in used.

        Returns (nodes, edges) of the tree, or None when some sink cannot be
        reached. The caller adds the nodes to used to reserve them.
        """
        if source in used:
            return None
        tree = {source}  # @line L6
        tree_edges: list[tuple[int, int]] = []
        for k in sinks:  # @line L7
            if k in tree:
                continue
            pred: dict[int, int] = {}
            seen = set(tree)
            queue = deque(sorted(tree))
            found = False
            while queue and not found:  # @line L8
                u = queue.popleft()
                for v in self.out[u]:
                    if v in seen or v in used:
                        continue
                    seen.add(v)
                    pred[v] = u
                    if v == k:
                        found = True
                        break
                    queue.append(v)
            if not found:  # @line L9
                return None
            v = k  # @line L10
            while v not in tree:
                u = pred[v]
                tree_edges.append((u, v))
                tree.add(v)
                v = u
        return tree, tree_edges  # @line L11

    def route_all(
        self, nets: list[tuple[int, list[int]]]
    ) -> list[Optional[tuple[set[int], list[tuple[int, int]]]]]:
        """Route the nets one after the other; a net that fails gets None."""
        used: set[int] = set()
        result = []
        for source, sinks in nets:
            r = self.route_net(source, sinks, used)
            if r is not None:
                used |= r[0]
            result.append(r)
        return result


def expected_counts(nx: int, ny: int, w: int, pins: int, fc_in: int, fc_out: int) -> tuple[int, int]:
    """Closed forms for the number of nodes and of directed edges."""
    nb = nx * ny
    segments = w * (nx * (ny + 1) + ny * (nx + 1))
    nodes = nb * (2 + 2 * pins) + segments
    sb = 0
    for i in range(nx + 1):
        for j in range(ny + 1):
            s = (i >= 1) + (i <= nx - 1) + (j >= 1) + (j <= ny - 1)
            sb += w * s * (s - 1)
    edges = nb * (1 + pins) + nb * 4 * fc_out + nb * pins * fc_in + sb
    return nodes, edges
test_routing_resource_graph.py 190 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/routing-resource-graph/. The authors are listed in prov/4ASKQ1.jsonl.

import random

from routing_resource_graph import PAIRS, RoutingResourceGraph, expected_counts, track_map

PATTERNS = ["subset", "universal", "turning"]


def random_graph(rng: random.Random) -> RoutingResourceGraph:
    w = rng.randint(1, 3)
    return RoutingResourceGraph(
        rng.randint(1, 3),
        rng.randint(1, 3),
        w,
        rng.randint(1, 3),
        rng.randint(1, w),
        rng.randint(1, w),
        rng.choice(PATTERNS),
    )


def random_nets(g: RoutingResourceGraph, rng: random.Random) -> list[tuple[int, list[int]]]:
    blocks = [(x, y) for x in range(1, g.nx + 1) for y in range(1, g.ny + 1)]
    sinks = [(x, y, p) for x, y in blocks for p in range(g.pins)]
    rng.shuffle(blocks)
    rng.shuffle(sinks)
    nets = []
    for x, y in blocks[: rng.randint(1, len(blocks))]:
        k = rng.randint(1, 3)
        mine = [s for s in sinks if (s[0], s[1]) != (x, y)][:k]
        if not mine:
            continue
        for s in mine:
            sinks.remove(s)
        nets.append((g.node(("SOURCE", x, y)), [g.node(("SINK",) + s) for s in mine]))
    return nets


def reachable(g: RoutingResourceGraph, start: int, blocked: set[int]) -> set[int]:
    """Plain depth-first search, written apart from the router."""
    if start in blocked:
        return set()
    seen = {start}
    stack = [start]
    while stack:
        u = stack.pop()
        for v in g.out[u]:
            if v not in seen and v not in blocked:
                seen.add(v)
                stack.append(v)
    return seen


def is_out_tree(edges: set[tuple[int, int]], nodes: set[int], root: int, sinks: list[int]) -> bool:
    """The edges form an out-tree on nodes, rooted at root, whose leaves are sinks."""
    indeg = {v: 0 for v in nodes}
    outdeg = {v: 0 for v in nodes}
    for u, v in edges:
        if u not in nodes or v not in nodes:
            return False
        indeg[v] += 1
        outdeg[u] += 1
    if indeg[root] != 0 or any(indeg[v] != 1 for v in nodes if v != root):
        return False
    if len(edges) != len(nodes) - 1:
        return False
    adj: dict[int, list[int]] = {v: [] for v in nodes}
    for u, v in edges:
        adj[u].append(v)
    seen = {root}
    stack = [root]
    while stack:
        u = stack.pop()
        for v in adj[u]:
            if v not in seen:
                seen.add(v)
                stack.append(v)
    if seen != nodes or not set(sinks) <= nodes:
        return False
    leaves = {v for v in nodes if outdeg[v] == 0 and v != root}
    return leaves <= set(sinks)


def test_counts_match_closed_forms():
    for nx in range(1, 4):
        for ny in range(1, 4):
            for w in range(1, 5):
                for pins in range(1, 4):
                    for pattern in PATTERNS:
                        fc = (w + 1) // 2
                        g = RoutingResourceGraph(nx, ny, w, pins, fc, w, pattern)
                        g.check_invariant()
                        assert (g.num_nodes(), g.num_edges()) == expected_counts(nx, ny, w, pins, fc, w)


def test_track_maps_are_permutations():
    for w in range(1, 7):
        for pattern in PATTERNS:
            for a, b in PAIRS:
                assert sorted(track_map(pattern, a, b, t, w) for t in range(w)) == list(range(w))


def test_example_of_the_page():
    def path(g, keys):
        return [g.node(k) for k in keys]

    for pattern in ("universal", "subset"):
        g = RoutingResourceGraph(2, 1, 2, 1, 2, 1, pattern)
        assert (g.num_nodes(), g.num_edges()) == (22, 56)
        a = (g.node(("SOURCE", 1, 1)), [g.node(("SINK", 2, 1, 0))])
        b = (g.node(("SOURCE", 2, 1)), [g.node(("SINK", 1, 1, 0))])
        r = g.route_all([a, b])
        assert r[0] is not None and len(r[0][1]) == 5
        if pattern == "universal":
            assert r[1] is not None
            assert ("CHANX", 1, 1, 1) in {g.keys[v] for v in r[1][0]}
        else:
            # Both orders fail when routed one net at a time ...
            assert r[1] is None
            assert g.route_all([b, a])[1] is None
            # ... but a legal routing exists: net a goes around the bottom.
            p1 = path(g, [("SOURCE", 1, 1), ("OPIN", 1, 1), ("CHANX", 1, 0, 0), ("CHANX", 2, 0, 0), ("CHANY", 2, 1, 0), ("CHANX", 2, 1, 0), ("IPIN", 2, 1, 0), ("SINK", 2, 1, 0)])
            p2 = path(g, [("SOURCE", 2, 1), ("OPIN", 2, 1), ("CHANY", 1, 1, 0), ("CHANX", 1, 1, 0), ("IPIN", 1, 1, 0), ("SINK", 1, 1, 0)])
            es = g.edges()
            assert all(e in es for p in (p1, p2) for e in zip(p, p[1:]))
            assert not set(p1) & set(p2)


def test_routes_are_disjoint_trees_and_failures_are_real():
    rng = random.Random(4)
    routed = failed = 0
    for _ in range(600):
        g = random_graph(rng)
        nets = random_nets(g, rng)
        result = g.route_all(nets)
        used: set[int] = set()
        es = g.edges()
        for (source, sinks), r in zip(nets, result):
            if r is None:
                # The router gives up only if some sink is out of reach of the source.
                reach = reachable(g, source, used)
                assert not set(sinks) <= reach
                failed += 1
                continue
            nodes, edges = r
            assert nodes.isdisjoint(used)
            assert set(edges) <= es
            assert len(set(edges)) == len(edges)
            assert is_out_tree(set(edges), nodes, source, sinks)
            used |= nodes
            routed += 1
    assert routed > 500 and failed > 0


def test_each_new_path_is_shortest_from_the_tree():
    rng = random.Random(9)
    for _ in range(200):
        g = random_graph(rng)
        nets = random_nets(g, rng)
        if not nets:
            continue
        source, sinks = nets[0]
        r = g.route_net(source, sinks[:1], set())
        if r is None:
            # Possible with the subset pattern and few pin connections.
            assert sinks[0] not in reachable(g, source, set())
            continue
        nodes, edges = r
        # Breadth-first distance from the source, computed apart from the router.
        dist = {source: 0}
        layer = [source]
        while layer:
            nxt = []
            for u in layer:
                for v in g.out[u]:
                    if v not in dist:
                        dist[v] = dist[u] + 1
                        nxt.append(v)
            layer = nxt
        assert len(edges) == dist[sinks[0]]


def test_subset_pattern_keeps_the_track():
    g = RoutingResourceGraph(2, 2, 3, 1, 1, 1, "subset")
    for u, v in g.edges():
        ku, kv = g.keys[u], g.keys[v]
        if ku[0] in ("CHANX", "CHANY") and kv[0] in ("CHANX", "CHANY"):
            assert ku[3] == kv[3]

History

McMurchie and Ebeling's PathFinder (1995) routed FPGAs on a graph whose nodes are wires and pins, with capacity 1 per node. Betz and Rose built VPR around a routing resource graph that the tool generates from a short description of the architecture: the channel width, the segment lengths, FcF_c, FsF_s and the switch block pattern. Their book (1999, Chapter 4) describes the node kinds and how the graph is built. This let the same router compare many architectures, and the graph remains the routing model of the VTR flow.

References

  1. Vaughn Betz, Jonathan Rose and Alexander Marquardt, Architecture and CAD for Deep-Submicron FPGAs, Kluwer, 1999 (doi 10.1007/978-1-4615-5145-4), Chapter 4, Section 4.2 Architecture Parameterization and Generation (the routing resource graph with SOURCE, OPIN, CHANX, CHANY, IPIN and SINK nodes, and node capacities) and Section 4.3 Routability-Driven Router
  2. Larry McMurchie and Carl Ebeling, PathFinder, a negotiation-based performance-driven router for FPGAs, Proceedings of the ACM Symposium on Field-Programmable Gate Arrays (FPGA '95), 111 to 117, 1995, the routing graph with wires and pins as nodes of capacity 1, and routes as trees in it
  3. Vaughn Betz and Jonathan Rose, VPR, a new packing, placement and routing tool for FPGA research, Field-Programmable Logic and Applications (FPL 1997), Lecture Notes in Computer Science 1304, Springer, 1997, the description of VPR and its architecture-driven router (general locator)
  4. Jason Luu and others, VTR 7.0, next generation architecture and CAD system for FPGAs, ACM Transactions on Reconfigurable Technology and Systems 7(2), 2014, the routing resource graph of the VTR flow (general locator)

Where this leads

About this page

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

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.build
  • a full proof of time.out
  • a full proof of time.route_net
  • a full proof of space.graph
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)
WritingW4 complete
  • a review of the text: no review record reviews/4ASKQ1/text.yaml