Algorithm Search⌘K

Algorithmcore

Dogleg channel routing

Also called Deutsch dogleg router.

Deutsch's router that splits each multi-pin net at its pins into pieces that may take different tracks, which breaks some constraint cycles and can use fewer tracks.

Time
O(n + P log P + T (P + n)) worst
Space
Θ(P + n) extra
Where
P = the number of pieces of nets; T = the number of tracks used; n = the number of columns
Properties
deterministicnot exactiterative
Origin
D. N. Deutsch, 1976

Dogleg channel routing extends the left-edge algorithm by letting a net change track. A dogleg is a jog of a net from one track to another in one column, with a short vertical wire. Deutsch's router allows doglegs only at the pin columns of the net. It cuts each net with pins in kk columns into k−1k - 1 pieces, one between each two pin columns that follow each other, and treats each piece as a net of its own. The constraint graph is built on the pieces, and the pieces are placed with the left-edge scan. A cycle in the vertical constraint graph of the nets can vanish in the graph of the pieces, and a long constraint path can split, so the channel can need fewer tracks. The method is a heuristic: it does not break every cycle, and it can also use more tracks than the left-edge algorithm.

In plain words

In the left-edge method, each net is one long stick that must stay in one lane. Here, a net that has pins in many places is cut at its pins into short sticks. The short sticks of one net still touch at the pins, where a short wire across the corridor joins them, so each can sit in a different lane.

Short sticks fit into gaps that a long stick cannot use. They can also get around a rule that would force one net both above and below another, as long as the two demands come from different parts of the net.

Then the short sticks are packed into lanes with the left-edge method, the same as before.

The problem

The input is a channel as on the page on the channel routing problem, in the reserved two-layer model with doglegs allowed at pin columns. For a net with pin columns c0<c1<⋯<ck−1c_0 < c_1 < \cdots < c_{k-1}, the pieces are pi=[ci,ci+1]p_i = [c_i, c_{i+1}] for 0≤i≤k−20 \le i \le k - 2. A net with pins in two columns has one piece.

The output is a track t(p)t(p) for each piece, such that:

  • two pieces of different nets on the same track have disjoint intervals;
  • if column cc has net aa on top and net b≠ab \ne a at the bottom, every piece of aa that holds cc is on a higher track than every piece of bb that holds cc.

The wires follow: a trunk of each piece on its track on layer H, and in each pin column of a net, one branch on layer V from the pin past all the tracks of the pieces of that net that meet there. Where two pieces of a net on different tracks meet, the branch is the dogleg. The goal is a small number of tracks TT.

The algorithm

  1. DOGLEG(channel)
  2. 1cut each net into pieces at its pin columns; sort the pieces by left end, ties by net and index
  3. 2build the constraint graph G_p of the pieces; t ← 0; U ← all pieces, in this order
  4. 3while U is not empty do
  5. 4t ← t + 1; last ← none; lastnet ← none
  6. 5for each piece p of net x in U, in order do
  7. 6if (last is none or l_p > last or (l_p = last and x = lastnet)) and every parent of p in G_p has a track < t then
  8. 7t(p) ← t; last ← r_p; lastnet ← x
  9. 8remove from U the pieces placed on track t
  10. 9if no piece was placed on track t then return "cycle"
  11. 10return the tracks t(p)

The graph GpG_p on line L2 has an edge p→qp \to q when some column cc has net aa on top and net b≠ab \ne a at the bottom, pp is a piece of aa that holds cc, and qq is a piece of bb that holds cc. A pin column of a net is held by two of its pieces when it is an inner pin column, and both get the edge, because the dogleg wire in that column runs past both of their tracks.

Lines L3 to L9 are the scan of the left-edge algorithm. The only change is on line L6: a piece may start in the column where the last piece on the track ends, if both belong to the same net. Then the two pieces form one straight trunk.

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

The nets have the intervals I1=[1,4]I_1 = [1, 4], I2=[1,2]I_2 = [1, 2] and I3=[4,6]I_3 = [4, 6], and the density is 2. The vertical constraint graph of the nets is the path 3→1→23 \to 1 \to 2, from columns 4 and 1. So without doglegs, nets 3, 1 and 2 need three different tracks in this order, and every routing without doglegs uses 3 tracks.

