Algorithm Search⌘K

Algorithmcore

Negotiated congestion routing

Also called PathFinder.

McMurchie and Ebeling's router that reroutes all nets each round with costs raised on resources by present and past overuse, until no resource is shared.

Time
O(I (P E log V + m E)) worst
Space
O(E + m V) extra
Where
E = the number of grid edges; I = the number of iterations; P = the number of pins; V = the number of gcells; m = the number of nets
Properties
deterministicnot exactiterative
Origin
Larry McMurchie, Carl Ebeling, 1995

Negotiated congestion routing, introduced by McMurchie and Ebeling as the PathFinder router, is a form of rip-up and reroute for global routing and FPGA routing. In each iteration it rips up and reroutes every net with a shortest path search such as Dijkstra's algorithm. The cost of a resource is its base cost plus a history term that grows each time the resource is overused, times a present term that grows with the number of other nets on it now. Early iterations let nets share resources cheaply. Later iterations make sharing expensive, so the nets with good alternatives move away and the net that needs a resource most keeps it. There is no general proof that the loop reaches a legal routing; its success is measured on benchmarks.

In plain words

Imagine many drivers who all want the best roads. In the first round, each driver takes the shortest way and ignores the others, so some roads get too many cars.

Then every driver plans again, one after the other. A road that is too full now costs more, and a road that was too full in earlier rounds also costs more, as a memory of past jams. A driver with a good second road takes it. A driver with no other choice pays the price and stays.

Round after round the penalty for crowding grows, until each road carries no more cars than it can hold. The drivers do not talk to each other: they only react to the prices, so the price of each road sets who gets it.

The problem

The input is a global routing grid G=(V,E)G = (V, E) with an integer capacity cec_e on each edge, and mm nets, where net ii has a set TiT_i of terminal gcells with ∣Ti∣≥2|T_i| \ge 2 and P=∑i∣Ti∣P = \sum_i |T_i|. The output is a route RiR_i for each net, a tree in GG that holds all of TiT_i and whose leaves are terminals. The usage of edge ee is ue=∣{i:e∈Ri}∣u_e = |\{ i : e \in R_i \}|. The goal is a legal routing, ue≤ceu_e \le c_e for all ee, with small wirelength ∑i∣Ri∣\sum_i |R_i|. When no legal routing is found, the goal is the least total overflow ∑emax⁡(0,ue−ce)\sum_e \max(0, u_e - c_e). The exact definitions are on the global routing page.

PathFinder works on the routing-resource graph of an FPGA, where the resources are the nodes (wire segments and pins) and each node has capacity 1. This page puts the capacities on the edges of a gcell grid, the form that global routers use. The algorithm is the same.

The algorithm

The cost of edge ee when a net is routed is

cost(e)=(be+he)⋅pe,pe=1+pres_fac⋅max⁡(0, ue+1−ce),\mathrm{cost}(e) = (b_e + h_e) \cdot p_e, \qquad p_e = 1 + \mathrm{pres\_fac} \cdot \max(0,\ u_e + 1 - c_e),

where ueu_e counts the other nets on ee at that moment. Here beb_e is the base cost (1 on this page), heh_e is the history cost and pep_e is the present congestion penalty: it is 1 when one more net still fits on ee, and it grows with the overflow that this net would cause.

  1. NEGOTIATED-CONGESTION(G, c, nets T_1..T_m)
  2. 1h_e ← 0 for every edge e; pres_fac ← pres_first
  3. 2for it ← 1 to max_iters do
  4. 3for i ← 1 to m do
  5. 4rip up R_i: u_e ← u_e − 1 for each e in R_i
  6. 5cost(e) ← (b_e + h_e) · (1 + pres_fac · max(0, u_e + 1 − c_e)) for each e
  7. 6R_i ← ROUTE-TREE(T_i, cost)
  8. 7u_e ← u_e + 1 for each e in R_i
  9. 8record the routing if it is the best so far; if no edge has u_e > c_e then stop
  10. 9h_e ← h_e + hist_fac · max(0, u_e − c_e) for each e
  11. 10pres_fac ← pres_init if pres_fac = 0, else pres_fac · pres_mult
  12. 11return the best routing recorded

