Algorithm Search⌘K

Algorithmcore

Greedy channel router

Also called Rivest-Fiduccia router.

Rivest and Fiduccia's router that scans the channel column by column and greedily joins, splits and jogs nets, and always completes by extending past the end.

Time
O((n + E) T^2) worst
Space
Θ(T + N) extra
Where
E = the number of extension columns; N = the number of nets; T = the number of tracks used; n = the number of columns
Properties
deterministicnot exactiterative
Origin
Ronald L. Rivest, Charles M. Fiduccia, 1982

The greedy channel router solves the channel routing problem by a scan from left to right, one column at a time. Unlike the left-edge algorithm, it does not assign whole nets to tracks. It keeps, for each track, the net that runs on it at the current column, and in each column it makes a few local moves: it brings the pins of the column onto tracks, joins the tracks of nets that are split over several tracks, moves nets toward the side of their next pin, and frees the tracks of nets that are done. A net may change track in any column where the vertical layer is free. If nets are still split after the last column, the router goes on in extra columns past the right end. So it always finishes, also when the vertical constraint graph has a cycle. The number of tracks is a measured result, not a proved one.

In plain words

Walk along the corridor from one end to the other, one step at a time. At each step, you hold the ropes that are already laid in their lanes.

When a door on the north or south wall comes up, bring its rope into the nearest lane that is free or already holds a rope of that color. If a color sits in two lanes, join the two lanes with a short rope across the corridor as soon as the way is clear, and free one lane. If a rope must reach a door on the south wall soon, move it to a lane near the south wall when you can.

When a color has no doors left, free its lane. If at the end of the corridor some color still sits in two lanes, keep walking past the end until they are joined.

The problem

The input is a channel with columns 1,…,n1, \ldots, n and a top and a bottom pin in each column, as on the page on the channel routing problem. The model is the reserved two-layer model with jogs in any column: trunks run on tracks on layer H, and vertical wires on layer V, and a net may use vertical wires in any column, not only at its pins. Wires may also go on to the right of column nn, in extension columns that hold no pins.

The output is a legal routing, with its number of tracks TT and its number of extension columns EE. The goal is a small TT with E=0E = 0, but the router puts completion first.

The algorithm

  1. GREEDY-CHANNEL(top, bot)
  2. 1make d empty tracks, where d is the channel density; c ← 1
  3. 2while c ≤ n or some track holds a net do
  4. 3bring in the pins of column c: each goes to the nearest track, from its own edge, that is empty or holds its net; if the two branches would meet, the shorter one stays and the other pin gets a new track at the edge of its side
  5. 4join split nets: add vertical jogs in column c between tracks of the same net, shortest first, where layer V is free; in each joined set keep the track on the side of the next pin and free the others
  6. 5move nets: each net on one track jogs toward the side of its next pin, to the farthest empty track it can reach in column c
  7. 6free the track of each net that is on one track and has no pin to the right of c
  8. 7c ← c + 1
  9. 8remove the tracks that hold no trunk and number the rest from the top
  10. 9return the tracks, the wires and E, the number of columns past n

The order of the steps follows Rivest and Fiduccia. Line L3 makes the connections that column cc forces. Line L4 frees tracks, which is the main way to keep the width small. Line L5 gets nets ready for the next pins, so that line L3 will find a track for them in a later column. A track freed in column cc is not given to another net in the same column, because the trunk of the old net still holds column cc on it.

The original router has one more step, which moves the tracks of a split net closer together when they cannot be joined yet, and it inserts the new track of line L3 by its own rule. This page leaves the first out and puts a new track at the edge of the side of its pin. The version stays legal and complete, as the proof shows.

Example

Take the channel

column 1 2 3 4 5 6
top 1 2 1 3 0 0
bottom 2 0 0 1 3 3

with density 2. Line L1 makes tracks 1 and 2.

