Algorithm Search⌘K

Algorithmadvanced

Yoshimura-Kuh algorithm

Also called net merging channel router.

Channel routing that merges nets onto common tracks zone by zone, choosing merges that keep the longest path of the vertical constraint graph short, then runs left-edge.

Time
O(n N^2 (N + n)) worst
Space
Θ(N + n) extra
Where
N = the number of nets; n = the number of columns
Properties
deterministicnot exactiterative
Origin
Takeshi Yoshimura, Ernest S. Kuh, 1982

The Yoshimura-Kuh algorithm is a channel router without doglegs that decides first which nets share a track and only then which track each group gets. In the left-edge algorithm, the nets that share a track are picked greedily from the left, and a poor pick can make a chain of vertical constraints longer than needed. Yoshimura and Kuh cut the channel into zones, the maximal sets of nets that cross one column, and scan the zones from left to right. At each boundary between zones, a net that has ended may be merged with a net that starts after it, if no path of the vertical constraint graph joins them. Merged nets become one node of the graph and will share a track. Among the possible merges, the algorithm takes the one that keeps the longest path through the new node shortest. The groups then get their tracks by the left-edge rule.

In plain words

Some nets must lie above others, and these rules form chains. A chain of five nets needs five lanes, however short the nets are. So the danger is that the lanes fill up in a way that makes the chains long.

Walk along the channel. Each time some nets end and new nets begin, pair an ending net with a starting net, so that the two will later share one lane. Do not pair two nets that a chain of rules puts one above the other, since they can never share a lane. Among the pairs that are allowed, take the pair that makes the longest chain through it as short as possible.

When the walk is over, place the pairs and groups into lanes as the left-edge method does.

The problem

The input is a channel as on the page on the channel routing problem, with nets xx, closed intervals [lx,rx][l_x, r_x], and the vertical constraint graph GvG_v. The model is the reserved two-layer model without doglegs. The output is a track t(x)t(x) for each net, with disjoint intervals on each track and t(a)<t(b)t(a) < t(b) for each edge a→ba \to b of GvG_v, or the answer that GvG_v has a cycle. The goal is a small number of tracks TT.

