Algorithm Search⌘K

Algorithmcore

Left-edge algorithm

Also called Hashimoto-Stevens algorithm.

Hashimoto and Stevens's channel router that sorts intervals by left end and fills each track greedily, which meets the density bound without vertical constraints.

Time
O(n + N log N + T (N + n)) worst
Space
Θ(N + n) extra
Where
N = the number of nets; T = the number of tracks used; n = the number of columns
Properties
deterministicnot exactiterative
Origin
A. Hashimoto, J. Stevens, 1971

The left-edge algorithm is the first channel router. It solves the channel routing problem without doglegs: each net gets one trunk on one track. It fills the tracks one at a time from the top. On each track it runs through the nets in the order of their left ends, and it puts a net on the track when the net does not overlap the last net there and all the nets that must lie above it, by the vertical constraint graph, are already on higher tracks. When the channel has no vertical constraints, this is the greedy method for interval partitioning, and it uses exactly dd tracks, the channel density, which is optimal. With vertical constraints it is a heuristic: it can use more tracks than needed, and it stops when the constraint graph has a cycle.

In plain words

Think of the nets as sticks of different lengths laid along a ruler. Each lane of the channel can hold sticks that do not touch. Sort the sticks by where they start.

Fill the first lane: take the first stick, then the next stick that starts after it ends, and so on to the end of the ruler. Then fill the second lane with the sticks that are left in the same way, and go on until no stick is left.

Some sticks must lie in a lane above some others, because their pins face each other across the channel. A stick may go into the current lane only when all sticks that must be above it are already in higher lanes. If a whole lane stays empty, the rules contradict each other, and the method gives up.

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. Each net xx has the interval [lx,rx][l_x, r_x] of columns from its first to its last pin. The vertical constraint graph GvG_v has an edge a→ba \to b when some column has aa on top and bb at the bottom.

The output is a track t(x)∈{1,…,T}t(x) \in \{1, \ldots, T\} for each net, with track 1 at the top, such that:

  • two nets on the same track have disjoint intervals;
  • every edge a→ba \to b of GvG_v has t(a)<t(b)t(a) < t(b).

From the tracks, the wires follow: a trunk of xx on track t(x)t(x) from column lxl_x to column rxr_x on layer H, and a branch on layer V from each pin to the trunk. The goal is a small TT.

The algorithm

  1. LEFT-EDGE(nets x with intervals [l_x, r_x], constraint graph G_v)
  2. 1sort the nets by left end l_x, with ties broken by label
  3. 2t ← 0; U ← all nets, in this order
  4. 3while U is not empty do
  5. 4t ← t + 1; last ← none
  6. 5for each net x in U, in order do
  7. 6if (last is none or l_x > last) and every parent of x in G_v has a track < t then
  8. 7t(x) ← t; last ← r_x
  9. 8remove from U the nets placed on track t
  10. 9if no net was placed on track t then return "cycle"
  11. 10return the tracks t(x)

Line L6 holds both rules. The test lx>lastl_x > \mathit{last} keeps the nets on a track disjoint. The intervals are closed, so a net that starts in the column where the last one ends must wait. The test on the parents keeps the vertical constraints. A parent that is not yet placed, or that is placed on the current track, blocks xx for this track.

Example

Take the channel

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

The intervals are I1=[1,4]I_1 = [1, 4], I2=[4,10]I_2 = [4, 10], I3=[1,7]I_3 = [1, 7], I4=[6,8]I_4 = [6, 8], I5=[9,10]I_5 = [9, 10] and I6=[2,8]I_6 = [2, 8]. The local densities are 2, 3, 3, 4, 3, 4, 4, 3, 2, 2, so d=4d = 4. The constraint graph has the edges 1→21 \to 2, 1→31 \to 3, 4→64 \to 6, 5→25 \to 2 and 6→36 \to 3. Line L1 gives the order 1, 3, 6, 2, 4, 5.