column what happens track 1 track 2
1 net 1 enters on track 1, net 2 on track 2; neither can move, because the branches fill the column 1 2
2 net 2 enters on track 2, with a branch past track 1; net 2 is done, track 2 is freed 1 2 (freed)
3 net 1 enters on track 1; its next pin is at the bottom, so it jogs down to the empty track 2, and track 1 is freed 1 (freed) 1
4 net 3 enters on track 1, net 1 enters on track 2; net 1 is done and is freed 3 1 (freed)
5 net 3 enters on track 2 from the bottom, so it is split; a jog joins tracks 1 and 2, and track 1 is freed, since the next pin is at the bottom 3 (freed) 3
6 net 3 enters on track 2 and is done 3 (freed)

The routing uses 2 tracks, the density, and no extension column. Net 1 changes track in column 3 and net 3 in column 5. Without doglegs, this channel needs 3 tracks, because its vertical constraint graph has the path 3→1→23 \to 1 \to 2.

A cycle. Take top pins 1,21, 2 and bottom pins 2,12, 1, with density 2. In column 1, net 1 enters on track 1 and net 2 on track 2. In column 2, the top pin of net 2 finds its track 2, and the bottom pin of net 1 finds track 1, so the two branches would cross. Both are equally long, so the top pin keeps track 2, and net 1 gets a new track 3 at the bottom. Net 2 is done and frees track 2. Net 1 is now on tracks 1 and 3, and the branch of net 2 blocks the jog in column 2. In the extension column 3, the jog from track 1 to track 3 is free, and net 1 is joined. The result has 3 tracks and 1 extension column. The page on channel density shows that 2 tracks are not enough for this channel in this model.

Correctness

The proof shows the following.

  • Legal wires. A track holds at most one net at a time, and a track is never given to a new net in the column where it was freed. Every vertical wire in a column is placed only where layer V is free, except the two pin branches, whose conflict line L3 resolves. So no point of a layer holds two nets.
  • Connected nets. Every part of the wire of a net is joined to one of the tracks that the net holds. A net is freed only when it holds one track and has no pin to the right, so its wire is then one connected piece.
  • Completion. In an extension column there are no pins, so the shortest jog of a split net is always free, and each extension column frees at least one track. The scan stops after at most as many extension columns as there are tracks.
  • Density bound. The router starts with dd tracks and every routing in this model needs at least dd, so T≥dT \ge d.
Proof: The greedy channel router of this page returns a legal routing of every channel, with at most as many extension columns as tracksfull

Call the state at a column the list of tracks in order from the top, with the net that each track holds, or none. A track is live for net xx when it holds xx. The router builds wires of three kinds in column cc: the branches of the pins (line L3), the jogs between tracks of one net (lines L4 and L5), and the trunks, where a trunk of xx on track tt runs from the column where xx took tt to the column where tt was freed. Rows of tracks are fixed only at line L8, which removes empty tracks and keeps the order, so it changes no relation between wires.

Lemma 1 (layer H). No point of layer H holds two nets.

Proof. A track holds at most one net at a time. A net xx takes a track tt in column cc only when tt is empty: in line L3 the pin goes to a track that is empty or already holds xx, and in line L5 the target must be empty. Line L5 also rejects every track freed in column cc, and line L3 of column cc runs before any track is freed in column cc. So if tt was freed in column c′c', the old trunk ends at c′c' and the new one starts at some c≥c′+1c \ge c' + 1. The two trunks on tt do not share a column. □\square

Lemma 2 (layer V). No point of layer V holds two nets.

Proof. In column cc, line L3 makes at most two branches: the top pin aa from row 0 to its track ii, and the bottom pin bb from its track jj to the bottom row. If a≠ba \ne b and ii is not above jj, line L3 gives one of the pins a new track at the edge of its own side, so afterwards ii is above jj and the two branches are disjoint. Every jog of lines L4 and L5 is added only when the rows it spans are free in column cc of every other net, and the jogs added so far in column cc are counted as used. So each new vertical wire avoids all earlier ones of other nets. □\square