Route-Tree(Ti,cost)\textsf{Route-Tree}(T_i, \mathrm{cost}) grows a tree from one terminal. At each step it runs Dijkstra's algorithm with all tree gcells as sources at distance 0, stops at the nearest terminal that is not yet in the tree, and adds the path to that terminal. This is the expansion of PathFinder for one sink at a time. The defaults of the implementation are pres_first=0\mathrm{pres\_first} = 0, pres_init=1/2\mathrm{pres\_init} = 1/2, pres_mult=3/2\mathrm{pres\_mult} = 3/2 and hist_fac=1\mathrm{hist\_fac} = 1, all as exact fractions. With pres_first=0\mathrm{pres\_first} = 0 the first iteration routes every net by its cheapest tree and ignores the other nets.

Example

Take a 3×33 \times 3 grid of gcells (x,y)(x, y) with capacity 1 on each of its 12 edges. Net A joins (1,0)(1,0) and (0,1)(0,1). Net B joins (0,0)(0,0) and (2,2)(2,2). Ties in Dijkstra's algorithm go to the gcell with the lower index 3y+x3y + x.

Iteration 1. pres_fac=0\mathrm{pres\_fac} = 0 and h=0h = 0, so every edge costs 1.

  • A has two routes of cost 2. The tie goes to the route through the corner, on the edges (1,0)(0,0)(1,0)(0,0) and (0,0)(0,1)(0,0)(0,1).
  • B takes (0,0)(0,0), (1,0)(1,0), (2,0)(2,0), (2,1)(2,1), (2,2)(2,2), of cost 4.

The edge (0,0)(1,0)(0,0)(1,0) carries both nets: total overflow 1, wirelength 6. Line L9 sets h=1h = 1 on that edge, and line L10 sets pres_fac=1/2\mathrm{pres\_fac} = 1/2.

Iteration 2. Rip up A. B is on its 4 edges, so each of them has ue+1−ce=1u_e + 1 - c_e = 1 and pe=3/2p_e = 3/2.

edge b+hb + h pp cost
(0,0)(1,0)(0,0)(1,0) 2 3/2 3
other edges of B 1 3/2 3/2
all other edges 1 1 1

The corner route of A now costs 3+1=43 + 1 = 4, and the route through the center, on (1,0)(1,1)(1,0)(1,1) and (1,1)(0,1)(1,1)(0,1), costs 2. A moves to the center. Then rip up B. Its old route costs 2+1+1+1=52 + 1 + 1 + 1 = 5, since the history term stays on (0,0)(1,0)(0,0)(1,0). The route up the left column and along the top row costs 4, and every route through the edges of A costs at least 4+1/24 + 1/2. B moves to (0,0)(0,0), (0,1)(0,1), (0,2)(0,2), (1,2)(1,2), (2,2)(2,2).

Now no edge is overflowed, and the loop stops after 2 iterations with wirelength 6. An exhaustive search over all 8⋅12=968 \cdot 12 = 96 pairs of routes gives the same least wirelength for a legal routing. A single pass of sequential routing in the order A, B, where B avoids full edges when it can, ends with overflow 1: B has no free edge out of the corner. The order B, A works. Negotiation finds a legal routing here without a choice of order.

Correctness

The proof shows the following. It does not show that the loop reaches a legal routing, because that is not true in general.

  • Valid trees. Route-Tree\textsf{Route-Tree} returns a tree that holds all terminals of the net, and every leaf is a terminal.
  • Cheapest step. Each step of Route-Tree\textsf{Route-Tree} adds a cheapest path, under the current costs, from the tree to the nearest unreached terminal. All costs are at least be>0b_e > 0, so Dijkstra's algorithm applies.
  • Exact usage. After line L7, ueu_e is the number of nets whose route contains ee.
  • Legal on early stop. If the loop stops at line L8, the returned routing has no overflow. In every case it returns the routing with the least total overflow, then the least wirelength, of all iterations.
  • Growing penalties. heh_e never decreases, and it grows by at least hist_fac\mathrm{hist\_fac} in each iteration that ends with ee overflowed. pres_fac\mathrm{pres\_fac} never decreases after the first iteration.
  • Termination. The loop runs at most max_iters\mathrm{max\_iters} iterations, and each call of Route-Tree\textsf{Route-Tree} makes at most ∣Ti∣−1|T_i| - 1 searches.
Proof: Negotiated congestion routing builds valid trees, keeps exact usage counts, returns a legal routing when it stops early, and ends after at most max_iters iterationsfull