track scan placed
1 1 placed, last = 4; 3 blocked (parent 1 is on this track); 6 blocked (parent 4 not placed); 2 overlaps; 4 placed, last = 8; 5 placed 1, 4, 5
2 3 blocked (parent 6 not placed); 6 placed, last = 8; 2 overlaps 6
3 3 placed, last = 7; 2 overlaps 3
4 2 placed 2

The result uses 4 tracks, which is dd, so it is optimal. The vertical constraints matter here. Without them, the same scan puts net 3 on track 2 and net 6 on track 3. Column 7 has net 6 on top and net 3 at the bottom, so the branch of 6 would come down to track 3 through the point where the branch of 3 leaves track 2, and the routing would be illegal.

A channel where left-edge is not optimal. Take

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], edges 1→51 \to 5 and 5→25 \to 2, and d=3d = 3. Left-edge puts net 4 on track 1, since it is the first net in order with no parent, and then nothing else fits there. It goes on with net 1 on track 2, nets 5 and 3 on track 3, and net 2 on track 4. That is 4 tracks. Three tracks are enough: net 1 on track 1, nets 5 and 3 on track 2, nets 2 and 4 on track 3. The greedy choice of net 4 for the top track is the mistake, because net 4 has no constraint and could go lower. The Yoshimura-Kuh algorithm finds the 3-track routing.

Correctness

The proof shows the following.

  • Legal tracks. On each track, the nets are placed in order of their left ends, and each starts after the right end of the one before, so their intervals are disjoint. Every net is placed only when its parents are on higher tracks, so every edge a→ba \to b has t(a)<t(b)t(a) < t(b).
  • Termination when GvG_v is acyclic. Some unplaced net has all its parents placed. The first such net in the order is placed on the next track, so each pass places at least one net, and the algorithm stops after at most NN passes.
  • Cycles are reported. A net on a cycle is never placed, because one of its parents on the cycle is never placed before it. So when GvG_v has a cycle, a pass places nothing and line L9 reports it. When GvG_v is acyclic, line L9 never fires.
  • Density without vertical constraints. If GvG_v has no edges, a net on track kk was rejected on tracks 1,…,k−11, \ldots, k - 1, each time because of a net on that track that holds its left end. So kk nets cross the column lxl_x, and k≤dk \le d. The interval coloring depth theorem gives the matching lower bound.
Proof: The left-edge algorithm returns a legal routing without doglegs, reports every cycle, and uses d tracks when there are no vertical constraintsfull

Let the nets be xx with closed intervals Ix=[lx,rx]I_x = [l_x, r_x], let GvG_v be the vertical constraint graph, and let ≺\prec be the order of line L1: by left end, then by label. Call pass tt the run of lines L4 to L9 with the value tt. Let NN be the number of nets.

Lemma 1 (disjoint intervals on a track). The nets placed on one track have pairwise disjoint intervals, and after each placement, last\mathit{last} is the largest right end on the track.

Proof. Within pass tt the nets are scanned in the order ≺\prec. Let y1,y2,…y_1, y_2, \ldots be the nets placed on track tt, in the order of placement. When yj+1y_{j+1} is placed, line L6 gives lyj+1>ryjl_{y_{j+1}} > r_{y_j}, and ryjr_{y_j} is the largest right end so far by induction. So Iyj+1I_{y_{j+1}} starts after every interval already on the track, and its right end ryj+1≥lyj+1>ryjr_{y_{j+1}} \ge l_{y_{j+1}} > r_{y_j} is the new largest. □\square

Lemma 2 (vertical constraints). For every edge a→ba \to b of GvG_v with both nets placed, t(a)<t(b)t(a) < t(b).

Proof. When bb is placed on track tt, line L6 requires its parent aa to have a track less than tt. A net keeps its track for ever, so t(a)<t(b)t(a) < t(b). □\square

Lemma 3 (progress). If GvG_v restricted to the unplaced nets UU at the start of pass tt has a node with no parent in UU, then pass tt places at least one net.