Lemma 3 (components). After each column, every connected part of the wire built so far for a net xx contains a live track of xx.

Proof. By induction over the steps. A pin of xx that enters on a live track of xx joins that part. A pin that enters on an empty track makes a new part, and the track becomes live. A jog joins two parts, and both keep their live tracks. Line L4 frees tracks only inside a joined set, and it keeps one track of each set, so each part keeps a live track. Line L5 adds a jog from the only track pp of xx to an empty track, makes that track live and then frees pp, so the part keeps a live track. Line L6 frees the only track of xx, and then xx has no part left to keep. □\square

Theorem 1 (legal routing). When the router stops, every net is connected and holds all its pins, and no point of a layer holds two nets.

Proof. Lemmas 1 and 2 give the second claim. Each pin is joined by its branch to a track of its net in its column. A net that holds no track has been freed by line L6, which needs one live track and no pin to the right. At that moment, by Lemma 3, every part of its wire holds that one track, so the wire is connected, and it holds all pins, since all of them are at or left of the current column. The loop of line L2 stops only when no track holds a net, so every net that has a pin is freed by then. □\square

Theorem 2 (completion). The router stops after at most TnT_n extension columns, where TnT_n is the number of tracks that hold a net after column nn. So E≤TE \le T.

Proof. In an extension column there are no pins. Suppose some track holds a net after the column before. If no net is on two or more tracks, every net holds one track and has no pin to the right, and line L6 frees them all, so the loop stops. Otherwise let xx be split. In line L4 no vertical wire exists yet in this column, so the first jog in the order is accepted, and the set it joins keeps one track and frees at least one. No step of an extension column takes an empty track except line L5, which frees the old track of the net in the same step. So the number of tracks that hold a net falls by at least 1 in each extension column, and after at most TnT_n such columns it is 0. □\square

Theorem 3 (density bound). The router uses at least dd tracks.

Proof. By Theorem 1 the result is a legal routing in the reserved two-layer model, within the columns of the channel and the extension columns. The density bound of the page on channel density holds for every such routing, so it has at least dd tracks. □\square

Theorem 4 (running time). With a table of the next pin of each net and an array of the rows of column cc used on layer V, each column takes O(T2)O(T^2) time, and the router takes O((n+E)T2)O((n + E) T^2) time.

Proof. Line L3 scans the tracks from each edge once, in O(T)O(T). Line L4 has fewer than TT jog candidates, and each is checked and marked in O(T)O(T). Line L5 scans at most TT rows for each of at most TT nets, and the clearness of a growing range is checked one row at a time. Line L6 looks at each track once. Line L3 adds at most two tracks per column, so T≤d+2nT \le d + 2n stays finite. □\square

Tests. No exhaustive optimum is used here, because the model with jogs in any column has too many routings to search. The tests run a geometric checker on every result, check that it rejects routings with a branch removed or with a wire given to another net, check that the number of tracks is at least dd, and check the channels of the page.

Complexity

  • Time. With an array that marks the rows of the current column used on layer V, each step of a column takes O(T)O(T) per net and O(T2)O(T^2) in all, and the next pin of each net comes from a table built in O(n)O(n) time. So the total time is O((n+E)T2)O((n + E) T^2). Line L3 adds at most two tracks per column, so T≤d+2nT \le d + 2n, and the completion argument gives E≤TE \le T.
  • Space. Θ(T+N)\Theta(T + N) for the state of the current column and the next pins, besides the output wires.

Properties

  • What is proved. Every result is a legal routing of all nets, possibly with extension columns, and it has at least dd tracks.
  • What is only measured. The number of tracks. Rivest and Fiduccia reported results close to the density on the benchmark channels of the time. On 1000 random channels of 20 columns and 10 nets, this version used dd tracks in 578, d+1d + 1 in 332, d+2d + 2 in 72, and more in 18. It needed extension columns in 272, and 447 of the channels had a cyclic constraint graph. On the acyclic ones, it beat left-edge in 123 and lost in 102. These are tests on random cases, not bounds.
  • Jogs anywhere. It handles cycles of the constraint graph without any special step, because a net can change track in any free column.
  • Local. Each decision depends only on the current column and the next pins. The router never goes back, so an early choice can cost tracks later.
  • Vias. Every jog adds two vias. The router does not try to keep the number of vias small.