Let G=(V,E)G = (V, E) be the grid graph, connected, with capacities ce≥0c_e \ge 0. Every cost in the algorithm has the form (be+he)pe(b_e + h_e) p_e with be>0b_e > 0, he≥0h_e \ge 0 and pe≥1p_e \ge 1, so every cost is at least be>0b_e > 0. Write β=min⁡ebe>0\beta = \min_e b_e > 0.

Lemma 1 (one search step). Let SS be the node set of the current tree and LL the set of terminals not in SS, with L≠∅L \ne \emptyset. The search of Route-Tree\textsf{Route-Tree}, Dijkstra's algorithm with every node of SS as a source at distance 0, stops at a terminal t∈Lt \in L with the least distance from SS, and the path it traces back from tt is a cheapest path from SS to tt. Its nodes other than its first node are not in SS.

Proof. Join a new node zz to every node of SS by an edge of cost 0. Dijkstra's algorithm from zz on this graph is the multi-source search, and all other costs are positive, so it removes nodes from the heap in order of their distance from zz, which is their distance from SS, and the predecessor links give shortest paths (Dijkstra's algorithm). The search stops at the first removed node of LL, which has the least distance among the nodes of LL. Every node of SS has distance 0, and no relaxation can lower a distance below 0, so no node of SS gets a predecessor link. The trace back from tt follows predecessor links and stops at the first node of SS that it meets. So only the first node of the path is in SS. GG is connected, so some node of LL is reachable and the search does not run out of nodes before it stops. □\square

Lemma 2 (valid trees). Route-Tree(Ti,cost)\textsf{Route-Tree}(T_i, \mathrm{cost}) returns an edge set RiR_i that is a tree, holds every node of TiT_i, and has only terminals as leaves. It makes at most ∣Ti∣−1|T_i| - 1 searches.

Proof. The invariant is: the current edge set is a tree on the node set SS, every leaf of it is a terminal, and SS holds the first terminal. At the start, SS is the first terminal and there are no edges. A step adds a path whose first node is in SS and whose other nodes are new (Lemma 1). Adding a path that meets a tree in exactly one node gives a tree. The only new leaf is the last node tt, a terminal. The first node gets one more edge, so if it was a leaf it no longer is, and the inner nodes of the path have degree 2. So the invariant holds. Each step puts at least the terminal tt into SS, so after at most ∣Ti∣−1|T_i| - 1 steps every terminal is in SS and the loop ends. □\square

Lemma 3 (exact usage). At the start of line L4 for net ii, and after line L7, ue=∣{j:e∈Rj}∣u_e = |\{ j : e \in R_j \}| for every edge ee, where RjR_j is the current route of net jj (empty before net jj is first routed).

Proof. At the start all routes are empty and all ue=0u_e = 0. Line L4 subtracts 1 for each edge of the old RiR_i, so ueu_e then counts the nets other than ii. Line L7 adds 1 for each edge of the new RiR_i, and RiR_i is a set, so each edge gets at most 1 from net ii. So the count is exact after line L7, and it stays exact until the next line L4, because nothing else changes uu. □\square

By Lemma 3, ueu_e at line L5 counts the other nets on ee, so pe=1p_e = 1 exactly when one more net fits, ue+1≤ceu_e + 1 \le c_e, and pe−1p_e - 1 is pres_fac\mathrm{pres\_fac} times the overflow that net ii would cause on ee.

Lemma 4 (growing penalties). heh_e never decreases. If edge ee is overflowed at line L9 of an iteration, then heh_e grows by at least hist_fac\mathrm{hist\_fac} in that iteration. If pres_init>0\mathrm{pres\_init} > 0 and pres_mult≥1\mathrm{pres\_mult} \ge 1, then pres_fac\mathrm{pres\_fac} never decreases.

Proof. Line L9 adds hist_fac⋅max⁡(0,ue−ce)≥0\mathrm{hist\_fac} \cdot \max(0, u_e - c_e) \ge 0, and the max is at least 1 when ue>ceu_e > c_e, since the values are integers. Line L10 replaces 0 by pres_init>0\mathrm{pres\_init} > 0, or multiplies a positive value by pres_mult≥1\mathrm{pres\_mult} \ge 1. No other line changes hh or pres_fac\mathrm{pres\_fac}. □\square

Theorem (correctness and termination).

  1. Every returned route RiR_i is a tree that holds TiT_i, and its leaves are terminals.
  2. If the loop stops at line L8, the returned routing has ue≤ceu_e \le c_e for every edge.
  3. In every case the returned routing is, among the routings at the ends of the iterations that ran, one with the least total overflow and, among those, the least wirelength.
  4. The algorithm stops after at most max_iters\mathrm{max\_iters} iterations, and each iteration makes at most P−mP - m searches.