Proof. Let xx be the first net in the order ≺\prec among the nets of UU whose parents are all outside UU. All its parents were placed in earlier passes, so they have tracks less than tt. If some net is placed before xx is scanned, the claim holds. Otherwise last\mathit{last} is still none when xx is scanned, and line L6 accepts xx. □\square

Lemma 4 (nets on a cycle are never placed). If x1→x2→⋯→xk→x1x_1 \to x_2 \to \cdots \to x_k \to x_1 is a cycle of GvG_v, no net of the cycle is ever placed.

Proof. Suppose some net of the cycle is placed, and let xix_i be the first one placed, in a pass tt. Its parent xi−1x_{i-1} on the cycle (with x0=xkx_0 = x_k) is not placed before xix_i. If it is still unplaced, line L6 rejects xix_i. If it is placed earlier in the same pass, it is on track tt, and line L6 rejects xix_i too. Both contradict the choice of xix_i. □\square

Theorem 1 (termination and cycle detection). If GvG_v is acyclic, the algorithm returns a track for every net after at most NN passes, and line L9 never fires. If GvG_v has a cycle, the algorithm returns "cycle" after at most N+1N + 1 passes.

Proof. If GvG_v is acyclic, so is its restriction to UU, and an acyclic graph with a node has a node with no parent. By Lemma 3, every pass places a net, so UU is empty after at most NN passes. If GvG_v has a cycle, by Lemma 4 its nets stay in UU for ever. The nets not on any cycle are placed at most once each, so at most NN passes place a net. A pass that places nothing makes line L9 return "cycle". □\square

Theorem 2 (legal routing). If the algorithm returns tracks t(x)t(x) with T=max⁡xt(x)T = \max_x t(x), then the routing with a trunk of xx on track t(x)t(x) over the columns of IxI_x on layer H, and a branch on layer V from each pin of xx straight to track t(x)t(x), is legal in the reserved two-layer model.

Proof. On layer H, two nets share a point only if they are on the same track and their intervals share a column. By Lemma 1 this does not happen. On layer V, the branches in column cc are the segment of top(c)\mathrm{top}(c) from row 0 to its track and the segment of bot(c)\mathrm{bot}(c) from its track to row T+1T + 1. If the two pins belong to the same net, the two segments belong to one net. If they belong to nets a≠ba \ne b, then a→ba \to b is an edge of GvG_v, and by Lemma 2 t(a)<t(b)t(a) < t(b), so the two segments are disjoint. Each via is at a point (c,t(x))(c, t(x)) with cc a pin column of xx, so c∈Ixc \in I_x and the trunk of xx holds that point on layer H. Each net is connected, because each branch reaches the trunk. □\square

Theorem 3 (optimal without vertical constraints). If GvG_v has no edges, the algorithm uses exactly dd tracks, where dd is the channel density, and no routing uses fewer.

Proof. Let xx be a net placed on track kk. For each j<kj < k, net xx was scanned in pass jj and rejected. With no parents, the only reason is lx≤lastl_x \le \mathit{last}, and last=ry\mathit{last} = r_y for a net yy already placed on track jj with y≺xy \prec x, so ly≤lxl_y \le l_x. So ly≤lx≤ryl_y \le l_x \le r_y, and yy crosses column lxl_x. The nets yy for different jj lie on different tracks and are different, and none of them is xx. So at least kk nets cross column lxl_x, and k≤d(lx)≤dk \le d(l_x) \le d. Hence T≤dT \le d. The density bound on the page on channel density, or the interval coloring depth theorem, gives T≥dT \ge d for every routing. □\square

Theorem 4 (running time). The algorithm runs in O(n+Nlog⁡N+T(N+n))O(n + N \log N + T(N + n)) time and Θ(N+n)\Theta(N + n) space.

Proof. One pass over the columns gives the intervals and the at most nn edges of GvG_v. Line L1 sorts NN nets. Each pass scans the nets of UU once, checks each parent of each scanned net once, and filters UU once, in O(N+n)O(N + n) time. There are TT passes, plus one more when a cycle is reported, and T≤NT \le N. □\square