Variants and improvements

  • Range reduction. Rivest and Fiduccia also move the tracks of a split net closer together when they cannot be joined yet. This makes a later join more likely.
  • Parameters. The original router has parameters, among them the starting number of tracks and a minimum length for a jog. Trying several values and keeping the best result is common.
  • Starting width. If the router needs extension columns, run it again with more starting tracks. More tracks often remove the need for extension columns.
  • Switchboxes. Luk in 1985 extended the column scan to pins on the left and right sides, for switchbox routing.
  • Doglegs at pins only. If jogs are allowed only at pin columns, the problem is the one of dogleg channel routing.

When to use it

  • When the vertical constraint graph has cycles, and routers without doglegs fail.
  • When a router that always completes is needed, and extension columns or extra tracks are acceptable.
  • On long channels, since the scan is linear in the number of columns.

When the channel has no vertical constraints, use the left-edge algorithm, which is optimal. When the number of tracks matters most, also try the Yoshimura-Kuh algorithm.

Pitfalls

  • Reusing a track in the column where it was freed. The old trunk holds column cc on that track. A new net there would touch it.
  • Forgetting the branch of a pin. The branch of a top pin passes over every track above its own on layer V. A jog in the same column must avoid those rows.
  • Expecting the density. The router starts with dd tracks, but it can add tracks and extension columns. Report both numbers.
  • Extension columns that are not allowed. If the channel has no room past its end, a result with E>0E > 0 is not a solution. Rerun with more tracks.

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.

channel.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the rt3 cad pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""A two-layer channel in the reserved-layer model, and a checker for routings.

A channel is given by two lists, top and bottom, of the same length n.
top[c - 1] is the net of the pin at the top of column c, and bottom[c - 1]
the net at the bottom; 0 means no pin. Columns are numbered 1 to n.

A routing in T tracks is a list of wires. Tracks are numbered 1 to T from
the top. Row 0 is the top edge of the channel and row T + 1 the bottom edge.
  ("H", net, track, c1, c2)  a trunk on layer H, on one track, from column c1 to c2
  ("V", net, column, r1, r2) a branch on layer V, in one column, from row r1 to r2