Proof. (1) is Lemma 2 for each call of line L6, and line L11 returns routes recorded at line L8, which are outputs of line L6. (2) At line L8 the usage is exact by Lemma 3. The stop happens only when no edge has ue>ceu_e > c_e. That routing has total overflow 0, the least possible, so it is recorded as the best, and it is returned. (3) Line L8 records the routing at the end of each iteration when its pair (total overflow, wirelength) is smaller in lexicographic order than the best pair so far. So the recorded routing is a lexicographic minimum over all iterations that ran. (4) The loop of line L2 runs at most max_iters\mathrm{max\_iters} times. Each net makes at most ∣Ti∣−1|T_i| - 1 searches by Lemma 2, and ∑i(∣Ti∣−1)=P−m\sum_i (|T_i| - 1) = P - m. Each search ends, since Dijkstra's algorithm removes each node at most once. □\square

What the theorem does not say. It does not say that the loop reaches total overflow 0 when a legal routing exists, and it gives no bound on the number of iterations needed. No such general result is known. The 2×22 \times 2 grid with capacity 1 and two nets between opposite corners shows that overflow 0 can be impossible: each route of one net meets each route of the other net in an edge, so the loop runs all max_iters\mathrm{max\_iters} iterations and returns overflow 1.

Complexity

  • One search. Dijkstra's algorithm with a binary heap takes O(Elog⁡V)O(E \log V) time on the grid.
  • One net. Route-Tree\textsf{Route-Tree} adds at least one terminal per search, so it makes at most ∣Ti∣−1|T_i| - 1 searches. Line L5 computes all edge costs in O(E)O(E) time. A router can update only the costs of the edges whose usage changed.
  • One iteration. Over all nets there are at most P−mP - m searches, so an iteration takes O(PElog⁡V+mE)O(P E \log V + m E) time. Lines L9 and L10 take O(E)O(E).
  • Whole run. O(I(PElog⁡V+mE))O(I (P E \log V + m E)) for II iterations. The number of iterations is not bounded by any proved function of the input; it is a parameter.
  • Space. O(E)O(E) for the costs, the usage and the history, and O(mV)O(m V) for the routes, since each tree has fewer than VV edges.

Properties

  • What is proved. Each net gets a valid tree, each search step is a cheapest path for the current costs, the usage counts are exact, a stop at line L8 means a legal routing, and the run ends after at most max_iters\mathrm{max\_iters} iterations.
  • What is not proved. There is no general proof that negotiated congestion reaches a legal routing when one exists, or that it reaches the least overflow. On the 2×22 \times 2 grid with capacity 1 and two nets between opposite corners, no legal routing exists, and the loop runs to its limit with overflow 1.
  • What is measured. NTHU-Route 2.0, built on this cost scheme, won the ISPD 2008 global routing contest, and its authors report routing 12 of the 16 ISPD 2008 benchmarks with no overflow. On 300 random toy instances made by the implementation's test generator with seed 2 (a 3×33 \times 3 grid, capacities drawn from 0, 1, 1, 2, and 2 or 3 nets), an exhaustive search found a legal routing for 141 of them. The implementation found a legal routing for all 141 within 30 iterations, and the least wirelength for 135. These are results on toy inputs, not benchmark results.
  • Deterministic. With exact costs and a fixed order of nets and ties, a run always gives the same routing.
  • Order of nets. The order still matters inside an iteration, but much less than in a single pass, because every net is rerouted in each iteration with the costs left by the others.
  • Relation to Lagrangian methods. The history term acts like a price on each edge that rises while the edge is overused, close in spirit to the multipliers of Lagrangian relaxation. This is an analogy, not a proof of convergence.