Line L1 cuts net 1 at column 3 into (1,0)=[1,3](1, 0) = [1, 3] and (1,1)=[3,4](1, 1) = [3, 4], and net 3 at column 5 into (3,0)=[4,5](3, 0) = [4, 5] and (3,1)=[5,6](3, 1) = [5, 6]. Net 2 stays one piece (2,0)=[1,2](2, 0) = [1, 2]. The graph of the pieces has two edges: (1,0)→(2,0)(1, 0) \to (2, 0) from column 1, and (3,0)→(1,1)(3, 0) \to (1, 1) from column 4. The path is broken, because the two edges at net 1 now end at different pieces.

The order is (1,0),(2,0),(1,1),(3,0),(3,1)(1, 0), (2, 0), (1, 1), (3, 0), (3, 1).

track scan placed
1 (1,0)(1, 0) placed, last = 3; (2,0)(2, 0) blocked (parent on this track); (1,1)(1, 1) blocked (parent (3,0)(3, 0) not placed); (3,0)(3, 0) placed, last = 5; (3,1)(3, 1) starts at 5 and is of the same net, placed (1,0),(3,0),(3,1)(1, 0), (3, 0), (3, 1)
2 (2,0)(2, 0) placed, last = 2; (1,1)(1, 1) placed (2,0),(1,1)(2, 0), (1, 1)

The result has 2 tracks, which is the density. Net 1 runs on track 1 from column 1 to column 3, jogs down to track 2 in column 3, and goes on to column 4. In column 3 the dogleg runs from the top pin to track 2, and no other net has a pin there. In column 4 net 3 comes down to track 1 and net 1 comes up to track 2, so they do not meet.

A cycle that doglegs break. Take top pins 1,1,21, 1, 2 and bottom pins 2,0,12, 0, 1. The nets give 1→21 \to 2 from column 1 and 2→12 \to 1 from column 3, a cycle, so left-edge fails. Net 1 has pins in columns 1, 2 and 3, and its pieces are [1,2][1, 2] and [2,3][2, 3]. The graph of the pieces is the path (1,0)→(2,0)→(1,1)(1, 0) \to (2, 0) \to (1, 1), and the scan routes the channel in 3 tracks.

A cycle that doglegs do not break. Take top pins 1,21, 2 and bottom pins 2,12, 1. Each net has pins in two columns only, so it is one piece, and the cycle stays. The method returns "cycle".

Correctness

The proof shows the following.

  • Legal routing. Pieces on one track are disjoint, except that pieces of one net may touch at a shared end. Every edge of GpG_p is kept, so in every column the branch of the top net ends above the branch of the bottom net. Each net is connected through its pin columns.
  • Termination and cycles. As for left-edge, each pass places a piece when GpG_p is acyclic, and a pass that places nothing happens exactly when GpG_p has a cycle.
  • The same as left-edge on two-pin nets. If every net has pins in two columns, each net is one piece, GpG_p is the vertical constraint graph, and the result is that of the left-edge algorithm.
  • Density bound. The result never uses fewer than dd tracks, since the bound of the page on channel density holds with doglegs.
Proof: The dogleg channel router returns a legal routing with doglegs at pin columns, reports exactly the cyclic cases, and never beats the densityfull

For a net xx with pin columns c0<c1<⋯<ck−1c_0 < c_1 < \cdots < c_{k-1}, the pieces are pi=[ci,ci+1]p_i = [c_i, c_{i+1}] for 0≤i≤k−20 \le i \le k - 2, each labeled with the net xx. Let GpG_p be the graph of line L2: an edge p→qp \to q when some column cc has net aa on top and net b≠ab \ne a at the bottom, pp is a piece of aa with c∈pc \in p, and qq is a piece of bb with c∈qc \in q. Let ≺\prec be the order of line L1.

Wires. From tracks t(p)t(p) with T=max⁡pt(p)T = \max_p t(p), build: a trunk of net xx on layer H on track t(p)t(p) over the columns of pp, for each piece pp of xx; and for each pin of xx in column cc, a branch of xx on layer V in column cc from the pin row (0 or T+1T + 1) to the farthest track t(p)t(p) among the pieces pp of xx that hold cc, with a via at each such track.

Lemma 1 (same track). Two pieces placed on one track either have disjoint intervals, or belong to the same net and share one end column.

