Algorithm Search⌘K

Algorithmadvanced

Gemini netlist comparison

Also called Ebeling netlist comparison, Gemini LVS, GeminiII.

Ebeling and Zajicek's LVS algorithm that labels devices and nets by local invariants and refines the labels iteratively, then breaks ties by guessing.

Time
O((n + m) (P + n + m) log(n + m)) one_refinement2^O((n + m) log(n + m)) with_backtracking_worstO((n + m)^2 (P + n + m) log(n + m)) with_guesses_no_backtracking
Space
O(n + m + P) extra
Where
P = the number of pins; m = the number of nets; n = the number of devices
Properties
deterministicexactrecursive
Origin
Carl Ebeling, Ofer Zajicek, 1983

Gemini is an algorithm that decides whether two transistor netlists are the same circuit, and if they are, gives the matching of their devices and nets. It is the classic method for layout versus schematic checking: it gives each device and each net a label from local facts, refines the labels again and again from the labels of the neighbours, and when the labels stop splitting it pairs two vertices with the same label by a guess and goes on. Carl Ebeling and Ofer Zajicek published it in 1983, and Ebeling's GeminiII followed in 1988. The refinement step is color refinement run on the two netlists at the same time.

In plain words

Two people draw the same circuit, but they name the wires differently and list the parts in another order. To check that the drawings agree, give every part and every wire a short description: "a transistor", "a wire that touches three parts". Then improve each description with the descriptions of its neighbours: "a transistor whose gate wire touches two parts". Do the same in both drawings at once, with the same rules.

If one drawing has more things with some description than the other, the drawings differ, and that description points to the place. If every description is unique, each thing matches the one thing with the same description in the other drawing. If some things still look alike, they are often copies of the same cell: pair one from each side by a guess, mark them, and go on.

The problem

A netlist has devices and nets. Each device has a type, and each pin of a device has a pin class and a net. Pins of one class are interchangeable, like the source and the drain of a MOS transistor or the two ends of a resistor. Some nets carry names that must match, such as the supplies and the ports. Two netlists are isomorphic when there are bijections π\pi on the devices and φ\varphi on the nets that keep the types, keep the names, and map the multiset of nets on the pins of class cc of each device uu to the multiset on the pins of class cc of π(u)\pi(u).

This is graph isomorphism of two bipartite graphs, one vertex per device and per net and one edge per pin, with the pin class as the colour of the edge. The output is the pair (π,φ)(\pi, \varphi), or a report of a difference. Costs are counted in the number of devices nn, of nets mm and of pins PP.

The algorithm

  1. GEMINI(G, G′)
  2. 1give each device the label of its type, and each net the label (name or none, number of pins)
  3. 2return SEARCH(λ)
  4. SEARCH(λ) ▷ λ labels the vertices of G and G′ together
  5. 3repeat
  6. 4for each net v of G and G′: key(v) ← (λ(v), multiset of (pin class, λ(u)) over the pins on v)
  7. 5for each device u: key(u) ← (λ(u), multiset of (pin class, λ(v)) over the pins of u) ▷ with the new net labels
  8. 6(after L4 and after L5) renumber the keys of both netlists with one table
  9. 7if some label has more vertices in G than in G′, or fewer, then return MISMATCH(that label)
  10. 8until the number of labels did not grow
  11. 9if every label has one vertex in G and one in G′ then return the map from G to G′ by equal labels
  12. 10choose a smallest label class K with two or more vertices on each side, and a vertex x of K in G
  13. 11for each vertex y of K in G′ do
  14. 12give x and y one new label; r ← SEARCH(λ); if r is a map then return r
  15. 13return the last MISMATCH

Line L1 uses only facts that every isomorphism keeps. Lines L4 to L6 are one round of colour refinement, done on the union of the two netlists, so that a label means the same thing on both sides. Line L7 compares the sizes of the classes, which is where a difference shows. Line L12 is the guess, which Ebeling and Zajicek describe as a heuristic step for the symmetric parts of a circuit. The version above tries the other candidates of line L11 when a guess leads to a mismatch, which makes it exact; with only the first candidate it is the plain guessing comparator.

Example