Variants and improvements

  • Timing-driven cost. PathFinder routes the connection from a source to sink jj with the cost Aijdn+(1−Aij)cnA_{ij} d_n + (1 - A_{ij}) c_n of resource nn, where dnd_n is its delay, cnc_n is the congestion cost above and Aij∈[0,1]A_{ij} \in [0, 1] is the criticality of the connection from static timing analysis. Critical connections take fast resources even when they are crowded.
  • Other cost forms. Some later routers multiply the base cost, the history cost and the present penalty instead of adding the first two, or they use an exponential present penalty. NTHU-Route 2.0 uses a history-based cost on a gcell grid with further changes of its own.
  • Search with a target. Replace Dijkstra's algorithm by A* search with the Manhattan distance to the target as the estimate, which visits fewer gcells.
  • Partial rip-up. Reroute only the nets that use an overflowed edge, not every net. This is faster per iteration, and global routers often do it after the first iterations.
  • Patterns first. Start from pattern routing, then negotiate only on the connections that still overflow.
  • Fractional start. Start from the rounded solution of multicommodity flow routing and negotiate away the overflow that the rounding leaves.

When to use it

  • FPGA routing, where every resource has capacity 1 and a legal routing is required.
  • Global routing of large netlists, where overflow must reach zero and a strong single-net search is available.
  • As the repair stage after a fast first routing, such as pattern routing or the rounding of a fractional solution.

When the run must have a proved bound, use the fractional method of multicommodity flow routing, whose fractional solution has a proved approximation ratio.

Pitfalls

  • Present penalty too large too soon. If pres_fac\mathrm{pres\_fac} is large in the first iteration, the first nets take the good resources and the later nets are pushed away, as in a single sequential pass. The usual schedule starts at 0 or at a small value and grows by a constant factor.
  • No history. Without the history term, two nets can trade the same two routes in every iteration.
  • Counting the current net. The present penalty must use the usage without the current net, which is why line L4 rips up the net before line L5 computes the costs. Otherwise a net pays for its own old route.
  • Shared edges inside one net. A tree uses each edge at most once, so a net adds 1 to the usage of an edge even when two of its connections pass there.
  • Unbounded history. In a long run the history terms grow without limit and dominate the base cost, so the routes get long. Routers bound the number of iterations, scale the history term or reset it.
  • Expecting a proof. The results are measured, not proved. A claim that the method "converges" holds only for the instances on which it was run.

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.

negotiated_congestion_routing.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/negotiated-congestion-routing/. The authors are listed in prov/V8CQHN.jsonl.

"""Negotiated congestion routing (PathFinder) on a global-routing grid.

The routing graph is a grid of width * height gcells. Node (x, y) has the
index y * width + x. Each edge between two neighbor gcells has an integer
capacity. A net is a list of distinct nodes. A route is a set of edge
indices that forms a tree in which every leaf is a pin of the net.

All costs are Fractions, and ties are broken by node index, so a run is
exact and gives the same result each time.
"""

import heapq
from fractions import Fraction
from typing import Sequence, Union

Edge = tuple[int, int]


def grid_edges(width: int, height: int) -> list[Edge]:
    """Edges (u, v) with u < v: first the horizontal edges, then the vertical edges."""
    edges = []
    for y in range(height):
        for x in range(width - 1):
            edges.append((y * width + x, y * width + x + 1))
    for y in range(height - 1):
        for x in range(width):
            edges.append((y * width + x, (y + 1) * width + x))
    return edges


def adjacency(n_nodes: int, edges: Sequence[Edge]) -> list[list[tuple[int, int]]]:
    """For each node, the list of (neighbor, edge index), sorted by neighbor."""
    adj: list[list[tuple[int, int]]] = [[] for _ in range(n_nodes)]
    for e, (u, v) in enumerate(edges):
        adj[u].append((v, e))
        adj[v].append((u, e))
    for lst in adj:
        lst.sort()
    return adj


def route_net(pins: Sequence[int], adj: list[list[tuple[int, int]]], cost: Sequence[Fraction]) -> frozenset[int]:
    """Grow a tree from the first pin. Each step runs Dijkstra from all tree nodes
    to the nearest pin that is not yet reached and adds that path to the tree."""
    tree_nodes = {pins[0]}
    tree_edges: set[int] = set()
    left = set(pins) - tree_nodes
    while left:
        dist = {v: Fraction(0) for v in tree_nodes}
        prev: dict[int, tuple[int, int]] = {}
        heap = [(Fraction(0), v) for v in sorted(tree_nodes)]
        heapq.heapify(heap)
        done: set[int] = set()
        target = -1
        while heap:
            d, u = heapq.heappop(heap)
            if u in done:
                continue
            done.add(u)
            if u in left:
                target = u
                break
            for v, e in adj[u]:
                nd = d + cost[e]
                if v not in dist or nd < dist[v]:
                    dist[v] = nd
                    prev[v] = (u, e)
                    heapq.heappush(heap, (nd, v))
        if target < 0:
            raise ValueError("a pin cannot be reached from the rest of the net")
        v = target
        while v not in tree_nodes:
            u, e = prev[v]
            tree_edges.add(e)
            tree_nodes.add(v)
            v = u
        left -= tree_nodes
    return frozenset(tree_edges)