Tests. The tests compare the implementation with two exhaustive searches over all maps from nets to tracks: one that builds the wires of each map and runs a geometric checker, and one that applies the rules of disjoint intervals and vertical constraints by backtracking, on channels with up to 6 nets. The track count of left-edge is never below the optimum, and it is above it on some cases. On channels with one pin per column, it always equals the density.

Complexity

  • Time. The intervals and the edges of GvG_v come from one pass over the columns, in O(n)O(n) time. Sorting takes O(Nlog⁡N)O(N \log N). Each pass of lines L5 to L8 looks at each unplaced net once and at each of its parents, in O(N+n)O(N + n) time, since GvG_v has at most nn edges. With TT passes, the total is O(n+Nlog⁡N+T(N+n))O(n + N \log N + T(N + n)). In the worst case T=NT = N and this is quadratic.
  • No vertical constraints. The track-by-track scan is not needed then. The one-pass form of interval partitioning, which keeps the free tracks in a heap, gives a routing with dd tracks in O(n+Nlog⁡N)O(n + N \log N) time.
  • Space. Θ(N+n)\Theta(N + n) for the intervals, the graph and the tracks.

Properties

  • What is proved. Every result is a legal routing without doglegs. With no vertical constraints, it uses dd tracks, which is optimal. A cycle of GvG_v is always reported.
  • What is only measured. With vertical constraints, the track count is a heuristic result. On 1000 random channels of 12 columns and 7 nets with an acyclic GvG_v, left-edge matched the optimum without doglegs in 858 and used more tracks in 142. That is a test on small random cases, not a bound.
  • No doglegs. It never splits a net, so a channel with a cyclic GvG_v is out of its reach. Dogleg channel routing extends it to pieces of nets.
  • Deterministic. The order of line L1 and the fixed tie rule fix the result.
  • Track order. Filling from the top is a choice. Filling from the bottom with the constraints reversed is the same method, and routers often try both and keep the better result.

Variants and improvements

  • Basic left-edge. Without vertical constraints, assign each net in order of left ends to any track whose last net ends before it. This is the greedy rule of interval partitioning, and it gives dd tracks.
  • Constrained left-edge. The form on this page, with the parent test of line L6.
  • Dogleg left-edge. Split each net at its pin columns and apply the same scan to the pieces. This is dogleg channel routing.
  • Merging first. The Yoshimura-Kuh algorithm first merges nets into groups that share a track, chosen to keep the longest path of GvG_v short, and then runs left-edge on the groups.
  • Both directions. Fill tracks from the top and from the bottom at the same time, and pick at each step the side where the next net fits better.

When to use it

  • When a channel has no vertical constraints, for example when all pins are on one side, or each column has only one pin. Then the result is optimal.
  • As a fast first try, or as the last step of a router that has already fixed the groups of nets on each track.
  • To teach channel routing, since each step can be traced by hand.

When the constraint graph has a cycle, use dogleg channel routing or the greedy channel router. When the track count matters, compare with the Yoshimura-Kuh algorithm.

Pitfalls

  • Half-open intervals. A net that starts in the column where another ends cannot share its track, because both need the point of that track in that column. The test must be lx>lastl_x > \mathit{last}, not lx≥lastl_x \ge \mathit{last}.
  • Parents on the current track. A parent placed earlier in the same pass is on track tt, not above it. The test must be t(p)<tt(p) < t, or the two branches meet.
  • Assuming the density bound is met. With vertical constraints, dd is only a lower bound, and the longest path of GvG_v can be larger. Report the result against max⁡(d,kmax⁡)\max(d, k_{\max}), the larger of the two bounds.
  • Nets in one column. A net with all pins in one column has no trunk. Leave it out, or it blocks a track for nothing.
  • Unbounded loop. Without the check of line L9, a cyclic channel makes the algorithm open new tracks forever.

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)
left_edge_algorithm.py 64 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/left-edge-algorithm/. The authors are listed in prov/NN5MVW.jsonl.