Proof. As in Lemma 1 of the left-edge proof, last\mathit{last} is the largest right end on the track, because line L6 only accepts lp≥lastl_p \ge \mathit{last}. If lp>lastl_p > \mathit{last}, the interval of pp is disjoint from all intervals on the track. If lp=lastl_p = \mathit{last}, line L6 requires that pp has the net of the piece that ends at last\mathit{last}. Every other piece on the track ends before last\mathit{last}, so pp is disjoint from those, and it shares only column lpl_p with the last one. □\square

Lemma 2 (edges kept). For every edge p→qp \to q of GpG_p with both pieces placed, t(p)<t(q)t(p) < t(q).

Proof. Line L6 places qq on track tt only when its parent pp has a track less than tt. □\square

Theorem 1 (legal routing). If the algorithm returns tracks, the wires above form a legal routing in the reserved two-layer model.

Proof. Layer H. Two trunks of different nets on one track are disjoint by Lemma 1.

Layer V. The only branches in column cc are the branch of a=top(c)a = \mathrm{top}(c), which holds rows 0 to max⁡{t(p):p a piece of a,c∈p}\max\{t(p) : p \text{ a piece of } a, c \in p\}, and the branch of b=bot(c)b = \mathrm{bot}(c), which holds rows min⁡{t(q):q a piece of b,c∈q}\min\{t(q) : q \text{ a piece of } b, c \in q\} to T+1T + 1. If a=ba = b, both belong to one net. If a≠ba \ne b, every pair of such pp and qq is an edge p→qp \to q of GpG_p, so by Lemma 2 the maximum is less than the minimum, and the two branches are disjoint.

Vias. Each via of xx is at (c,t(p))(c, t(p)) with c∈pc \in p, so the trunk of pp holds that point on layer H.

Connectivity. The pieces pi−1p_{i-1} and pip_i of xx both hold the pin column cic_i, and the branch of a pin of xx in column cic_i reaches both of their tracks, with vias. So consecutive pieces are joined, all pieces of xx form one connected wire, and every pin of xx lies on a branch that reaches a trunk of xx. □\square

Theorem 2 (termination and cycles). If GpG_p is acyclic, the algorithm returns a track for every piece after at most PP passes. If GpG_p has a cycle, it returns "cycle".

Proof. The argument is that of Lemmas 3 and 4 and Theorem 1 of the left-edge proof, with pieces for nets. If GpG_p is acyclic, the first piece in the order ≺\prec among the unplaced pieces with all parents placed is accepted when it is scanned, unless an earlier piece of the pass was accepted. So every pass places a piece. A piece on a cycle is never placed, since its parent on the cycle is never on a higher track before it, so a cyclic GpG_p leads to a pass that places nothing, and line L9 returns "cycle". □\square

Theorem 3 (two-pin nets). If every net has pins in exactly two columns, the algorithm returns the same tracks as the left-edge algorithm, with each net in the place of its only piece.

Proof. Each net is one piece with the same interval, so the orders of line L1 agree. Two pieces of one net never meet, so the extra clause of line L6 never applies. A column with aa on top and b≠ab \ne a at the bottom is in the only piece of each, so GpG_p is the vertical constraint graph of the nets. The two scans are then the same step by step. □\square

Theorem 4 (density). The algorithm never uses fewer than dd tracks.

Proof. By Theorem 1 the result is a legal routing in the reserved two-layer model, and the density bound holds for every such routing, with doglegs or without. □\square

Theorem 5 (running time). The algorithm runs in O(n+Plog⁡P+T(P+n))O(n + P \log P + T(P + n)) time.

Proof. A column cc is held by at most two pieces of a net: the one or two pieces that end at cc if cc is a pin column of the net, and one piece otherwise. So each column gives at most 2⋅2=42 \cdot 2 = 4 edges, and GpG_p has at most 4n4n edges. A sweep over the columns that keeps, for each net, the pieces that hold the current column builds the pieces and GpG_p in O(n+P)O(n + P) time. Sorting takes O(Plog⁡P)O(P \log P). Each pass looks at each unplaced piece and its parents once, in O(P+n)O(P + n) time, and there are at most T+1T + 1 passes. □\square

Tests. The tests compare the implementation with two exhaustive searches over all maps from pieces to tracks: one that builds the wires and runs a geometric checker, and one that applies the rules of Lemma 1 and the edges of GpG_p directly. On small channels both searches agree, the router is legal and never below their optimum, and it returns "cycle" exactly when no map works.