def overflow_of(occ: Sequence[int], cap: Sequence[int]) -> int:
    """Total overflow: the sum over all edges of max(0, occupancy - capacity)."""
    return sum(max(0, o - c) for o, c in zip(occ, cap))


def occupancy(routes: Sequence[frozenset[int]], n_edges: int) -> list[int]:
    occ = [0] * n_edges
    for r in routes:
        for e in r:
            occ[e] += 1
    return occ


def negotiated_congestion_routing(
    width: int,
    height: int,
    cap: Union[int, Sequence[int]],
    nets: Sequence[Sequence[int]],
    max_iters: int = 50,
    pres_fac_first: Fraction = Fraction(0),
    pres_fac_init: Fraction = Fraction(1, 2),
    pres_fac_mult: Fraction = Fraction(3, 2),
    hist_fac: Fraction = Fraction(1),
    base: Fraction = Fraction(1),
) -> dict:
    """Route all nets with negotiated congestion.

    Returns a dict with the keys routes (one frozenset of edge indices per
    net), overflow, wirelength, iterations and log (a list of the pair
    (overflow, wirelength) after each iteration). The routes are those of the
    best iteration: least overflow, then least wirelength.
    """
    edges = grid_edges(width, height)
    m = len(edges)
    caps = [cap] * m if isinstance(cap, int) else list(cap)
    if len(caps) != m:
        raise ValueError("one capacity per edge is needed")
    adj = adjacency(width * height, edges)
    nets = [list(dict.fromkeys(p)) for p in nets]
    if not nets or max_iters < 1:
        return {"routes": [frozenset()] * len(nets), "overflow": 0, "wirelength": 0, "iterations": 0, "log": []}

    hist = [Fraction(0)] * m  # @line L1
    pres_fac = pres_fac_first
    occ = [0] * m
    routes: list[frozenset[int]] = [frozenset()] * len(nets)
    best = None
    log = []
    it = 0
    for it in range(1, max_iters + 1):  # @line L2
        for i, pins in enumerate(nets):  # @line L3
            for e in routes[i]:  # @line L4
                occ[e] -= 1
            cost = []
            for e in range(m):  # @line L5
                p = 1 + pres_fac * max(0, occ[e] + 1 - caps[e])
                cost.append((base + hist[e]) * p)
            routes[i] = route_net(pins, adj, cost) if len(pins) > 1 else frozenset()  # @line L6
            for e in routes[i]:  # @line L7
                occ[e] += 1
        ov = overflow_of(occ, caps)
        wl = sum(len(r) for r in routes)
        log.append((ov, wl))
        if best is None or (ov, wl) < best[0]:
            best = ((ov, wl), list(routes))
        if ov == 0:  # @line L8
            break
        for e in range(m):  # @line L9
            hist[e] += hist_fac * max(0, occ[e] - caps[e])
        pres_fac = pres_fac_init if pres_fac == 0 else pres_fac * pres_fac_mult  # @line L10
    assert best is not None
    (ov, wl), best_routes = best
    return {"routes": best_routes, "overflow": ov, "wirelength": wl, "iterations": it, "log": log}  # @line L11
test_negotiated_congestion_routing.py 179 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/negotiated-congestion-routing/. The authors are listed in prov/V8CQHN.jsonl.

import itertools
import random
from fractions import Fraction

from negotiated_congestion_routing import (
    adjacency,
    grid_edges,
    negotiated_congestion_routing,
    occupancy,
    overflow_of,
    route_net,
)


def is_route(width: int, height: int, pins: list[int], route: frozenset[int]) -> bool:
    """Checker: the edges form a tree that holds all pins, and every leaf is a pin."""
    edges = grid_edges(width, height)
    pins_set = set(pins)
    if len(pins_set) == 1:
        return not route
    deg: dict[int, int] = {}
    nbr: dict[int, list[int]] = {}
    for e in route:
        if not 0 <= e < len(edges):
            return False
        u, v = edges[e]
        for a, b in ((u, v), (v, u)):
            deg[a] = deg.get(a, 0) + 1
            nbr.setdefault(a, []).append(b)
    nodes = set(deg)
    if not pins_set <= nodes or len(route) != len(nodes) - 1:
        return False
    if any(d == 1 and v not in pins_set for v, d in deg.items()):
        return False
    start = next(iter(nodes))
    seen = {start}
    stack = [start]
    while stack:
        u = stack.pop()
        for v in nbr[u]:
            if v not in seen:
                seen.add(v)
                stack.append(v)
    return seen == nodes