The schematic is a CMOS NAND gate with inputs A and B and output Y. P1 is a p-transistor with gate A between Y and VDD, P2 a p-transistor with gate B between VDD and Y, N1 an n-transistor with gate A between Y and X, and N2 an n-transistor with gate B between X and GND. The extracted layout has the nets n1 to n6, with n4 named VDD and n6 named GND, and the devices in this order: 0 is an n-transistor with gate n2 between n6 and n5, 1 a p-transistor with gate n1 between n4 and n3, 2 an n-transistor with gate n1 between n3 and n5, and 3 a p-transistor with gate n2 between n3 and n4. Each transistor has the pin classes gate, and source or drain twice.

step classes of the schematic classes of the layout
L1, devices {N1, N2}, {P1, P2} {0, 2}, {1, 3}
L1, nets {A, B, X} (2 pins), {Y} (3 pins), {GND}, {VDD} {n1, n2, n5}, {n3}, {n6}, {n4}
round 1, nets {A, B}, {X}, {Y}, {GND}, {VDD} {n1, n2}, {n5}, {n3}, {n6}, {n4}
round 1, devices {N1}, {N2}, {P1, P2} {2}, {0}, {1, 3}
round 2, nets {A}, {B}, {X}, {Y}, {GND}, {VDD} {n1}, {n2}, {n5}, {n3}, {n6}, {n4}
round 2, devices {N1}, {N2}, {P1}, {P2} {2}, {0}, {1}, {3}

In round 1 the nets A and B (one p gate and one n gate each) part from X (two n sources or drains), and the device N1 (on Y and X) parts from N2 (on X and GND). In round 2 the net A, the gate of N1, parts from B, the gate of N2, and then P1 parts from P2. Round 3 splits nothing. Every class has one member on each side, so line L9 returns A to n1, B to n2, X to n5, Y to n3, VDD to n4, GND to n6, and P1, P2, N1, N2 to devices 1, 3, 2, 0. No guess was needed.

If the layout had A at the bottom of the n stack and B at the top, the two netlists would still be isomorphic, with A and B exchanged: without names the comparator cannot tell which input drives the transistor at the bottom of the stack, although that changes the delay. Naming the ports A and B makes this a mismatch at round 1. A ring of six equal resistors against two rings of three is the opposite case: every net has two pins and every resistor two neighbours, the refinement never splits a class, and only a guess shows the difference.

Correctness

The proof is in proofs/correctness.md. The labels are sound: every isomorphism that agrees with the guesses made so far maps each vertex to a vertex with the same label. Line L1 is sound because types, names and pin counts are kept by an isomorphism, a round of lines L4 to L6 keeps soundness because the key of a vertex is built from its neighbours with their pin classes, and a guess keeps soundness for the isomorphisms that agree with it. So a class with different sizes on the two sides proves that no such isomorphism exists. When every class has one member on each side and the labels are stable, the map by equal labels is an isomorphism, because each device has the same multiset of (pin class, net label) as its image, and each net label names one net on each side. With backtracking, the candidate y=f(x)y = f(x) of some isomorphism ff is always among those tried, so a match is found whenever one exists.

Proof: Gemini netlist comparison reports only real differences, and with backtracking it finds a match whenever one existsfull

We use the model and the pseudocode of the page. A netlist GG has a set DD of devices, a set VV of nets and a set of named nets. Each device uu has a type τ(u)\tau(u), and each pin of uu has a pin class and a net. For a device uu and a pin class cc, let Nc(u)N_c(u) be the multiset of nets on the pins of uu of class cc. Two netlists GG and G′G' are isomorphic when there are bijections π:D→D′\pi : D \to D' and φ:V→V′\varphi : V \to V' such that

  1. τ(π(u))=τ(u)\tau(\pi(u)) = \tau(u) and φ(Nc(u))=Nc(π(u))\varphi(N_c(u)) = N_c(\pi(u)) for every device uu and class cc, and
  2. a named net vv maps to the net φ(v)\varphi(v) with the same name, and an unnamed net to an unnamed net.

Write f=π∪φf = \pi \cup \varphi for the map on all vertices of the bipartite device and net graph. The algorithm keeps one label λ(x)\lambda(x) for each vertex xx of GG and of G′G', from one common set of labels.

Definition. A labeling is sound for a set of pairs I={(x1,y1),…,(xr,yr)}I = \{(x_1, y_1), \ldots, (x_r, y_r)\} if every isomorphism ff with f(xi)=yif(x_i) = y_i for all ii also has λ(f(x))=λ(x)\lambda(f(x)) = \lambda(x) for every vertex xx of GG.