Two wires of the same net that share a grid point on the same layer are
joined. An H wire and a V wire of the same net that share a grid point are
joined by a via.
"""

from typing import Dict, List, Sequence, Tuple

Wire = Tuple[str, int, int, int, int]


def pins_of(top: Sequence[int], bottom: Sequence[int]) -> Dict[int, List[Tuple[int, str]]]:
    """Map each net to its pins (column, "T" or "B"), in column order."""
    pins: Dict[int, List[Tuple[int, str]]] = {}
    for c, (a, b) in enumerate(zip(top, bottom), start=1):
        if a:
            pins.setdefault(a, []).append((c, "T"))
        if b:
            pins.setdefault(b, []).append((c, "B"))
    return pins


def intervals(top: Sequence[int], bottom: Sequence[int]) -> Dict[int, Tuple[int, int]]:
    """Map each net to its interval (leftmost pin column, rightmost pin column)."""
    return {x: (p[0][0], p[-1][0]) for x, p in pins_of(top, bottom).items()}


def local_density(top: Sequence[int], bottom: Sequence[int], c: int) -> int:
    """Number of nets whose interval holds column c."""
    return sum(1 for l, r in intervals(top, bottom).values() if l <= c <= r)


def density(top: Sequence[int], bottom: Sequence[int]) -> int:
    """Channel density: the largest local density over all columns."""
    return max((local_density(top, bottom, c) for c in range(1, len(top) + 1)), default=0)


def vcg_edges(top: Sequence[int], bottom: Sequence[int]) -> List[Tuple[int, int]]:
    """Edges (a, b) of the vertical constraint graph: a is on top and b at the bottom of a column."""
    edges = set()
    for a, b in zip(top, bottom):
        if a and b and a != b:
            edges.add((a, b))
    return sorted(edges)


def realize(top: Sequence[int], bottom: Sequence[int], pieces: Dict[object, Tuple[int, int, int]],
            track: Dict[object, int], ntracks: int) -> List[Wire]:
    """Turn a track for each piece (net, left column, right column) into wires.

    A piece is a trunk. At each pin column c of a net, one branch runs from the
    pin to every track of the pieces of that net whose interval holds c.
    """
    wires: List[Wire] = []
    for p, (net, l, r) in pieces.items():
        wires.append(("H", net, track[p], l, r))
    for net, pins in pins_of(top, bottom).items():
        for c, side in pins:
            rows = [track[p] for p, (x, l, r) in pieces.items() if x == net and l <= c <= r]
            rows.append(0 if side == "T" else ntracks + 1)
            wires.append(("V", net, c, min(rows), max(rows)))
    return wires


def check_routing(top: Sequence[int], bottom: Sequence[int], ntracks: int, wires: Sequence[Wire],
                  extra_columns: int = 0) -> List[str]:
    """Return a list of problems with the routing. An empty list means a legal routing.

    Checks: every wire is inside the channel; no grid point of a layer holds two
    nets (no short); the edge rows are touched only at the pins of the same net;
    each pin is reached; the wires and pins of each net are connected.
    """
    n = len(top)
    last_col = n + extra_columns
    probs: List[str] = []
    owner: Dict[Tuple[str, int, int], int] = {}
    cells: Dict[Tuple[str, int, int], List[int]] = {}
    for i, (layer, net, a, b, c) in enumerate(wires):
        if layer == "H":
            t, c1, c2 = a, min(b, c), max(b, c)
            if not 1 <= t <= ntracks or c1 < 1 or c2 > last_col:
                probs.append(f"wire {i} leaves the channel")
                continue
            pts = [("H", x, t) for x in range(c1, c2 + 1)]
        else:
            col, r1, r2 = a, min(b, c), max(b, c)
            if not 1 <= col <= last_col or r1 < 0 or r2 > ntracks + 1:
                probs.append(f"wire {i} leaves the channel")
                continue
            pts = [("V", col, y) for y in range(r1, r2 + 1)]
        for pt in pts:
            if pt in owner and owner[pt] != net:
                probs.append(f"short between nets {owner[pt]} and {net} at {pt}")
            owner.setdefault(pt, net)
            cells.setdefault(pt, []).append(i)
    pins = pins_of(top, bottom)
    pin_points = {}
    for net, ps in pins.items():
        for c, side in ps:
            pin_points[("V", c, 0 if side == "T" else ntracks + 1)] = net
    for pt, net in owner.items():
        if pt[0] == "V" and pt[2] in (0, ntracks + 1) and pin_points.get(pt) != net:
            probs.append(f"net {net} touches the channel edge at {pt} without a pin")
    for pt, net in pin_points.items():
        if owner.get(pt) != net:
            probs.append(f"pin of net {net} at {pt} is not reached")
    if probs:
        return probs
    parent = list(range(len(wires)))

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

    def union(x: int, y: int) -> None:
        parent[find(x)] = find(y)

    for pt, ws in cells.items():
        for w in ws[1:]:
            union(ws[0], w)
        if pt[0] == "H":
            other = cells.get(("V", pt[1], pt[2]))
            if other and owner[("V", pt[1], pt[2])] == owner[pt]:
                union(ws[0], other[0])
    for net, ps in pins.items():
        roots = {find(cells[pt][0]) for pt, x in pin_points.items() if x == net}
        if len(roots) != 1:
            probs.append(f"net {net} is not connected")
    return probs


def tracks_used(wires: Sequence[Wire]) -> int:
    """The largest track number used by an H wire."""
    return max((w[2] for w in wires if w[0] == "H"), default=0)
greedy_channel_router.py 172 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/greedy-channel-router/. The authors are listed in prov/N38E4M.jsonl.

"""A greedy channel router after Rivest and Fiduccia, in the reserved two-layer model.