_SUBTREES: dict[tuple[int, int], list[tuple[frozenset[int], frozenset[int], frozenset[int]]]] = {}


def subtrees(width: int, height: int) -> list[tuple[frozenset[int], frozenset[int], frozenset[int]]]:
    """Every nonempty edge subset of the grid that is a tree, with its nodes and its leaves."""
    if (width, height) not in _SUBTREES:
        edges = grid_edges(width, height)
        m = len(edges)
        out = []
        for mask in range(1, 1 << m):
            route = frozenset(e for e in range(m) if mask >> e & 1)
            nodes = frozenset(v for e in route for v in edges[e])
            if is_route(width, height, sorted(nodes), route):
                deg = {v: sum(v in edges[e] for e in route) for v in nodes}
                out.append((route, nodes, frozenset(v for v in nodes if deg[v] == 1)))
        _SUBTREES[(width, height)] = out
    return _SUBTREES[(width, height)]


def all_trees(width: int, height: int, pins: list[int]) -> list[frozenset[int]]:
    """Brute force: every edge subset of the grid that is a valid route of the net."""
    p = set(pins)
    return [r for r, nodes, leaves in subtrees(width, height) if p <= nodes and leaves <= p]


def brute_force(width: int, height: int, caps: list[int], nets: list[list[int]]) -> tuple[int, int]:
    """Least (total overflow, wirelength) over all combinations of routes."""
    m = len(grid_edges(width, height))
    cands = [all_trees(width, height, p) for p in nets]
    best = None
    for combo in itertools.product(*cands):
        key = (overflow_of(occupancy(combo, m), caps), sum(len(r) for r in combo))
        if best is None or key < best:
            best = key
    assert best is not None
    return best


def sequential(width: int, height: int, caps: list[int], nets: list[list[int]]) -> int:
    """Route the nets once, in order, each one on a shortest path that avoids full edges
    when it can. Return the total overflow."""
    edges = grid_edges(width, height)
    adj = adjacency(width * height, edges)
    occ = [0] * len(edges)
    big = Fraction(10**6)
    for pins in nets:
        cost = [Fraction(1) if occ[e] < caps[e] else big for e in range(len(edges))]
        for e in route_net(pins, adj, cost):
            occ[e] += 1
    return overflow_of(occ, caps)