Complexity

  • Time. A net with pins in kk columns gives k−1k - 1 pieces, so PP is less than the number of pins. A column is held by at most two pieces of each net, so each column gives at most 4 edges of GpG_p, and GpG_p has O(n)O(n) edges. Building the pieces and GpG_p in one sweep over the columns takes O(n+P)O(n + P) time. Sorting takes O(Plog⁡P)O(P \log P), and each pass of the scan takes O(P+n)O(P + n). The total is O(n+Plog⁡P+T(P+n))O(n + P \log P + T(P + n)).
  • Space. Θ(P+n)\Theta(P + n) for the pieces, the graph and the tracks.

Properties

  • What is proved. The result is a legal routing with doglegs at pin columns, it is reported as "cycle" exactly when GpG_p has a cycle, and it has at least dd tracks.
  • Not always better. Take top pins 1,2,1,21, 2, 1, 2 and bottom pins 0,0,0,10, 0, 0, 1. Left-edge puts net 2 on track 1 and net 1 on track 2. The dogleg scan puts the first piece of net 1 on track 1, and then its second piece must go below net 2, so it uses 3 tracks.
  • What is only measured. On 1000 random channels of 12 columns and 7 nets with an acyclic constraint graph, the dogleg scan used fewer tracks than the optimum without doglegs in 27, as many in 744, and more in 229. Against the left-edge algorithm, it was better in 58 and worse in 128. On a sample of small random channels whose constraint graph has a cycle, it routed about one third. These are tests on random cases, not bounds.
  • Why it can lose. A dogleg holds its pin column on layer V across the tracks of both pieces. This adds constraints in that column, and a piece placed early on a high track can force the next piece of the same net lower.
  • Deterministic. The order of line L1 fixes the result.

Variants and improvements

  • Doglegs in any column. Allow a net to change track wherever the column is free on layer V. The greedy channel router works in this model.
  • Fewer cuts. Cut a net only at the pin columns where a cut breaks a cycle or shortens a long path of the constraint graph, so that fewer vias are made.
  • Merging pieces. The Yoshimura-Kuh algorithm has a form with pieces at pin columns, where it merges pieces before the scan.
  • Both directions. Fill tracks from the top and from the bottom, and keep the better result.

When to use it

  • When the constraint graph of the nets has a cycle or a long path, and the nets have pins in three or more columns.
  • When vias are cheap, since every dogleg adds vias.

When the nets have only two pins each, the method is plain left-edge, and the greedy channel router is the better choice for cycles.

Pitfalls

  • Cutting at the wrong columns. The cuts must be at the pin columns of the net. A cut between pin columns needs a free column on layer V there, which is a different model.
  • Missing edges at the dogleg column. At an inner pin column, both pieces of the net hold the column, and both must get the edges of that column. With only one of them, the dogleg wire can cross the branch of the other net.
  • Pieces of one net on one track. Two pieces of one net that share a column may lie on the same track. Treating them as different nets wastes tracks.
  • Expecting fewer tracks. The dogleg form is not always better than left-edge. Run both and keep the better result.

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)
dogleg_channel_routing.py 86 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dogleg-channel-routing/. The authors are listed in prov/SJ43AX.jsonl.

"""The dogleg channel router in the reserved two-layer model.

Each net is cut at its pin columns into pieces, called subnets. A net with
pins in k distinct columns gives k - 1 pieces, and two pieces of the same net
meet at a pin column. Each piece is a trunk on one track, so a net can change
track (a dogleg) at a pin column. The pieces are placed with the left-edge
rule, under the vertical constraints between pieces.
"""

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

from channel import pins_of, realize

Piece = Tuple[int, int]  # (net, index of the piece within the net)


def split_nets(top: Sequence[int], bottom: Sequence[int]) -> Dict[Piece, Tuple[int, int, int]]:
    """Cut each net at its pin columns. Returns piece -> (net, left column, right column)."""
    pieces: Dict[Piece, Tuple[int, int, int]] = {}
    for net, pins in pins_of(top, bottom).items():
        cols = sorted({c for c, _ in pins})
        for i in range(len(cols) - 1):
            pieces[(net, i)] = (net, cols[i], cols[i + 1])
    return pieces