Zones. Let S(c)S(c) be the set of nets that cross column cc. A set S(c)S(c) that is not contained in any other S(c′)S(c') is maximal. The zones Z1,Z2,…,ZmZ_1, Z_2, \ldots, Z_m are the different maximal sets, in the order of the columns where they occur. Each net lies in a run of consecutive zones, from its first zone to its last zone. The largest zone has dd nets, the channel density.

The algorithm

  1. YOSHIMURA-KUH(channel)
  2. 1build G_v; if G_v has a cycle then return "cycle"
  3. 2compute the zones Z_1, ..., Z_m; each group is one net
  4. 3L ← ∅
  5. 4for i ← 1 to m - 1 do
  6. 5add to L the groups whose last zone is Z_i
  7. 6R ← the groups whose first zone is Z_{i+1}
  8. 7while some a in L and b in R have no path between them in G_v do
  9. 8take such a pair with the least cost max(u(a), u(b)) + max(d(a), d(b)) - 1, ties by label
  10. 9merge b into a in G_v; remove a from L and b from R
  11. 10assign tracks to the groups with the left-edge scan on G_v, a group spanning its nets
  12. 11return the track of each net, the track of its group

Here u(v)u(v) is the number of nodes on a longest path of GvG_v that ends at vv, and d(v)d(v) the number on a longest path that starts at vv, both counted with vv. After the merge of aa and bb, the longest path through the new node has exactly the cost of line L8, so the rule picks the merge that keeps the paths through it shortest. Both numbers come from a longest path computation on the acyclic graph.

A merged group stays out of LL until its new last zone is reached, and then line L5 adds it again, so a group can take more nets at later boundaries. The groups in RR are always single nets, because a group made by a merge starts in an earlier zone.

Example

Take the channel

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

with I5=[1,4]I_5 = [1, 4], I2=[1,2]I_2 = [1, 2], I4=[3,8]I_4 = [3, 8], I1=[4,7]I_1 = [4, 7], I3=[5,6]I_3 = [5, 6] and d=3d = 3. The graph GvG_v is the path 1→5→21 \to 5 \to 2, and net 3 and net 4 have no edges. The left-edge algorithm uses 4 tracks here, because it puts net 4 alone on track 1.

The zones are Z1={2,5}Z_1 = \{2, 5\} (columns 1 and 2), Z2={1,4,5}Z_2 = \{1, 4, 5\} (column 4) and Z3={1,3,4}Z_3 = \{1, 3, 4\} (columns 5 and 6). The path numbers are u=1,3,1,1,2u = 1, 3, 1, 1, 2 and d=3,1,1,1,2d = 3, 1, 1, 1, 2 for nets 1, 2, 3, 4, 5.

  • Boundary 1. L={2}L = \{2\}, R={1,4}R = \{1, 4\}. Net 1 reaches net 2, so the pair (2,1)(2, 1) is out. The pair (2,4)(2, 4) costs max⁡(3,1)+max⁡(1,1)−1=3\max(3, 1) + \max(1, 1) - 1 = 3. Merge: nets 2 and 4 form one group.
  • Boundary 2. L={5}L = \{5\}, R={3}R = \{3\}. The pair (5,3)(5, 3) costs max⁡(2,1)+max⁡(2,1)−1=3\max(2, 1) + \max(2, 1) - 1 = 3. Merge: nets 5 and 3 form one group.

The groups are {1}\{1\}, {5,3}\{5, 3\} with span [1,6][1, 6], and {2,4}\{2, 4\} with span [1,8][1, 8], and the graph of the groups is the path {1}→{5,3}→{2,4}\{1\} \to \{5, 3\} \to \{2, 4\}. The left-edge scan puts net 1 on track 1, nets 5 and 3 on track 2, and nets 2 and 4 on track 3. That is 3 tracks, which is optimal, since the density is 3.

Correctness

The proof shows the following.

  • Merged nets are disjoint. When a net aa with last zone at most ZiZ_i is merged with a net bb with first zone Zi+1Z_{i+1}, the interval of aa ends before the interval of bb starts. So all nets of a group fit on one track.
  • No cycles. A merge of two nodes with no path between them keeps GvG_v acyclic. So the scan of line L10 places every group.
  • Legal routing. Groups on a track have disjoint spans, and every edge of GvG_v between nets becomes an edge between their groups, which the scan keeps.
  • Cycles are reported. If GvG_v has a cycle, no routing without doglegs exists, and line L1 says so.
Proof: The Yoshimura-Kuh merging keeps groups of disjoint nets and an acyclic constraint graph, so the final left-edge scan gives a legal routingfull

Let the zones be Zk=S(ck)Z_k = S(c_k) for columns c1<c2<⋯<cmc_1 < c_2 < \cdots < c_m, where S(c)S(c) is the set of nets whose closed interval holds cc. Then net xx lies in ZkZ_k exactly when lx≤ck≤rxl_x \le c_k \le r_x, so the zones that hold xx are a run of consecutive indices, from first(x)\mathrm{first}(x) to last(x)\mathrm{last}(x). Every set S(c)S(c) is contained in some zone, by the definition of maximal sets. The first and last zone of a group are those of its first and its last net.

Lemma 1 (order of merged nets). Let aa be a net with last(a)≤i\mathrm{last}(a) \le i and bb a net with first(b)=i+1\mathrm{first}(b) = i + 1. Then ra<lbr_a < l_b.

Proof. Since a∈Zlast(a)a \in Z_{\mathrm{last}(a)} and last(a)≤i\mathrm{last}(a) \le i, la≤cil_a \le c_i. Since a∉Zi+1a \notin Z_{i+1} and la≤ci<ci+1l_a \le c_i < c_{i+1}, ra<ci+1r_a < c_{i+1}. Since b∈Zi+1b \in Z_{i+1}, ci+1≤rbc_{i+1} \le r_b, and since b∉Zib \notin Z_i while ci<ci+1≤rbc_i < c_{i+1} \le r_b, ci<lbc_i < l_b. Suppose the intervals share a column cc. Then S(c)S(c) holds aa and bb and lies in some zone ZkZ_k, so lb≤ck≤ral_b \le c_k \le r_a. From ck≤ra<ci+1c_k \le r_a < c_{i+1} we get k≤ik \le i, and from ck≥lb>cic_k \ge l_b > c_i we get k≥i+1k \ge i + 1, a contradiction. So the intervals are disjoint, and la≤ci<lbl_a \le c_i < l_b puts aa on the left. □\square

Lemma 2 (groups). At every moment, the nets of a group have pairwise disjoint intervals, and in the order of their left ends each ends before the next starts. The last net of the group has the last zone of the group, and every group in RR is a single net.

Proof. By induction over the merges. A group made by a merge has the first zone of its oldest net, which is at most ii at boundary ii, so a group with first zone i+1i + 1 was never merged and is one net. A merge at boundary ii joins a group a∈La \in L, whose last net a′a' has last(a′)≤i\mathrm{last}(a') \le i, with a single net bb with first(b)=i+1\mathrm{first}(b) = i + 1. By Lemma 1, ra′<lbr_{a'} < l_b, and by the induction every other net of aa ends before a′a' starts. So bb comes after all nets of aa, and it becomes the last net, with the last zone of the new group. □\square

Lemma 3 (acyclic). If GvG_v is acyclic and aa and bb have no path between them, the graph made by merging bb into aa is acyclic.

Proof. A cycle in the new graph that avoids the merged node is a cycle of GvG_v. A cycle through it leaves along an edge of aa or of bb and comes back along an edge into aa or into bb. If it leaves from aa and returns into aa, or leaves from bb and returns into bb, the path between avoids the merged node, so it is a cycle of GvG_v. Otherwise it gives a path of GvG_v from aa to bb or from bb to aa, which is excluded. □\square

Lemma 4 (cost). After the merge of aa and bb, the longest path through the merged node has max⁡(u(a),u(b))+max⁡(d(a),d(b))−1\max(u(a), u(b)) + \max(d(a), d(b)) - 1 nodes.

Proof. A path through the merged node is a path that ends at aa or bb, followed by a path that starts at aa or bb, sharing the merged node. The parts before and after do not change, because no path joins aa and bb, so no longest path into aa passes through bb and the other way. The longest choices give the formula. □\square

Theorem 1 (legal routing). If GvG_v is acyclic, the algorithm returns tracks that form a legal routing without doglegs.

Proof. By Lemma 3, applied at every merge, the graph of groups stays acyclic. Line L10 is the left-edge scan on the groups, with the span of a group from its first left end to its last right end. By Lemmas 3 and 1 of the left-edge proof, it places every group, groups on one track have disjoint spans, and every edge of the graph of groups goes from a higher track to a lower one. By Lemma 2, the nets inside a group are disjoint and lie inside its span, so two nets on one track never share a column. An edge a→ba \to b of GvG_v between nets in different groups is an edge between their groups, so t(a)<t(b)t(a) < t(b). Nets aa and bb with an edge are never in one group, because a merge needs no path between them, and later merges keep the edge between their groups. Theorem 2 of the left-edge proof then gives a legal routing in the reserved two-layer model. □\square

Theorem 2 (termination). The algorithm stops.

Proof. Each merge lowers the number of groups by one, so at boundary ii the loop of lines L7 to L9 runs at most NN times. There are m−1m - 1 boundaries, and the scan of line L10 stops on an acyclic graph. □\square

Lower bound. Every result has at least max⁡(d,k)\max(d, k) tracks, with kk the number of nets on a longest path of the original GvG_v, since both bounds hold for every routing without doglegs.

Tests. The tests compare the implementation with two exhaustive searches over all maps from nets to tracks, one with a geometric checker of the wires and one with the rules of disjoint intervals and vertical constraints, on channels with up to 7 nets. They check that the result is legal, never below the optimum, that merged nets are disjoint, and that the zones equal those found by comparing all sets S(c)S(c).

Complexity

  • Time. The zones come from one sweep over the columns, keeping only the sets S(c)S(c) that are maximal, in O(n+N2)O(n + N^2) time with sets of nets. In this version, each try of line L7 recomputes uu and dd in O(N+n)O(N + n) and tests each pair by a search in O(N+n)O(N + n). There are at most NN merges and m−1<nm - 1 < n boundaries, and each try looks at fewer than N2N^2 pairs, so the time is O(nN2(N+n))O(n N^2 (N + n)). A reachability matrix updated after each merge makes the test of a pair O(1)O(1).
  • Space. Θ(N+n)\Theta(N + n) for the graph, the zones as runs of indices, and the groups.

Properties

  • What is proved. The result is a legal routing without doglegs whenever GvG_v is acyclic. It has at least max⁡(d,k)\max(d, k) tracks, where kk is the number of nets on a longest path of GvG_v.
  • What is only measured. The track count. On 1000 random channels of 12 columns and 7 nets with an acyclic GvG_v, this version matched the optimum without doglegs in 980 and used more tracks in 20. It used fewer tracks than left-edge in 133 and more in 11. These are tests on small random cases, not bounds.
  • Not always better than left-edge. The merges are greedy, one boundary at a time, and a merge that is cheap now can block a better one later.
  • No doglegs. On a cyclic GvG_v it fails, like left-edge. The form with doglegs below works on pieces of nets.

Variants and improvements

  • Merging by matching. Yoshimura and Kuh also give a form in which the merges at each boundary come from a bipartite matching between LL and RR, with weights that favor pairs on long paths. It looks at all pairs of a boundary at once.
  • Doglegs at pin columns. Cut the nets into pieces at their pin columns, as in dogleg channel routing, and merge the pieces. This can break cycles of GvG_v.
  • Looking ahead. Cost functions that also count the nets still to come, so that a merge does not use up a net that a later boundary needs.

When to use it

  • When GvG_v is acyclic and has long paths, so that left-edge wastes tracks.
  • When doglegs are not wanted, for example to keep the number of vias small.

When GvG_v has a cycle, use dogleg channel routing or the greedy channel router. When GvG_v has no edges, the left-edge algorithm is already optimal.

Pitfalls

  • Merging nets joined by a path. Two nets with a path between them in GvG_v need different tracks. Merging them makes a cycle, and the scan fails.
  • Zones that are not maximal. A set S(c)S(c) inside another one is not a zone. Keeping it gives extra boundaries and wrong first and last zones.
  • Stale path numbers. uu and dd change after every merge, because the merged node has the edges of both nets. Recompute them, or update them, before the next choice.
  • Spans of groups. The span of a group is from the left end of its first net to the right end of its last net. The scan of line L10 must use these spans, not the intervals of single nets, or two groups can overlap on a track.

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)
yoshimura_kuh_algorithm.py 172 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/yoshimura-kuh-algorithm/. The authors are listed in prov/MQ0AC7.jsonl.