"""The left-edge channel router, with the vertical constraints of the reserved two-layer model.

Each net gets one trunk on one track (no doglegs). Tracks are filled one at a
time from the top. Within a track, the nets are tried in the order of their
left ends, and a net is placed when it does not overlap the last net on the
track and all its parents in the vertical constraint graph are on higher tracks.
"""

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

from channel import intervals, realize, vcg_edges


def left_edge(spans: Dict[int, Tuple[int, int]], edges: Sequence[Tuple[int, int]]) -> Optional[Dict[int, int]]:
    """Assign a track (1 = top) to each net. spans maps a net to (left, right).

    edges are the vertical constraints (a, b): a must be on a higher track than b.
    Returns None when the constraints have a cycle.
    """
    parents: Dict[int, List[int]] = {x: [] for x in spans}
    for a, b in edges:
        parents[b].append(a)
    order = sorted(spans, key=lambda x: (spans[x][0], x))  # @line L1
    track: Dict[int, int] = {}
    t = 0  # @line L2
    unplaced = list(order)
    while unplaced:  # @line L3
        t += 1  # @line L4
        last = None
        now = []
        for x in unplaced:  # @line L5
            free = last is None or spans[x][0] > last
            if free and all(track.get(p, t) < t for p in parents[x]):  # @line L6
                track[x] = t  # @line L7
                last = spans[x][1]
                now.append(x)
        unplaced = [x for x in unplaced if x not in track]  # @line L8
        if not now:  # @line L9
            return None
    return track  # @line L10


def left_edge_route(top: Sequence[int], bottom: Sequence[int]):
    """Route a channel with the left-edge algorithm.

    Returns (number of tracks, track of each net, wires), or None if the
    vertical constraint graph has a cycle.
    """
    spans = intervals(top, bottom)
    track = left_edge(spans, vcg_edges(top, bottom))
    if track is None:
        return None
    t = max(track.values(), default=0)
    pieces = {x: (x, l, r) for x, (l, r) in spans.items()}
    return t, track, realize(top, bottom, pieces, track, t)


if __name__ == "__main__":
    top = [1, 0, 2, 1, 3, 0, 4, 0]
    bottom = [0, 2, 0, 3, 0, 4, 0, 3]
    print(left_edge_route(top, bottom)[:2])
test_left_edge_algorithm.py 161 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/left-edge-algorithm/. The authors are listed in prov/NN5MVW.jsonl.

import itertools
import random

from channel import check_routing, density, intervals, realize, vcg_edges
from left_edge_algorithm import left_edge, left_edge_route


def random_channel(rng: random.Random, n: int, nets: int, maxpins: int, one_side: bool = False):
    """A random channel of n columns. With one_side, each column has at most one pin."""
    while True:
        if one_side:
            slots = [(c, rng.choice("TB")) for c in range(n)]
        else:
            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 no_dogleg_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 no_dogleg_optimum_fast(top, bottom, max_tracks: int):
    """The same optimum, with the two rules written out: no overlap on a track, and every edge a -> b has a above b."""
    spans = intervals(top, bottom)
    edges = 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 test_example_page() -> None:
    top = [1, 0, 3, 1, 0, 4, 6, 4, 0, 5]
    bottom = [3, 6, 0, 2, 2, 0, 3, 6, 5, 2]
    assert intervals(top, bottom) == {1: (1, 4), 2: (4, 10), 3: (1, 7), 4: (6, 8), 5: (9, 10), 6: (2, 8)}
    assert vcg_edges(top, bottom) == [(1, 2), (1, 3), (4, 6), (5, 2), (6, 3)]
    assert density(top, bottom) == 4
    t, track, wires = left_edge_route(top, bottom)
    assert t == 4
    assert track == {1: 1, 4: 1, 5: 1, 6: 2, 3: 3, 2: 4}
    assert check_routing(top, bottom, t, wires) == []
    # Without the vertical constraints, net 3 would take track 2 and short with net 6 in column 7.
    free = left_edge(intervals(top, bottom), [])
    assert free[3] == 2 and free[6] == 3
    pieces = {x: (x, l, r) for x, (l, r) in intervals(top, bottom).items()}
    assert check_routing(top, bottom, 4, realize(top, bottom, pieces, free, 4)) != []