Lemma 1 (the start is sound). The labels of line L1 are sound for I=∅I = \emptyset.

Proof. A device gets its type, and an isomorphism keeps the type. A net gets its name (or the empty name) and its number of pins. An isomorphism keeps the name by condition 2. The number of pins of a net vv is the number of pairs (device uu, pin of uu) with net vv, which is the sum over uu and cc of the multiplicity of vv in Nc(u)N_c(u). By condition 1 it equals the same sum for φ(v)\varphi(v). □\square

Lemma 2 (relabeling keeps soundness). If λ\lambda is sound for II, then the labels after one pass of lines L4 to L6 are sound for II.

Proof. Line L4 gives a net vv the key (λ(v),M(v))(\lambda(v), M(v)) with M(v)M(v) the multiset of the pairs (c,λ(u))(c, \lambda(u)) over the pins of class cc of the devices uu on vv, one pair per pin. Take an isomorphism ff that agrees with II. By condition 1, the pins on φ(v)\varphi(v) are the images of the pins on vv, with the same classes, and their devices are the images π(u)\pi(u). By soundness λ(π(u))=λ(u)\lambda(\pi(u)) = \lambda(u), so M(φ(v))=M(v)M(\varphi(v)) = M(v), and also λ(φ(v))=λ(v)\lambda(\varphi(v)) = \lambda(v). So the keys of vv and φ(v)\varphi(v) are equal. Line L6 maps equal keys to equal labels, because it renumbers the keys of both netlists with one table. Line L5 is the same argument for devices, with the new net labels. □\square

Lemma 3 (individualization keeps soundness). If λ\lambda is sound for II and xx, yy have the same label, then the labeling that gives xx and yy one new label, used by no other vertex, is sound for I∪{(x,y)}I \cup \{(x, y)\}.

Proof. Take an isomorphism ff that agrees with II and has f(x)=yf(x) = y. For a vertex z≠xz \ne x, f(z)≠yf(z) \ne y, so neither zz nor f(z)f(z) got the new label, and λ(f(z))=λ(z)\lambda(f(z)) = \lambda(z) as before. For z=xz = x both have the new label. □\square

Theorem 4 (a mismatch is real). If the algorithm reports a mismatch at line L7 while the pairs II are fixed, then no isomorphism agrees with II. In particular, a mismatch with I=∅I = \emptyset proves that the netlists are not isomorphic, and the report names a label with more vertices on one side than on the other.

Proof. By Lemmas 1 to 3 the labeling is sound for II. An isomorphism ff that agrees with II maps the vertices of GG with label ℓ\ell one to one into the vertices of G′G' with label ℓ\ell, and f−1f^{-1} does the same in the other direction, so the two counts are equal for every label. Line L7 fires only when some count differs. □\square

Lemma 5 (the stable map is an isomorphism). Suppose that after line L8 every label has exactly one vertex in GG and one in G′G'. Let ff map each vertex of GG to the vertex of G′G' with the same label. Then ff is an isomorphism.