def piece_vcg(top: Sequence[int], bottom: Sequence[int],
              pieces: Dict[Piece, Tuple[int, int, int]]) -> List[Tuple[Piece, Piece]]:
    """Edges (p, q): in some column, net(p) has the top pin, net(q) the bottom pin, and both pieces hold the column."""
    edges = set()
    for c, (a, b) in enumerate(zip(top, bottom), start=1):
        if a and b and a != b:
            above = [p for p, (x, l, r) in pieces.items() if x == a and l <= c <= r]
            below = [q for q, (x, l, r) in pieces.items() if x == b and l <= c <= r]
            for p in above:
                for q in below:
                    edges.add((p, q))
    return sorted(edges)


def left_edge_pieces(pieces: Dict[Piece, Tuple[int, int, int]],
                     edges: Sequence[Tuple[Piece, Piece]]) -> Optional[Dict[Piece, int]]:
    """Constrained left-edge on pieces. Two pieces of the same net may meet at a column on one track."""
    parents: Dict[Piece, List[Piece]] = {p: [] for p in pieces}
    for p, q in edges:
        parents[q].append(p)
    order = sorted(pieces, key=lambda p: (pieces[p][1], p))  # @line L1
    track: Dict[Piece, int] = {}
    t = 0  # @line L2
    unplaced = list(order)
    while unplaced:  # @line L3
        t += 1  # @line L4
        last, last_net = None, None
        now = []
        for p in unplaced:  # @line L5
            net, l, r = pieces[p]
            free = last is None or l > last or (l == last and net == last_net)
            if free and all(track.get(u, t) < t for u in parents[p]):  # @line L6
                track[p] = t  # @line L7
                last, last_net = r, net
                now.append(p)
        unplaced = [p for p in unplaced if p not in track]  # @line L8
        if not now:  # @line L9
            return None
    return track  # @line L10


def dogleg_route(top: Sequence[int], bottom: Sequence[int]):
    """Route a channel with doglegs at pin columns.

    Returns (number of tracks, track of each piece, wires), or None if the
    vertical constraints between pieces have a cycle.
    """
    pieces = split_nets(top, bottom)
    track = left_edge_pieces(pieces, piece_vcg(top, bottom, pieces))
    if track is None:
        return None
    t = max(track.values(), default=0)
    return t, track, realize(top, bottom, pieces, track, t)


if __name__ == "__main__":
    print(dogleg_route([1, 1, 2], [2, 0, 1])[:2])
test_dogleg_channel_routing.py 153 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dogleg-channel-routing/. The authors are listed in prov/SJ43AX.jsonl.

import itertools
import random

from channel import check_routing, density, intervals, realize, vcg_edges
from dogleg_channel_routing import dogleg_route, left_edge_pieces, piece_vcg, split_nets


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 checker_optimum(top, bottom, pieces, max_tracks: int):
    """Fewest tracks over all maps from pieces to tracks whose realized routing passes the checker."""
    keys = sorted(pieces)
    for t in range(1, max_tracks + 1):
        for assign in itertools.product(range(1, t + 1), repeat=len(keys)):
            track = dict(zip(keys, assign))
            if not check_routing(top, bottom, t, realize(top, bottom, pieces, track, t)):
                return t
    return None


def rule_optimum(pieces, edges, max_tracks: int):
    """The same optimum by backtracking with the rules written out."""
    keys = sorted(pieces)
    eset = set(edges)

    def fits(track, p, k):
        net, l, r = pieces[p]
        for q, j in track.items():
            y, l2, r2 = pieces[q]
            if j == k and net != y and not (r < l2 or r2 < l):
                return False
            if ((p, q) in eset and k >= j) or ((q, p) in eset and j >= k):
                return False
        return True

    def search(i, track, t):
        if i == len(keys):
            return True
        for k in range(1, t + 1):
            if fits(track, keys[i], k):
                track[keys[i]] = k
                if search(i + 1, track, t):
                    return True
                del track[keys[i]]
        return False

    for t in range(1, max_tracks + 1):
        if search(0, {}, t):
            return t
    return None