def test_example_not_optimal() -> None:
    top = [5, 0, 0, 1, 0, 0, 1, 0]
    bottom = [2, 2, 4, 5, 3, 3, 1, 4]
    assert density(top, bottom) == 3
    t, track, wires = left_edge_route(top, bottom)
    assert t == 4 and track == {4: 1, 1: 2, 5: 3, 3: 3, 2: 4}
    assert check_routing(top, bottom, t, wires) == []
    assert no_dogleg_optimum(top, bottom, 4) == 3


def test_cycle() -> None:
    top, bottom = [1, 2], [2, 1]
    assert left_edge_route(top, bottom) is None
    assert no_dogleg_optimum(top, bottom, 3) is None


def test_edges() -> None:
    assert left_edge({}, []) == {}
    assert left_edge({1: (1, 2)}, []) == {1: 1}
    assert left_edge({1: (1, 2), 2: (2, 3)}, []) == {1: 1, 2: 2}
    assert left_edge({1: (1, 2), 2: (3, 4)}, []) == {1: 1, 2: 1}
    assert left_edge({1: (1, 2), 2: (3, 4)}, [(2, 1)]) == {2: 1, 1: 2}


def test_no_constraints_meets_density(seed: int = 11) -> None:
    rng = random.Random(seed)
    for _ in range(300):
        n = rng.randint(4, 14)
        top, bottom = random_channel(rng, n, rng.randint(1, n // 2), 3, one_side=True)
        assert vcg_edges(top, bottom) == []
        t, track, wires = left_edge_route(top, bottom)
        assert t == density(top, bottom)
        assert check_routing(top, bottom, t, wires) == []


def test_against_checker_brute_force(seed: int = 5) -> 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 = no_dogleg_optimum(top, bottom, 4)
        assert best == no_dogleg_optimum_fast(top, bottom, 4)
        r = left_edge_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_fast_brute_force(seed: int = 3) -> None:
    rng = random.Random(seed)
    worse = 0
    for _ in range(150):
        n = rng.randint(4, 10)
        top, bottom = random_channel(rng, n, rng.randint(2, min(6, n)), 3)
        best = no_dogleg_optimum_fast(top, bottom, 6)
        r = left_edge_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)
        worse += t > best
    assert worse > 0

History

A. Hashimoto and J. Stevens presented the method at the 8th Design Automation Workshop in 1971, the meeting that later became the Design Automation Conference. They treated the wiring between rows of cells as the assignment of intervals to tracks. The rule of taking the intervals in order of left ends gave the method its name. The same greedy rule appears in scheduling and in the coloring of interval graphs, where it is optimal. Channel routers of the 1970s added the vertical constraints in the form given here. Deutsch in 1976 applied the scan to pieces of nets to get around cycles, and Yoshimura and Kuh in 1982 merged nets before the scan to need fewer tracks.

References

  1. A. Hashimoto and J. Stevens, Wire routing by optimizing channel assignment within large apertures, Proceedings of the 8th Design Automation Workshop, 155 to 169, 1971, the assignment of trunks to tracks in order of their left ends (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 left-edge algorithm with vertical constraints; 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 basic and the constrained left-edge algorithm; general locator)
  4. T. Yoshimura and E. S. Kuh, Efficient algorithms for channel routing, IEEE Transactions on Computer-Aided Design 1(1), 25 to 35, 1982, the left-edge assignment as the last step after the merging of nets, and channels where it needs more tracks than the optimum (general locator)

Where this leads

About this page

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

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.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