Proof. ff maps devices to devices and nets to nets, because the two kinds are labeled in separate arrays, and it is a bijection on each kind. The loop stopped because one pass did not split any class, so every vertex has the same label as before the pass, and the label of a vertex now determines its key in the last pass. Take a device uu and u′=f(u)u' = f(u). Their keys are equal, so the multisets of pairs (class, net label) on their pins are equal. Each net label belongs to exactly one net of GG and one net of G′G', which ff pairs, so φ(Nc(u))=Nc(u′)\varphi(N_c(u)) = N_c(u') for every class cc. Types are kept since a device label always contains its type from line L1. A net and its image have equal labels, so they carry the same name by line L1. □\square

The implementation also checks the map directly before it returns it, which is a second guard against a bug.

Lemma 6 (termination of one refinement). The loop of lines L3 to L8 runs at most ∣D∣+∣V∣+∣D′∣+∣V′∣|D| + |V| + |D'| + |V'| passes.

Proof. The key of a vertex contains its old label, so two vertices with different labels keep different labels: each pass splits classes or leaves them unchanged. Line L8 stops the loop when the number of labels did not grow. While it grows, it grows by at least 1 per pass, and it cannot pass the number of vertices. □\square

Theorem 7 (completeness with backtracking). If the netlists are isomorphic, the search with backtracking returns an isomorphism. Every returned map is an isomorphism.

Proof. The second statement is Lemma 5. For the first, we show by induction on the number of classes with two or more members that SEARCH returns a map when some isomorphism ff agrees with the current pairs II. By soundness, line L7 does not fire. If all classes are singletons on each side, line L9 returns a map. Else line L10 picks a class KK and a vertex x∈Kx \in K in GG. By soundness f(x)f(x) has the label of xx, so f(x)f(x) is one of the candidates yy of line L11. For y=f(x)y = f(x), the call at line L12 runs with the pairs I∪{(x,f(x))}I \cup \{(x, f(x))\}, with which ff still agrees, so by Lemma 3 the labels stay sound. The new label of xx is a class of one member on each side, and xx came from a class of two or more, so the number of labels grows by at least 1. The depth of the search is at most the number of vertices of GG, and by induction the call for y=f(x)y = f(x) returns a map, which the loop returns. □\square

Without backtracking. If line L11 tries only the first candidate, Theorem 4 still makes every reported mismatch at the top level real, but a mismatch that appears after a guess can be caused by the guess. The test file gives such a case: two netlists, each a ring of six resistors plus two rings of three, where every net has the same label until a guess, and the first guess pairs a net of the long ring with a net of a short ring. If for any two vertices yy, y′y' of KK in G′G' some automorphism of G′G' that fixes the vertices already paired in II maps yy to y′y', then every guess is as good as any other: if an isomorphism maps xx to yy, its composition with that automorphism maps xx to y′y'. This is the usual case of identical cells in a layout.

Complexity. Let n=∣D∣n = |D|, m=∣V∣m = |V| and PP the number of pins. One pass builds n+mn + m keys of total size O(P)O(P) and sorts them, in O(Plog⁡P+(n+m)log⁡(n+m))O(P \log P + (n + m) \log (n + m)) time with comparisons of keys. By Lemma 6 one refinement makes at most 2(n+m)2(n + m) passes. A search without backtracking makes at most n+mn + m guesses, since each makes a new class, so it costs O((n+m)2(P+n+m)log⁡(n+m))O((n + m)^2 (P + n + m) \log (n + m)) in the worst case. With backtracking the number of calls can be exponential in n+mn + m: Neuen and Schweitzer (2018) give graphs on which every individualization and refinement method with color refinement visits exponentially many nodes.

Complexity

One round builds n+mn + m keys of total size O(P)O(P) and sorts them, which costs O(Plog⁡P+(n+m)log⁡(n+m))O(P \log P + (n + m) \log(n + m)) time. The number of labels grows in every round but the last and cannot pass the number of vertices, so one refinement takes at most 2(n+m)2(n + m) rounds. A guess makes a new class, so a run without backtracking makes at most n+mn + m guesses and costs O((n+m)2(P+n+m)log⁡(n+m))O((n + m)^2 (P + n + m) \log(n + m)) in the worst case. With backtracking the search tree has depth at most n+mn + m and at most n+mn + m branches at each node, so it has 2O((n+m)log⁡(n+m))2^{O((n + m) \log(n + m))} nodes, and Neuen and Schweitzer showed that every individualization and refinement search needs exponentially many nodes on some graphs. These are bounds on the worst case. On real layouts the refinement splits almost every class in a few rounds, because supply nets, ports and the mix of device types break the symmetry early. That is an observation from practice, not a theorem.

Properties

  • Every reported mismatch at the top level is real (Theorem 4 of the proof). A mismatch after a guess is real only when the guess cannot be wrong, for example when the tied vertices are copies of one cell.
  • Every returned map is an isomorphism.
  • The labels are exact signatures here. Gemini computes numeric labels from the neighbour labels, which can collide. A collision merges two classes that should differ, which can force an extra guess, but it cannot make a wrong map pass the final check.
  • Unlike Weisfeiler-Leman as a test of non-isomorphism, Gemini runs the refinement on both netlists with one label table, uses the pin classes and the names, returns a matching, and points to the place of a difference.

Variants and improvements

  • GeminiII. Ebeling's second version uses the bipartite structure of the device and net graph, with nets and devices relabeled in turn, to make the relabeling faster.
  • SubGemini. The labels of a small pattern circuit find all its copies in a large netlist, a subgraph isomorphism problem: candidates in the large netlist are filtered by labels that only depend on a bounded neighbourhood.
  • Series and parallel reduction. LVS tools often merge parallel transistors and series stacks before the comparison, and permute the inputs of a stack of equivalent transistors, so that netlists that differ only in these ways compare equal.
  • Canonical forms. Canonical labeling tools such as nauty solve the same problem for general graphs with a full individualization and refinement search and automorphism pruning.

When to use it

Use it to compare an extracted netlist with a schematic netlist at the transistor or the cell level, and to find a known circuit inside a larger one. For general graphs with large symmetric parts use nauty or a similar individualization and refinement tool, which prunes the search with automorphisms. For pattern search with a small pattern and a large target, VF2 and similar backtracking matchers are simpler.

Pitfalls

  • Pin classes matter. If the source and the drain are two different classes, a layout with them exchanged is reported as a mismatch.
  • Unnamed supply nets make the problem much more symmetric. Give the supplies and the ports names before the comparison.
  • A guess that leads to a mismatch is not a proof of a difference. Report it as a difference only if the tied vertices are known to be interchangeable, or else backtrack.
  • A class that differs by one vertex says where a difference is, not what it is. A short or an open in the layout changes the labels of all vertices near it, so the first reported class is often a neighbour of the real error.
  • The refinement compares structure only. Device sizes and parameter values need a separate check after the matching.

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.

gemini_netlist_comparison.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/gemini-netlist-comparison/. The authors are listed in prov/N08Y88.jsonl.
"""Gemini style netlist comparison: iterative relabeling of devices and nets,
then individualization (a guess) when the labels stop splitting.

A netlist is a pair (devices, anchors):

  devices: a list of (type, pins), where pins is a tuple of net names.
  anchors: a dict {net name: global name} for nets that must match by name,
           for example the supply nets and the ports.

PIN_CLASSES[type] gives, for each pin position of the type, its class. Pins
of one class are interchangeable (the source and the drain of a MOS
transistor, the two ends of a resistor).

compare(a, b, pin_classes) returns ("match", device_map, net_map) or
("mismatch", report). Labels are exact sorted signatures renumbered over both
netlists at once, so two vertices get the same label only when their
signatures are equal. Gemini itself uses numeric labels that can collide; a
collision only makes a class coarser, and the final check below catches it.
"""

from collections import Counter


class _Graph:
    """The bipartite device and net graph of one netlist."""

    def __init__(self, netlist, pin_classes):
        devices, anchors = netlist
        nets = sorted({v for _, pins in devices for v in pins} | set(anchors))
        self.net_index = {v: i for i, v in enumerate(nets)}
        self.nets = nets
        self.dev_type = [t for t, _ in devices]
        self.dev_pins = []  # per device: list of (class, net index)
        self.net_pins = [[] for _ in nets]  # per net: list of (class, device index)
        for d, (t, pins) in enumerate(devices):
            classes = pin_classes[t]
            if len(classes) != len(pins):
                raise ValueError(f"device {d}: wrong number of pins for {t}")
            row = []
            for c, v in zip(classes, pins):
                j = self.net_index[v]
                row.append((c, j))
                self.net_pins[j].append((c, d))
            self.dev_pins.append(row)
        self.anchor = [anchors.get(v) for v in nets]


def _renumber(keys_a, keys_b):
    """Replace keys by small integers, the same integer for equal keys in both lists."""
    table = {k: i for i, k in enumerate(sorted(set(keys_a) | set(keys_b)))}
    return [table[k] for k in keys_a], [table[k] for k in keys_b]


def _classes(lab_a, lab_b):
    count = Counter()
    for x in lab_a:
        count[x] += 1
    for x in lab_b:
        count[x] -= 1
    return count


def _refine(ga, gb, dev, net):
    """Relabel nets from devices and devices from nets until the number of
    labels stops growing. dev and net are pairs (labels of a, labels of b).
    Returns the new labels, or a mismatch report."""
    while True:
        before = len(set(dev[0]) | set(dev[1])) + len(set(net[0]) | set(net[1]))
        keys = []
        for g, dl, nl in ((ga, dev[0], net[0]), (gb, dev[1], net[1])):
            keys.append([(nl[j], tuple(sorted((c, dl[d]) for c, d in g.net_pins[j])))  # @line L4
                         for j in range(len(g.nets))])
        net = _renumber(*keys)  # @line L6
        keys = []
        for g, dl, nl in ((ga, dev[0], net[0]), (gb, dev[1], net[1])):
            keys.append([(dl[d], tuple(sorted((c, nl[j]) for c, j in g.dev_pins[d])))  # @line L5
                         for d in range(len(g.dev_type))])
        dev = _renumber(*keys)  # @line L6
        for kind, (la, lb) in (("device", dev), ("net", net)):
            bad = [x for x, k in _classes(la, lb).items() if k != 0]
            if bad:  # @line L7
                x = bad[0]
                return None, (kind, [i for i, y in enumerate(la) if y == x],
                              [i for i, y in enumerate(lb) if y == x])
        after = len(set(dev[0]) | set(dev[1])) + len(set(net[0]) | set(net[1]))
        if after == before:  # @line L8
            return (dev, net), None


def _check(ga, gb, dmap, nmap):
    """True when the maps are an isomorphism of the netlists."""
    for d, row in enumerate(ga.dev_pins):
        e = dmap[d]
        if ga.dev_type[d] != gb.dev_type[e]:
            return False
        if Counter((c, nmap[j]) for c, j in row) != Counter(gb.dev_pins[e]):
            return False
    return all(ga.anchor[j] == gb.anchor[nmap[j]] for j in range(len(ga.nets)))


def _search(ga, gb, dev, net, backtrack, stats):
    stats["refinements"] += 1
    labels, report = _refine(ga, gb, dev, net)  # @line L3
    if labels is None:
        return None, report
    dev, net = labels
    sizes = Counter(dev[0])
    nsizes = Counter(net[0])
    if all(k == 1 for k in sizes.values()) and all(k == 1 for k in nsizes.values()):  # @line L9
        dpos = {x: i for i, x in enumerate(dev[1])}
        npos = {x: i for i, x in enumerate(net[1])}
        dmap = [dpos[x] for x in dev[0]]
        nmap = [npos[x] for x in net[0]]
        if _check(ga, gb, dmap, nmap):
            return (dmap, nmap), None
        return None, ("check", [], [])
    # the smallest class with two or more members, devices first on ties
    cand = [(k, 0, x) for x, k in sizes.items() if k > 1] + [(k, 1, x) for x, k in nsizes.items() if k > 1]  # @line L10
    _, side, x = min(cand)
    labs = dev if side == 0 else net
    i = labs[0].index(x)
    fresh = 1 + max(max(dev[0]), max(net[0]) if net[0] else 0)
    report = None
    for j in [j for j, y in enumerate(labs[1]) if y == x]:  # @line L11
        stats["guesses"] += 1
        la, lb = list(labs[0]), list(labs[1])
        la[i] = lb[j] = fresh  # @line L12
        nd, nn = ((la, lb), net) if side == 0 else (dev, (la, lb))
        result, report = _search(ga, gb, nd, nn, backtrack, stats)
        if result is not None:
            return result, None
        if not backtrack:
            break
    return None, report  # @line L13


def compare(a, b, pin_classes, backtrack=True, stats=None):
    """Compare two netlists. With backtrack=False only the first guess at each
    tie is tried, as a plain guessing comparator does; a wrong guess can then
    report a false mismatch."""
    if stats is None:
        stats = {}
    stats.setdefault("refinements", 0)
    stats.setdefault("guesses", 0)
    ga, gb = _Graph(a, pin_classes), _Graph(b, pin_classes)
    if len(ga.dev_type) != len(gb.dev_type) or len(ga.nets) != len(gb.nets):
        return ("mismatch", ("size", [], []))
    dev = _renumber(ga.dev_type, gb.dev_type)  # @line L1
    net = _renumber([(ga.anchor[j] or "", len(ga.net_pins[j])) for j in range(len(ga.nets))],
                    [(gb.anchor[j] or "", len(gb.net_pins[j])) for j in range(len(gb.nets))])
    result, report = _search(ga, gb, dev, net, backtrack, stats)  # @line L2
    if result is None:
        return ("mismatch", report)
    dmap, nmap = result
    return ("match", dmap, {ga.nets[j]: gb.nets[nmap[j]] for j in range(len(ga.nets))})
test_gemini_netlist_comparison.py 176 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/gemini-netlist-comparison/. The authors are listed in prov/N08Y88.jsonl.

import random
from collections import Counter
from itertools import permutations

import pytest

from gemini_netlist_comparison import compare

PINS = {
    "nmos": ("g", "sd", "sd"),
    "pmos": ("g", "sd", "sd"),
    "res": ("t", "t"),
    "diode": ("a", "k"),
}


def signature(t, pins, f):
    """Type and, for each pin class, the multiset of mapped nets."""
    by_class = {}
    for c, v in zip(PINS[t], pins):
        by_class.setdefault(c, []).append(f[v])
    return (t, tuple(sorted((c, tuple(sorted(vs))) for c, vs in by_class.items())))


def brute_isomorphic(a, b):
    """Try every bijection of nets. For a fixed net map, a device map exists
    exactly when the multisets of device signatures are equal."""
    (da, aa), (db, ab) = a, b
    na = sorted({v for _, p in da for v in p} | set(aa))
    nb = sorted({v for _, p in db for v in p} | set(ab))
    if len(na) != len(nb) or len(da) != len(db):
        return False
    target = Counter(signature(t, p, {v: v for v in nb}) for t, p in db)
    for perm in permutations(nb):
        f = dict(zip(na, perm))
        if any(aa.get(v) != ab.get(f[v]) for v in na):
            continue
        if Counter(signature(t, p, f) for t, p in da) == target:
            return True
    return False


def check_match(a, b, out):
    """The returned maps must be an isomorphism."""
    _, dmap, nmap = out
    (da, aa), (db, ab) = a, b
    assert sorted(dmap) == list(range(len(db)))
    assert len(set(nmap.values())) == len(nmap)
    for d, (t, p) in enumerate(da):
        tb, pb = db[dmap[d]]
        assert tb == t
        assert signature(t, p, nmap) == signature(tb, pb, {v: v for v in pb})
    for v, g in aa.items():
        assert ab.get(nmap[v]) == g


def random_netlist(rng, n_dev, n_net):
    nets = [f"n{i}" for i in range(n_net)]
    devs = []
    for _ in range(n_dev):
        t = rng.choice(sorted(PINS))
        devs.append((t, tuple(rng.choice(nets) for _ in PINS[t])))
    anchors = {}
    if rng.random() < 0.5:
        anchors[rng.choice(nets)] = "VDD"
    return devs, anchors


def scramble(rng, netlist):
    """An isomorphic copy: new net names, shuffled devices, swapped equal pins."""
    devs, anchors = netlist
    nets = sorted({v for _, p in devs for v in p} | set(anchors))
    new = [f"m{i}" for i in range(len(nets))]
    rng.shuffle(new)
    f = dict(zip(nets, new))
    out = []
    for t, p in devs:
        p = [f[v] for v in p]
        cls = PINS[t]
        for c in set(cls):
            idx = [i for i, x in enumerate(cls) if x == c]
            vals = [p[i] for i in idx]
            rng.shuffle(vals)
            for i, v in zip(idx, vals):
                p[i] = v
        out.append((t, tuple(p)))
    rng.shuffle(out)
    return out, {f[v]: g for v, g in anchors.items()}


def mutate(rng, netlist):
    devs, anchors = netlist
    devs = list(devs)
    d = rng.randrange(len(devs))
    t, p = devs[d]
    nets = sorted({v for _, q in devs for v in q})
    p = list(p)
    p[rng.randrange(len(p))] = rng.choice(nets)
    devs[d] = (t, tuple(p))
    return devs, anchors


NAND2 = ([("pmos", ("A", "Y", "VDD")), ("pmos", ("B", "VDD", "Y")),
          ("nmos", ("A", "Y", "X")), ("nmos", ("B", "X", "GND"))],
         {"VDD": "VDD", "GND": "GND"})
LAYOUT = ([("nmos", ("n2", "n6", "n5")), ("pmos", ("n1", "n4", "n3")),
           ("nmos", ("n1", "n3", "n5")), ("pmos", ("n2", "n3", "n4"))],
          {"n4": "VDD", "n6": "GND"})


def test_nand2_page_example():
    # The layout lists the devices in another order, swaps some sources and
    # drains, and calls the nets n1 to n6.
    layout = LAYOUT
    out = compare(NAND2, layout, PINS)
    assert out[0] == "match"
    check_match(NAND2, layout, out)
    assert out[2] == {"A": "n1", "B": "n2", "Y": "n3", "VDD": "n4", "X": "n5", "GND": "n6"}


def test_swapped_inputs_need_port_names():
    swapped = ([("pmos", ("A", "Y", "VDD")), ("pmos", ("B", "VDD", "Y")),
                ("nmos", ("B", "Y", "X")), ("nmos", ("A", "X", "GND"))],
               {"VDD": "VDD", "GND": "GND"})
    assert compare(NAND2, swapped, PINS)[0] == "match"
    named = lambda n: (n[0], dict(n[1], A="A", B="B"))
    out = compare(named(NAND2), named(swapped), PINS)
    assert out[0] == "mismatch"
    assert not brute_isomorphic(named(NAND2), named(swapped))


def ring(nets):
    return [("res", (nets[i], nets[(i + 1) % len(nets)])) for i in range(len(nets))]


def test_regular_graphs_need_guesses():
    six = (ring([f"a{i}" for i in range(6)]), {})
    two_three = (ring(["b0", "b1", "b2"]) + ring(["c0", "c1", "c2"]), {})
    assert compare(six, two_three, PINS)[0] == "mismatch"
    assert not brute_isomorphic(six, two_three)
    stats = {}
    out = compare(six, (ring([f"z{i}" for i in (3, 1, 4, 0, 5, 2)]), {}), PINS, stats=stats)
    assert out[0] == "match" and stats["guesses"] >= 1


def test_wrong_guess_without_backtracking():
    # Both netlists are a 6-ring plus two 3-rings. All nets look alike to the
    # refinement. A guess that pairs a net of the 6-ring with a net of a
    # 3-ring fails, so the plain guessing comparator can report a false
    # mismatch, while the backtracking search finds the match.
    a = (ring([f"a{i}" for i in range(6)]) + ring(["b0", "b1", "b2"]) + ring(["c0", "c1", "c2"]), {})
    b = (ring(["p0", "p1", "p2"]) + ring([f"q{i}" for i in range(6)]) + ring(["r0", "r1", "r2"]), {})
    assert compare(a, b, PINS)[0] == "match"
    assert compare(a, b, PINS, backtrack=False)[0] == "mismatch"


@pytest.mark.parametrize("seed", range(150))
def test_random_against_brute_force(seed):
    rng = random.Random(seed)
    n_dev = rng.randint(1, 7)
    n_net = rng.randint(2, 6)
    a = random_netlist(rng, n_dev, n_net)
    b = scramble(rng, a)
    out = compare(a, b, PINS)
    assert out[0] == "match"
    check_match(a, b, out)
    for _ in range(3):
        c = scramble(rng, mutate(rng, a))
        want = brute_isomorphic(a, c)
        got = compare(a, c, PINS)
        assert (got[0] == "match") == want
        if want:
            check_match(a, c, got)

History

Ebeling and Zajicek presented Gemini at ICCAD 1983 as a way to validate a VLSI layout by comparing wirelists with a graph isomorphism method. Ebeling's GeminiII at ICCAD 1988 used the bipartite structure of the device and net graph for a faster relabeling, and Ohlrich, Ebeling, Ginting and Sather used the same labels to find subcircuits in SubGemini at DAC 1993.

References

  1. Carl Ebeling and Ofer Zajicek, Validating VLSI circuit layout by wirelist comparison, Proceedings of the IEEE International Conference on Computer-Aided Design (ICCAD) 1983, 172 to 173, the reduction of layout validation to graph isomorphism of the device and net graphs, the iterative relabeling from neighbour labels, and the guess when labels stop splitting
  2. Carl Ebeling, GeminiII, a second generation layout validation program, IEEE International Conference on Computer-Aided Design (ICCAD) 1988, Digest of Technical Papers, 322 to 325, the improved relabeling on the bipartite graph of devices and nets, and the reporting of differences
  3. Miles Ohlrich, Carl Ebeling, Eka Ginting and Lisa Sather, SubGemini, identifying subcircuits using a fast subgraph isomorphism algorithm, Proceedings of the 30th Design Automation Conference, 1993, the use of the Gemini labels to find all instances of a small circuit in a large netlist
  4. Daniel Neuen and Pascal Schweitzer, An exponential lower bound for individualization-refinement algorithms for graph isomorphism, Proceedings of the 50th ACM Symposium on Theory of Computing (STOC), 2018, the graphs on which every individualization and refinement search visits exponentially many nodes

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 proofH2 full proof
  • correctness: no review record reviews/N08Y88/proof-correctness.yaml
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