"""Net merging channel routing after Yoshimura and Kuh, in the reserved two-layer model, without doglegs.

The columns are grouped into zones: the maximal sets of nets that cross one
column. The zones are scanned from left to right. At each zone boundary, a
net that has ended may be merged with a net that starts in the next zone, if
no path of the vertical constraint graph joins them. Merged nets share one
track. Of all such pairs, the pair that gives the shortest longest path
through the merged node is taken first. At the end, the merged nets get
their tracks with the constrained left-edge rule.

This is the version of the page: the cost of a merge is the length of the
longest path through the merged node. Yoshimura and Kuh also give a merge
step based on bipartite matching.
"""

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

from channel import intervals, realize, vcg_edges


def zones(top: Sequence[int], bottom: Sequence[int]) -> List[FrozenSet[int]]:
    """The maximal sets S(c) of nets that cross column c, in column order."""
    spans = intervals(top, bottom)
    sets = [frozenset(x for x, (l, r) in spans.items() if l <= c <= r) for c in range(1, len(top) + 1)]
    out: List[FrozenSet[int]] = []
    for s in sets:
        if s and not any(s < t for t in sets) and (not out or out[-1] != s):
            out.append(s)
    return out


def topological_order(nodes: Sequence[int], succ: Dict[int, Set[int]]) -> Optional[List[int]]:
    indeg = {v: 0 for v in nodes}
    for v in nodes:
        for w in succ[v]:
            indeg[w] += 1
    stack = sorted((v for v in nodes if indeg[v] == 0), reverse=True)
    order = []
    while stack:
        v = stack.pop()
        order.append(v)
        for w in sorted(succ[v], reverse=True):
            indeg[w] -= 1
            if indeg[w] == 0:
                stack.append(w)
    return order if len(order) == len(nodes) else None