The router scans the channel one column at a time, from left to right. In
each column it brings the pins into the channel, joins the tracks of nets
that are split over two or more tracks, moves nets toward the side of their
next pin, and frees the track of each net that is finished. A net may
change track in any column (a jog). If a net is still split after the last
column, the router goes on in extension columns to the right of the channel.

This is the version of the page. Range reduction is left out, and a pin
that cannot enter gets a new track at the edge of its own side.
"""

from typing import Dict, List, Optional, Sequence, Tuple

from channel import density, pins_of

TOP, BOTTOM = "T", "B"


def greedy_route(top: Sequence[int], bottom: Sequence[int]):
    """Route a channel. Returns (number of tracks, wires, number of extension columns)."""
    n = len(top)
    pins = pins_of(top, bottom)
    order: List[int] = list(range(density(top, bottom)))  # @line L1
    next_id = len(order)
    occ: Dict[int, Optional[int]] = {t: None for t in order}
    start: Dict[int, int] = {}
    h_wires: List[Tuple[int, int, int, int]] = []  # (net, track id, c1, c2)
    v_wires: List[Tuple[int, int, object, object]] = []  # (net, column, end, end); an end is a track id, TOP or BOTTOM

    def new_track(side: str) -> int:
        nonlocal next_id
        t = next_id
        next_id += 1
        if side == TOP:
            order.insert(0, t)
        else:
            order.append(t)
        occ[t] = None
        return t

    def free(t: int, c: int) -> None:
        h_wires.append((occ[t], t, start[t], c))
        occ[t] = None

    def next_pin(x: int, c: int) -> Optional[str]:
        later = [s for col, s in pins[x] if col > c]
        if not later:
            return None
        first = min(col for col, s in pins[x] if col > c)
        sides = [s for col, s in pins[x] if col == first]
        return TOP if TOP in sides else BOTTOM

    def tracks_of(x: int) -> List[int]:
        return [t for t in order if occ[t] == x]

    c = 1
    while c <= n or any(v is not None for v in occ.values()):  # @line L2
        a = top[c - 1] if c <= n else 0
        b = bottom[c - 1] if c <= n else 0
        # Step 1: bring the pins in.  @line L3
        i = next((t for t in order if occ[t] in (None, a)), None) if a else None
        j = next((t for t in reversed(order) if occ[t] in (None, b)), None) if b else None
        if a and b and a != b:
            if i is not None and j is not None and order.index(i) < order.index(j):
                pass
            else:
                up = order.index(i) + 1 if i is not None else len(order) + 2
                down = len(order) - order.index(j) if j is not None else len(order) + 2
                if up <= down and i is not None:
                    j = None
                elif j is not None:
                    i = None
        if a and i is None:
            i = new_track(TOP)
        if b and j is None:
            j = new_track(BOTTOM)
        for x, t, end in ((a, i, TOP), (b, j, BOTTOM)):
            if x:
                if occ[t] is None:
                    occ[t], start[t] = x, c
                v_wires.append((x, c, end, t))
        pos = {t: k for k, t in enumerate(order)}
        used: List[Tuple[int, int, int]] = []  # V use in this column: (low position, high position, net)
        if a:
            used.append((-1, pos[i], a))
        if b:
            used.append((pos[j], len(order), b))

        def clear(lo: int, hi: int, x: int) -> bool:
            return all(y == x or h < lo or hi < l for l, h, y in used)

        # Step 2: join split nets, shortest jog first.  @line L4
        jogs = []
        for x in sorted({v for v in occ.values() if v is not None}):
            ts = tracks_of(x)
            for p, q in zip(ts, ts[1:]):
                jogs.append((pos[q] - pos[p], pos[p], x, p, q))
        group = {t: t for t in order}

        def find(t: int) -> int:
            while group[t] != t:
                t = group[t]
            return t

        for _, _, x, p, q in sorted(jogs):
            if clear(pos[p], pos[q], x):
                used.append((pos[p], pos[q], x))
                v_wires.append((x, c, p, q))
                group[find(p)] = find(q)
        just_freed = set()
        for x in sorted({v for v in occ.values() if v is not None}):
            sets: Dict[int, List[int]] = {}
            for t in tracks_of(x):
                sets.setdefault(find(t), []).append(t)
            side = next_pin(x, c)
            for ts in sets.values():
                keep = ts[-1] if side == BOTTOM else ts[0]
                for t in ts:
                    if t != keep:
                        free(t, c)
                        just_freed.add(t)
        # Step 4: move nets toward the side of their next pin.  @line L5
        for x in sorted({v for v in occ.values() if v is not None}):
            ts = tracks_of(x)
            side = next_pin(x, c)
            if len(ts) != 1 or side is None:
                continue
            p = ts[0]
            step = -1 if side == TOP else 1
            best = None
            k = pos[p] + step
            while 0 <= k < len(order) and clear(min(k, pos[p]), max(k, pos[p]), x):
                t = order[k]
                if occ[t] is None and t not in just_freed and t not in (i, j):
                    best = t
                k += step
            if best is not None:
                used.append((min(pos[p], pos[best]), max(pos[p], pos[best]), x))
                v_wires.append((x, c, p, best))
                occ[best], start[best] = x, c
                free(p, c)
                just_freed.add(p)
        # Step 5: free the track of each finished net.  @line L6
        for x in sorted({v for v in occ.values() if v is not None}):
            ts = tracks_of(x)
            if len(ts) == 1 and next_pin(x, c) is None:
                free(ts[0], c)
        c += 1  # @line L7
    last_col = c - 1
    used_ids = [t for t in order if any(w[1] == t for w in h_wires)]  # @line L8
    row = {t: k + 1 for k, t in enumerate(used_ids)}
    T = len(used_ids)

    def to_row(end) -> int:
        if end == TOP:
            return 0
        if end == BOTTOM:
            return T + 1
        return row[end]

    wires = [("H", x, row[t], c1, c2) for x, t, c1, c2 in h_wires]
    wires += [("V", x, col, to_row(e1), to_row(e2)) for x, col, e1, e2 in v_wires]
    return T, wires, max(0, last_col - n)  # @line L9


if __name__ == "__main__":
    print(greedy_route([1, 2], [2, 1]))
test_greedy_channel_router.py 115 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/greedy-channel-router/. The authors are listed in prov/N38E4M.jsonl.

import random

from channel import check_routing, density, intervals, tracks_used, vcg_edges
from greedy_channel_router import greedy_route


def random_channel(rng: random.Random, n: int, nets: int, maxpins: int):
    while True:
        slots = [(c, s) for c in range(n) for s in "TB"]
        rng.shuffle(slots)
        top, bottom = [0] * n, [0] * n
        k, ok = 0, True
        for x in range(1, nets + 1):
            p = rng.randint(2, maxpins)
            mine = slots[k:k + p]
            k += p
            if len(mine) < 2 or len({c for c, _ in mine}) < 2:
                ok = False
                break
            for c, s in mine:
                (top if s == "T" else bottom)[c] = x
        if ok:
            return top, bottom


def has_cycle(top, bottom) -> bool:
    """Plain depth-first search for a cycle in the vertical constraint graph."""
    succ = {}
    for a, b in vcg_edges(top, bottom):
        succ.setdefault(a, []).append(b)
    state = {}

    def visit(v) -> bool:
        state[v] = 1
        for w in succ.get(v, []):
            if state.get(w) == 1 or (w not in state and visit(w)):
                return True
        state[v] = 2
        return False

    return any(v not in state and visit(v) for v in list(succ))


def check(top, bottom):
    t, wires, extra = greedy_route(top, bottom)
    assert check_routing(top, bottom, t, wires, extra_columns=extra) == []
    assert tracks_used(wires) == t
    assert t >= density(top, bottom)
    return t, extra


def test_example_page() -> None:
    top = [1, 2, 1, 3, 0, 0]
    bottom = [2, 0, 0, 1, 3, 3]
    assert check(top, bottom) == (2, 0)


def test_cycle_needs_extension() -> None:
    top, bottom = [1, 2], [2, 1]
    assert has_cycle(top, bottom)
    t, extra = check(top, bottom)
    assert extra >= 1


def test_edges() -> None:
    assert greedy_route([], []) == (0, [], 0)
    assert check([1, 1], [0, 0]) == (1, 0)
    assert check([1, 0], [0, 1]) == (1, 0)
    assert check([1, 2, 1, 2], [0, 0, 0, 0])[0] == 2


def test_checker_rejects_broken_routings(seed: int = 3) -> None:
    rng = random.Random(seed)
    for _ in range(100):
        n = rng.randint(3, 10)
        top, bottom = random_channel(rng, n, rng.randint(2, min(5, n)), 3)
        t, wires, extra = greedy_route(top, bottom)
        branches = [k for k, w in enumerate(wires) if w[0] == "V" and (0 in w[3:] or t + 1 in w[3:])]
        k = rng.choice(branches)
        assert check_routing(top, bottom, t, wires[:k] + wires[k + 1:], extra_columns=extra) != []
        x = wires[k]
        other = [y for y in intervals(top, bottom) if y != x[1]]
        if other:
            moved = wires[:k] + [(x[0], other[0]) + x[2:]] + wires[k + 1:]
            assert check_routing(top, bottom, t, moved, extra_columns=extra) != []
        assert check_routing(top, bottom, t - 1, wires, extra_columns=extra) != []


def test_random_channels(seed: int = 21) -> None:
    rng = random.Random(seed)
    extended = cyclic = 0
    for _ in range(400):
        n = rng.randint(2, 16)
        top, bottom = random_channel(rng, n, rng.randint(1, min(9, n)), 4)
        t, extra = check(top, bottom)
        extended += extra > 0
        cyclic += has_cycle(top, bottom)
        assert t <= density(top, bottom) + 2 * (n + extra)
    assert cyclic > 0 and extended > 0


def test_one_side_pins_meet_density(seed: int = 4) -> None:
    rng = random.Random(seed)
    for _ in range(200):
        n = rng.randint(2, 14)
        top, _ = random_channel(rng, n, rng.randint(1, max(1, n // 2)), 3)
        top = [x for x in top]
        bottom = [0] * n
        spans = intervals(top, bottom)
        if any(l == r for l, r in spans.values()):
            continue
        check(top, bottom)

History

Ronald L. Rivest and Charles M. Fiduccia presented the greedy channel router at the 19th Design Automation Conference in 1982. It differed from the routers before it, which assigned whole nets or pieces of nets to tracks, in that it routed one column at a time with jogs anywhere. It became one of the most used channel routers, and Luk extended it to switchboxes in 1985. Szymanski's proof of 1985 that the fewest tracks with doglegs is NP-hard to find explained why such heuristics are the practical choice.

References

  1. R. L. Rivest and C. M. Fiduccia, A greedy channel router, Proceedings of the 19th Design Automation Conference, 418 to 424, 1982, the steps of the router in each column, its parameters and its results on benchmark channels (general locator)
  2. 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 6, Detailed Routing, the section on channel routing (the greedy channel router; general locator)
  3. Naveed A. Sherwani, Algorithms for VLSI Physical Design Automation, third edition, Kluwer, 1999, the chapter on detailed routing, the part on channel routing (the greedy channel router and its steps; general locator)
  4. W. K. Luk, A greedy switch-box router, Integration, the VLSI Journal 3(2), 129 to 149, 1985, the extension of the column scan to pins on all four sides (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