def test_example_page() -> None:
    top = [1, 2, 1, 3, 0, 0]
    bottom = [2, 0, 0, 1, 3, 3]
    assert vcg_edges(top, bottom) == [(1, 2), (3, 1)]
    assert density(top, bottom) == 2
    pieces = split_nets(top, bottom)
    assert pieces == {(1, 0): (1, 1, 3), (1, 1): (1, 3, 4), (2, 0): (2, 1, 2), (3, 0): (3, 4, 5), (3, 1): (3, 5, 6)}
    assert piece_vcg(top, bottom, pieces) == [((1, 0), (2, 0)), ((3, 0), (1, 1))]
    t, track, wires = dogleg_route(top, bottom)
    assert t == 2
    assert track == {(1, 0): 1, (3, 0): 1, (3, 1): 1, (2, 0): 2, (1, 1): 2}
    assert check_routing(top, bottom, t, wires) == []
    whole = {x: (x, l, r) for x, (l, r) in intervals(top, bottom).items()}
    assert checker_optimum(top, bottom, whole, 3) == 3


def test_cycle_broken() -> None:
    top, bottom = [1, 1, 2], [2, 0, 1]
    t, track, wires = dogleg_route(top, bottom)
    assert t == 3 and track == {(1, 0): 1, (2, 0): 2, (1, 1): 3}
    assert check_routing(top, bottom, t, wires) == []


def test_cycle_not_broken() -> None:
    top, bottom = [1, 2], [2, 1]
    assert dogleg_route(top, bottom) is None
    assert checker_optimum(top, bottom, split_nets(top, bottom), 3) is None


def test_edges() -> None:
    assert dogleg_route([], []) == (0, {}, [])
    assert dogleg_route([1, 1], [0, 0])[:2] == (1, {(1, 0): 1})
    assert left_edge_pieces({}, []) == {}


def test_against_checker_brute_force(seed: int = 2) -> None:
    rng = random.Random(seed)
    for _ in range(120):
        n = rng.randint(2, 5)
        top, bottom = random_channel(rng, n, rng.randint(1, min(3, n)), 3)
        pieces = split_nets(top, bottom)
        if len(pieces) > 5:
            continue
        best = checker_optimum(top, bottom, pieces, 4)
        assert best == rule_optimum(pieces, piece_vcg(top, bottom, pieces), 4)
        r = dogleg_route(top, bottom)
        if r is None:
            assert best is None
            continue
        t, _, wires = r
        assert check_routing(top, bottom, t, wires) == []
        assert best is not None and t >= best >= density(top, bottom)


def test_against_rule_brute_force(seed: int = 9) -> None:
    rng = random.Random(seed)
    for _ in range(200):
        n = rng.randint(4, 9)
        top, bottom = random_channel(rng, n, rng.randint(2, min(5, n)), 3)
        pieces = split_nets(top, bottom)
        edges = piece_vcg(top, bottom, pieces)
        best = rule_optimum(pieces, edges, len(pieces))
        r = dogleg_route(top, bottom)
        if r is None:
            assert best is None
            continue
        t, _, wires = r
        assert check_routing(top, bottom, t, wires) == []
        assert t >= best >= density(top, bottom)


def test_two_pin_nets_have_one_piece(seed: int = 4) -> None:
    rng = random.Random(seed)
    for _ in range(200):
        n = rng.randint(3, 12)
        top, bottom = random_channel(rng, n, rng.randint(1, n // 2 + 1), 2)
        pieces = split_nets(top, bottom)
        assert len(pieces) == len(intervals(top, bottom))
        r = dogleg_route(top, bottom)
        if r is not None:
            assert check_routing(top, bottom, r[0], r[2]) == []

History

D. N. Deutsch presented the dogleg channel router at the 13th Design Automation Conference in 1976. The paper also gave a channel with density 19 that later papers call Deutsch's difficult example, and that served for years as the standard test of channel routers. In 1983 Burstein and Pelavin reported that their hierarchical router routed it in 19 tracks, and that the routers known to them needed 20 or more. Szymanski showed in 1985 that the fewest tracks with doglegs is NP-hard to find, so a fast exact dogleg router is not to be expected.

References

  1. D. N. Deutsch, A dogleg channel router, Proceedings of the 13th Design Automation Conference, 425 to 433, 1976, the cut of nets into pieces at their pin columns, the constraint graph of the pieces and the large test channel (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 (doglegs and the dogleg left-edge algorithm; 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 dogleg router; general locator)
  4. Thomas G. Szymanski, Dogleg channel routing is NP-complete, IEEE Transactions on Computer-Aided Design 4(1), 31 to 41, 1985, the hardness of the fewest tracks when nets may dogleg

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