def path_lengths(nodes, succ, pred) -> Tuple[Dict[int, int], Dict[int, int]]:
    """u[v]: nodes on the longest path that ends at v. d[v]: nodes on the longest path that starts at v."""
    order = topological_order(nodes, succ)
    u = {v: 1 for v in nodes}
    d = {v: 1 for v in nodes}
    for v in order:
        for w in succ[v]:
            u[w] = max(u[w], u[v] + 1)
    for v in reversed(order):
        for w in pred[v]:
            d[w] = max(d[w], d[v] + 1)
    return u, d


def reaches(succ: Dict[int, Set[int]], a: int, b: int) -> bool:
    seen, stack = {a}, [a]
    while stack:
        v = stack.pop()
        if v == b:
            return True
        for w in succ[v]:
            if w not in seen:
                seen.add(w)
                stack.append(w)
    return False


def merge_nets(top: Sequence[int], bottom: Sequence[int]):
    """Merge nets zone by zone. Returns (groups, group spans, successors), or None on a cycle.

    groups maps a group id (its first net) to its nets. A group span is
    (leftmost column, rightmost column) over its nets.
    """
    spans = intervals(top, bottom)
    succ: Dict[int, Set[int]] = {x: set() for x in spans}
    pred: Dict[int, Set[int]] = {x: set() for x in spans}
    for a, b in vcg_edges(top, bottom):  # @line L1
        succ[a].add(b)
        pred[b].add(a)
    if topological_order(sorted(spans), succ) is None:
        return None
    zs = zones(top, bottom)  # @line L2
    first = {x: min(i for i, z in enumerate(zs, 1) if x in z) for x in spans}
    last = {x: max(i for i, z in enumerate(zs, 1) if x in z) for x in spans}
    groups = {x: [x] for x in spans}
    gspan = dict(spans)
    left: List[int] = []  # @line L3
    for i in range(1, len(zs)):  # @line L4
        left += sorted(g for g in groups if last[g] == i)  # @line L5
        right = sorted(g for g in groups if first[g] == i + 1)  # @line L6
        while True:
            nodes = sorted(groups)
            u, d = path_lengths(nodes, succ, pred)
            best = None
            for a in left:  # @line L7
                for b in right:
                    if reaches(succ, a, b) or reaches(succ, b, a):
                        continue
                    cost = max(u[a], u[b]) + max(d[a], d[b]) - 1  # @line L8
                    if best is None or (cost, a, b) < best:
                        best = (cost, a, b)
            if best is None:
                break
            _, a, b = best
            groups[a] += groups.pop(b)  # @line L9
            gspan[a] = (gspan[a][0], gspan.pop(b)[1])
            last[a] = last.pop(b)
            first.pop(b)
            for w in succ.pop(b):
                pred[w].discard(b)
                pred[w].add(a)
                succ[a].add(w)
            for w in pred.pop(b):
                succ[w].discard(b)
                succ[w].add(a)
                pred[a].add(w)
            left.remove(a)
            right.remove(b)
    return groups, gspan, succ


