| @@ -0,0 +1,186 @@ |
| 1 | + |
| 2 | +"""Dependency-free OpenQASM 2 router with deterministic layout annealing. |
| 3 | + |
| 4 | +Usage: solve.py INPUT.qasm DEVICE.json [OUTPUT.qasm] |
| 5 | +The input circuit is preserved except for qubit indices and inserted SWAPs. |
| 6 | +""" |
| 7 | +from __future__ import annotations |
| 8 | + |
| 9 | +import json |
| 10 | +import math |
| 11 | +import random |
| 12 | +import re |
| 13 | +import sys |
| 14 | +from collections import Counter, defaultdict, deque |
| 15 | +from pathlib import Path |
| 16 | + |
| 17 | +QREF = re.compile(r"q\[(\d+)\]") |
| 18 | + |
| 19 | + |
| 20 | +def load_edges(path: Path) -> tuple[int, set[tuple[int, int]]]: |
| 21 | + data = json.loads(path.read_text()) |
| 22 | + edges = data.get("coupling_map", data.get("edges", data.get("couplings", data))) |
| 23 | + if isinstance(edges, dict): |
| 24 | + edges = edges.get("edges", edges.get("coupling_map", [])) |
| 25 | + pairs: set[tuple[int, int]] = set() |
| 26 | + max_node = -1 |
| 27 | + for item in edges if isinstance(edges, list) else []: |
| 28 | + if isinstance(item, dict): |
| 29 | + a, b = item.get("source", item.get("u")), item.get("target", item.get("v")) |
| 30 | + else: |
| 31 | + a, b = item[0], item[1] |
| 32 | + a, b = int(a), int(b) |
| 33 | + pairs.add((min(a, b), max(a, b))) |
| 34 | + max_node = max(max_node, a, b) |
| 35 | + n = int(data.get("num_qubits", data.get("n_qubits", max_node + 1))) |
| 36 | + if n <= 0: |
| 37 | + raise ValueError("device.json contains no qubits") |
| 38 | + return n, pairs |
| 39 | + |
| 40 | + |
| 41 | +def parse_qasm(text: str) -> tuple[list[str], int, list[tuple[int, int]]]: |
| 42 | + lines = text.splitlines() |
| 43 | + n = 0 |
| 44 | + interactions: list[tuple[int, int]] = [] |
| 45 | + for line in lines: |
| 46 | + m = re.search(r"qreg\s+q\[(\d+)\]", line) |
| 47 | + if m: |
| 48 | + n = int(m.group(1)) |
| 49 | + qs = [int(x) for x in QREF.findall(line)] |
| 50 | + if len(qs) == 2 and not line.lstrip().startswith("//"): |
| 51 | + interactions.append((qs[0], qs[1])) |
| 52 | + if n == 0: |
| 53 | + raise ValueError("input has no qreg q[N]") |
| 54 | + return lines, n, interactions |
| 55 | + |
| 56 | + |
| 57 | +def all_pairs(n: int, edges: set[tuple[int, int]]) -> dict[int, dict[int, int]]: |
| 58 | + graph = [[] for _ in range(n)] |
| 59 | + for a, b in edges: |
| 60 | + if a < n and b < n: |
| 61 | + graph[a].append(b) |
| 62 | + graph[b].append(a) |
| 63 | + dist: dict[int, dict[int, int]] = {} |
| 64 | + for src in range(n): |
| 65 | + d = {src: 0} |
| 66 | + todo = deque([src]) |
| 67 | + while todo: |
| 68 | + u = todo.popleft() |
| 69 | + for v in graph[u]: |
| 70 | + if v not in d: |
| 71 | + d[v] = d[u] + 1 |
| 72 | + todo.append(v) |
| 73 | + dist[src] = d |
| 74 | + return dist |
| 75 | + |
| 76 | + |
| 77 | +def objective(mapping: list[int], interactions: list[tuple[int, int]], dist: dict[int, dict[int, int]]) -> float: |
| 78 | + score = 0.0 |
| 79 | + weight = Counter(interactions) |
| 80 | + for (a, b), w in weight.items(): |
| 81 | + score += w * dist[mapping[a]].get(mapping[b], 10_000) |
| 82 | + return score |
| 83 | + |
| 84 | + |
| 85 | +def anneal(nlogical: int, nphysical: int, interactions: list[tuple[int, int]], dist: dict[int, dict[int, int]]) -> list[int]: |
| 86 | + if nlogical > nphysical: |
| 87 | + raise ValueError(f"circuit needs {nlogical} qubits but device has {nphysical}") |
| 88 | + rng = random.Random(0x5A17) |
| 89 | + base = sorted(range(nphysical), key=lambda p: (len(dist[p]), p), reverse=True) |
| 90 | + current = base[:nlogical] |
| 91 | + best = current[:] |
| 92 | + current_cost = objective(current, interactions, dist) |
| 93 | + best_cost = current_cost |
| 94 | + steps = max(200, min(4000, 40 * max(1, len(interactions)))) |
| 95 | + for step in range(steps): |
| 96 | + i = rng.randrange(nlogical) |
| 97 | + j = rng.randrange(nlogical) |
| 98 | + if i == j: |
| 99 | + continue |
| 100 | + current[i], current[j] = current[j], current[i] |
| 101 | + new_cost = objective(current, interactions, dist) |
| 102 | + temp = max(0.05, 2.5 * (1.0 - step / steps)) |
| 103 | + if new_cost <= current_cost or rng.random() < math.exp((current_cost - new_cost) / temp): |
| 104 | + current_cost = new_cost |
| 105 | + else: |
| 106 | + current[i], current[j] = current[j], current[i] |
| 107 | + if current_cost < best_cost: |
| 108 | + best, best_cost = current[:], current_cost |
| 109 | + return best |
| 110 | + |
| 111 | + |
| 112 | +def shortest_path(a: int, b: int, n: int, edges: set[tuple[int, int]]) -> list[int]: |
| 113 | + graph = [[] for _ in range(n)] |
| 114 | + for u, v in edges: |
| 115 | + graph[u].append(v) |
| 116 | + graph[v].append(u) |
| 117 | + prev = {a: None} |
| 118 | + todo = deque([a]) |
| 119 | + while todo: |
| 120 | + u = todo.popleft() |
| 121 | + if u == b: |
| 122 | + break |
| 123 | + for v in graph[u]: |
| 124 | + if v not in prev: |
| 125 | + prev[v] = u |
| 126 | + todo.append(v) |
| 127 | + if b not in prev: |
| 128 | + raise ValueError(f"device has no path between physical qubits {a} and {b}") |
| 129 | + path = [] |
| 130 | + u: int | None = b |
| 131 | + while u is not None: |
| 132 | + path.append(u) |
| 133 | + u = prev[u] |
| 134 | + return path[::-1] |
| 135 | + |
| 136 | + |
| 137 | +def emit_swap(a: int, b: int) -> list[str]: |
| 138 | + return [f"cx q[{a}],q[{b}];", f"cx q[{b}],q[{a}];", f"cx q[{a}],q[{b}];"] |
| 139 | + |
| 140 | + |
| 141 | +def route(text: str, device: Path) -> str: |
| 142 | + lines, nlogical, interactions = parse_qasm(text) |
| 143 | + nphysical, edges = load_edges(device) |
| 144 | + dist = all_pairs(nphysical, edges) |
| 145 | + mapping = anneal(nlogical, nphysical, interactions, dist) |
| 146 | + inverse = {p: q for q, p in enumerate(mapping)} |
| 147 | + out: list[str] = [] |
| 148 | + for line in lines: |
| 149 | + qs = [int(x) for x in QREF.findall(line)] |
| 150 | + if len(qs) != 2 or line.lstrip().startswith("//"): |
| 151 | + if qs and not line.lstrip().startswith("qreg"): |
| 152 | + line = QREF.sub(lambda m: f"q[{mapping[int(m.group(1))]}]", line) |
| 153 | + out.append(line) |
| 154 | + continue |
| 155 | + q0, q1 = qs |
| 156 | + p0, p1 = mapping[q0], mapping[q1] |
| 157 | + if (min(p0, p1), max(p0, p1)) not in edges: |
| 158 | + path = shortest_path(p0, p1, nphysical, edges) |
| 159 | + for left, right in zip(path, path[1:]): |
| 160 | + out.extend(emit_swap(left, right)) |
| 161 | + lq, rq = inverse.get(left), inverse.get(right) |
| 162 | + if lq is not None: |
| 163 | + mapping[lq] = right |
| 164 | + if rq is not None: |
| 165 | + mapping[rq] = left |
| 166 | + inverse[left], inverse[right] = inverse.get(right), inverse.get(left) |
| 167 | + p0, p1 = mapping[q0], mapping[q1] |
| 168 | + out.append(QREF.sub(lambda m: f"q[{mapping[int(m.group(1))]}]", line)) |
| 169 | + return "\n".join(out) + "\n" |
| 170 | + |
| 171 | + |
| 172 | +def main(argv: list[str]) -> int: |
| 173 | + if len(argv) not in (3, 4): |
| 174 | + print(__doc__.strip(), file=sys.stderr) |
| 175 | + return 2 |
| 176 | + src, device = Path(argv[1]), Path(argv[2]) |
| 177 | + result = route(src.read_text(), device) |
| 178 | + if len(argv) == 4: |
| 179 | + Path(argv[3]).write_text(result) |
| 180 | + else: |
| 181 | + sys.stdout.write(result) |
| 182 | + return 0 |
| 183 | + |
| 184 | + |
| 185 | +if __name__ == "__main__": |
| 186 | + raise SystemExit(main(sys.argv)) |