def coords(width: int, route: frozenset[int], height: int = 3) -> list[tuple[tuple[int, int], tuple[int, int]]]:
    edges = grid_edges(width, height)
    return sorted(((u % width, u // width), (v % width, v // width)) for u, v in (edges[e] for e in route))


def test_example() -> None:
    # 3 x 3 grid, capacity 1. Net A joins (1,0) and (0,1). Net B joins (0,0) and (2,2).
    nets = [[1, 3], [0, 8]]
    assert sequential(3, 3, [1] * 12, nets) == 1
    assert sequential(3, 3, [1] * 12, nets[::-1]) == 0
    assert brute_force(3, 3, [1] * 12, nets) == (0, 6)
    r = negotiated_congestion_routing(3, 3, 1, nets)
    assert r["log"] == [(1, 6), (0, 6)]
    assert r["iterations"] == 2
    assert coords(3, r["routes"][0]) == [((0, 1), (1, 1)), ((1, 0), (1, 1))]
    assert coords(3, r["routes"][1]) == [((0, 0), (0, 1)), ((0, 1), (0, 2)), ((0, 2), (1, 2)), ((1, 2), (2, 2))]
    first = negotiated_congestion_routing(3, 3, 1, nets, max_iters=1)
    assert coords(3, first["routes"][0]) == [((0, 0), (0, 1)), ((0, 0), (1, 0))]


def test_single_net_is_shortest() -> None:
    rng = random.Random(3)
    for _ in range(50):
        w, h = rng.randrange(1, 7), rng.randrange(1, 7)
        if w * h < 2:
            continue
        s, t = rng.sample(range(w * h), 2)
        r = negotiated_congestion_routing(w, h, 1, [[s, t]])
        assert r["overflow"] == 0
        assert r["wirelength"] == abs(s % w - t % w) + abs(s // w - t // w)


def test_edges_cases() -> None:
    assert negotiated_congestion_routing(2, 2, 1, [])["routes"] == []
    r = negotiated_congestion_routing(2, 2, 1, [[3, 3]])
    assert r["routes"] == [frozenset()] and r["overflow"] == 0
    # Two nets on the only edge of a 2 x 1 grid with capacity 1 cannot both fit.
    r = negotiated_congestion_routing(2, 1, 1, [[0, 1], [1, 0]], max_iters=5)
    assert r["overflow"] == 1 and r["iterations"] == 5


def test_against_brute_force() -> None:
    rng = random.Random(1)
    legal = solved = 0
    for _ in range(80):
        caps = [rng.choice([0, 1, 1, 2]) for _ in range(12)]
        k = rng.choice([2, 3])
        nets = [rng.sample(range(9), rng.choice([2, 2, 3]) if k == 2 else 2) for _ in range(k)]
        best_ov, best_wl = brute_force(3, 3, caps, nets)
        r = negotiated_congestion_routing(3, 3, caps, nets, max_iters=30)
        for pins, route in zip(nets, r["routes"]):
            assert is_route(3, 3, pins, route)
        occ = occupancy(r["routes"], 12)
        assert r["overflow"] == overflow_of(occ, caps) >= best_ov
        assert r["wirelength"] == sum(len(x) for x in r["routes"])
        if r["overflow"] == 0:
            assert all(o <= c for o, c in zip(occ, caps))
            assert r["wirelength"] >= best_wl
        if best_ov == 0:
            legal += 1
            solved += r["overflow"] == 0
    # Measured on these seeds, not a theorem: every instance with a legal routing was solved.
    assert legal > 20 and solved == legal


def test_larger_grids_are_valid() -> None:
    rng = random.Random(7)
    for _ in range(4):
        w = h = 6
        m = len(grid_edges(w, h))
        caps = [rng.choice([1, 2]) for _ in range(m)]
        nets = [rng.sample(range(w * h), rng.choice([2, 3, 4])) for _ in range(12)]
        r = negotiated_congestion_routing(w, h, caps, nets, max_iters=20)
        for pins, route in zip(nets, r["routes"]):
            assert is_route(w, h, pins, route)
        assert r["overflow"] == min(ov for ov, _ in r["log"])
        again = negotiated_congestion_routing(w, h, caps, nets, max_iters=20)
        assert again == r

History

Ravi Nair described in 1987 a global router that rerouted every net in turn, with all others in place, over several passes. Larry McMurchie and Carl Ebeling presented PathFinder at FPGA '95. They added the history cost of past overuse to the present sharing cost, and gave the timing-driven form with criticality. PathFinder became the base of FPGA routers. For chip global routing, NTHU-Route 2.0 by Chang, Lee and Wang used a history-based cost on the gcell grid and won the ISPD 2008 global routing contest, and later global routers kept the same scheme.

References

  1. 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 cost of a node (b + h) p, the update of the history term, the growth of the present sharing factor and the timing term with criticality
  2. Yen-Jung Chang, Yu-Ting Lee and Ting-Chi Wang, NTHU-Route 2.0, a fast and stable global router, Proceedings of the IEEE/ACM International Conference on Computer-Aided Design (ICCAD), 338 to 343, 2008, the history-based cost function for rip-up and reroute on a gcell grid, and the results on the ISPD 2008 benchmarks
  3. Yen-Jung Chang, Yu-Ting Lee, Jhih-Rong Gao, Pei-Ci Wu and Ting-Chi Wang, NTHU-Route 2.0, a robust global router for modern designs, IEEE Transactions on Computer-Aided Design of Integrated Circuits and Systems 29(12), 1931 to 1944, 2010, the journal version, with the cost scheme and the experiments (general locator)
  4. Ravi Nair, A simple yet effective technique for global wiring, IEEE Transactions on Computer-Aided Design CAD-6(2), 165 to 172, 1987, the rerouting of every net in each pass with the other nets in place (general locator)
  5. Andrew B. Kahng, Jens Lienig, Igor L. Markov and Jin Hu, VLSI Physical Design, From Graph Partitioning to Timing Closure, second edition, Springer, 2022, Chapter 5, Section 5.8 Modern Global Routing (negotiated congestion routing; 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.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