def left_edge(spans: Dict[int, Tuple[int, int]], succ: Dict[int, Set[int]]) -> Dict[int, int]:
    """Constrained left-edge on groups: fill one track at a time; a group goes on track t
    when it does not overlap the last group on t and all its parents are on higher tracks."""
    parents: Dict[int, List[int]] = {g: [] for g in spans}
    for a, ws in succ.items():
        for b in ws:
            parents[b].append(a)
    unplaced = sorted(spans, key=lambda g: (spans[g][0], g))
    track: Dict[int, int] = {}
    t = 0
    while unplaced:
        t += 1
        last = None
        for g in unplaced:
            if (last is None or spans[g][0] > last) and all(track.get(p, t) < t for p in parents[g]):
                track[g] = t
                last = spans[g][1]
        unplaced = [g for g in unplaced if g not in track]
    return track


def yoshimura_kuh_route(top: Sequence[int], bottom: Sequence[int]):
    """Route a channel by net merging. Returns (tracks, track of each net, wires, groups), or None on a cycle."""
    merged = merge_nets(top, bottom)
    if merged is None:
        return None
    groups, gspan, succ = merged
    gtrack = left_edge(gspan, succ)  # @line L10
    track = {x: gtrack[g] for g, xs in groups.items() for x in xs}
    t = max(track.values(), default=0)
    spans = intervals(top, bottom)
    pieces = {x: (x, l, r) for x, (l, r) in spans.items()}
    return t, track, realize(top, bottom, pieces, track, t), groups  # @line L11


if __name__ == "__main__":
    top = [5, 0, 0, 1, 0, 0, 1, 0]
    bottom = [2, 2, 4, 5, 3, 3, 1, 4]
    print(zones(top, bottom))
    print(yoshimura_kuh_route(top, bottom)[:2])
test_yoshimura_kuh_algorithm.py 155 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/yoshimura-kuh-algorithm/. The authors are listed in prov/MQ0AC7.jsonl.

import itertools
import random

from channel import check_routing, density, intervals, realize, vcg_edges
from yoshimura_kuh_algorithm import merge_nets, yoshimura_kuh_route, zones


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


def rule_optimum(top, bottom, max_tracks: int):
    """The same optimum by backtracking: no overlap on a track, and a above b for each edge (a, b)."""
    spans = intervals(top, bottom)
    edges = set(vcg_edges(top, bottom))
    nets = sorted(spans)

    def fits(track, x, k):
        for y, j in track.items():
            if j == k and not (spans[x][1] < spans[y][0] or spans[y][1] < spans[x][0]):
                return False
            if ((x, y) in edges and k >= j) or ((y, x) in edges and j >= k):
                return False
        return True

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

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


def brute_zones(top, bottom):
    spans = intervals(top, bottom)
    sets = [frozenset(x for x, (l, r) in spans.items() if l <= c <= r) for c in range(1, len(top) + 1)]
    maximal = {s for s in sets if s and not any(s < t for t in sets)}
    return sorted(maximal, key=lambda s: min(c for c, t in enumerate(sets) if t == s))


def test_example_page() -> None:
    top = [5, 0, 0, 1, 0, 0, 1, 0]
    bottom = [2, 2, 4, 5, 3, 3, 1, 4]
    assert zones(top, bottom) == [frozenset({2, 5}), frozenset({1, 4, 5}), frozenset({1, 3, 4})]
    groups, gspan, _ = merge_nets(top, bottom)
    assert groups == {1: [1], 2: [2, 4], 5: [5, 3]}
    assert gspan == {1: (4, 7), 2: (1, 8), 5: (1, 6)}
    t, track, wires, _ = yoshimura_kuh_route(top, bottom)
    assert t == 3 == density(top, bottom)
    assert track == {1: 1, 5: 2, 3: 2, 2: 3, 4: 3}
    assert check_routing(top, bottom, t, wires) == []


def test_cycle() -> None:
    assert yoshimura_kuh_route([1, 2], [2, 1]) is None


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


def test_zones(seed: int = 1) -> None:
    rng = random.Random(seed)
    for _ in range(300):
        n = rng.randint(2, 12)
        top, bottom = random_channel(rng, n, rng.randint(1, min(6, n)), 3)
        assert zones(top, bottom) == brute_zones(top, bottom)


def test_merged_nets_are_disjoint(seed: int = 6) -> None:
    rng = random.Random(seed)
    for _ in range(300):
        n = rng.randint(3, 14)
        top, bottom = random_channel(rng, n, rng.randint(1, min(8, n)), 3)
        merged = merge_nets(top, bottom)
        if merged is None:
            continue
        spans = intervals(top, bottom)
        for xs in merged[0].values():
            for x, y in itertools.combinations(xs, 2):
                assert spans[x][1] < spans[y][0] or spans[y][1] < spans[x][0]
                assert (x, y) not in vcg_edges(top, bottom) and (y, x) not in vcg_edges(top, bottom)


def test_against_checker_brute_force(seed: int = 8) -> None:
    rng = random.Random(seed)
    for _ in range(120):
        n = rng.randint(2, 6)
        top, bottom = random_channel(rng, n, rng.randint(1, min(4, n)), 3)
        best = checker_optimum(top, bottom, 4)
        assert best == rule_optimum(top, bottom, 4)
        r = yoshimura_kuh_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 = 12) -> None:
    rng = random.Random(seed)
    for _ in range(200):
        n = rng.randint(4, 11)
        top, bottom = random_channel(rng, n, rng.randint(2, min(7, n)), 3)
        best = rule_optimum(top, bottom, 7)
        r = yoshimura_kuh_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)

History

Takeshi Yoshimura and Ernest S. Kuh published the method in 1982, in the first issue of the IEEE Transactions on Computer-Aided Design. They took the vertical constraint graph and the zone representation of the channel as the main objects, and merged nets to keep the longest path of the graph short, since that path bounds the tracks from below when there are no doglegs. Their paper gave a merge rule based on path lengths and a second one based on bipartite matching, and a form with pieces of nets. Szymanski showed in 1985 that the general problem with doglegs is NP-complete, and LaPaugh had shown the same in 1980 for the problem without doglegs, so such heuristics remained the practical approach.

References

  1. T. Yoshimura and E. S. Kuh, Efficient algorithms for channel routing, IEEE Transactions on Computer-Aided Design 1(1), 25 to 35, 1982, the zone representation, the merging of nets that keeps the longest path of the vertical constraint graph short, and the form with bipartite matching (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 (zones and the vertical constraint graph; 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 Yoshimura-Kuh router and the merging of nets; 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