#!/usr/bin/env python3 """Dependency-free OpenQASM 2 router with deterministic layout annealing. Usage: solve.py INPUT.qasm DEVICE.json [OUTPUT.qasm] The input circuit is preserved except for qubit indices and inserted SWAPs. """ from __future__ import annotations import json import math import random import re import sys from collections import Counter, defaultdict, deque from pathlib import Path QREF = re.compile(r"q\[(\d+)\]") SELF_INVERSE = {"cx", "cz", "x", "y", "z", "h", "swap"} GATE_LINE = re.compile(r"\s*([a-z][a-z0-9_]*)[^;]*;\s*$", re.I) def simplify_lines(lines: list[str]) -> list[str]: """Cancel adjacent identical self-inverse gates without crossing barriers.""" out: list[str] = [] swap_history: list[tuple[int, int]] = [] for line in lines: stripped = line.strip() m = GATE_LINE.fullmatch(stripped) name = m.group(1).lower() if m else "" key = (name, tuple(QREF.findall(stripped))) if name in SELF_INVERSE else None if key is not None and out: prev = out[-1].strip() pm = GATE_LINE.fullmatch(prev) pname = pm.group(1).lower() if pm else "" pkey = (pname, tuple(QREF.findall(prev))) if pname in SELF_INVERSE else None if pkey == key: out.pop() continue out.append(line) return out def load_edges(path: Path) -> tuple[int, set[tuple[int, int]]]: data = json.loads(path.read_text()) edges = data.get("coupling_map", data.get("edges", data.get("couplings", data))) if isinstance(edges, dict): edges = edges.get("edges", edges.get("coupling_map", [])) pairs: set[tuple[int, int]] = set() max_node = -1 for item in edges if isinstance(edges, list) else []: if isinstance(item, dict): a, b = item.get("source", item.get("u")), item.get("target", item.get("v")) else: a, b = item[0], item[1] a, b = int(a), int(b) pairs.add((min(a, b), max(a, b))) max_node = max(max_node, a, b) n = int(data.get("num_qubits", data.get("n_qubits", max_node + 1))) if n <= 0: raise ValueError("device.json contains no qubits") return n, pairs def parse_qasm(text: str) -> tuple[list[str], int, list[tuple[int, int]]]: lines = text.splitlines() n = 0 interactions: list[tuple[int, int]] = [] for line in lines: m = re.search(r"qreg\s+q\[(\d+)\]", line) if m: n = int(m.group(1)) qs = [int(x) for x in QREF.findall(line)] if len(qs) == 2 and not line.lstrip().startswith("//"): interactions.append((qs[0], qs[1])) if n == 0: raise ValueError("input has no qreg q[N]") return lines, n, interactions def all_pairs(n: int, edges: set[tuple[int, int]]) -> dict[int, dict[int, int]]: graph = [[] for _ in range(n)] for a, b in edges: if a < n and b < n: graph[a].append(b) graph[b].append(a) dist: dict[int, dict[int, int]] = {} for src in range(n): d = {src: 0} todo = deque([src]) while todo: u = todo.popleft() for v in graph[u]: if v not in d: d[v] = d[u] + 1 todo.append(v) dist[src] = d return dist def objective(mapping: list[int], interactions: list[tuple[int, int]], dist: dict[int, dict[int, int]]) -> float: score = 0.0 weight = Counter(interactions) for (a, b), w in weight.items(): score += w * dist[mapping[a]].get(mapping[b], 10_000) return score def anneal(nlogical: int, nphysical: int, interactions: list[tuple[int, int]], dist: dict[int, dict[int, int]]) -> list[int]: if nlogical > nphysical: raise ValueError(f"circuit needs {nlogical} qubits but device has {nphysical}") rng = random.Random(0x5A17) base = sorted(range(nphysical), key=lambda p: (len(dist[p]), p), reverse=True) current = base[:nlogical] best = current[:] current_cost = objective(current, interactions, dist) best_cost = current_cost steps = max(200, min(4000, 40 * max(1, len(interactions)))) for step in range(steps): i = rng.randrange(nlogical) j = rng.randrange(nlogical) if i == j: continue current[i], current[j] = current[j], current[i] new_cost = objective(current, interactions, dist) temp = max(0.05, 2.5 * (1.0 - step / steps)) if new_cost <= current_cost or rng.random() < math.exp((current_cost - new_cost) / temp): current_cost = new_cost else: current[i], current[j] = current[j], current[i] if current_cost < best_cost: best, best_cost = current[:], current_cost return best def shortest_path(a: int, b: int, n: int, edges: set[tuple[int, int]]) -> list[int]: graph = [[] for _ in range(n)] for u, v in edges: graph[u].append(v) graph[v].append(u) prev = {a: None} todo = deque([a]) while todo: u = todo.popleft() if u == b: break for v in graph[u]: if v not in prev: prev[v] = u todo.append(v) if b not in prev: raise ValueError(f"device has no path between physical qubits {a} and {b}") path = [] u: int | None = b while u is not None: path.append(u) u = prev[u] return path[::-1] def emit_swap(a: int, b: int) -> list[str]: return [f"cx q[{a}],q[{b}];", f"cx q[{b}],q[{a}];", f"cx q[{a}],q[{b}];"] def realize_mapping(target: list[int], nphysical: int, edges: set[tuple[int, int]]) -> tuple[list[tuple[int, int]], list[int]]: """Token-swap identity wires onto target physical slots.""" current = list(range(len(target))) inverse = {p: q for q, p in enumerate(current)} swaps: list[tuple[int, int]] = [] for q, target_p in enumerate(target): if current[q] == target_p: continue path = shortest_path(current[q], target_p, nphysical, edges) for left, right in zip(path, path[1:]): lq, rq = inverse.get(left), inverse.get(right) if lq is not None: current[lq] = right if rq is not None: current[rq] = left inverse[left], inverse[right] = inverse.get(right), inverse.get(left) swaps.append((left, right)) if current != target: raise AssertionError("could not realize initial layout permutation") return swaps, current def route(text: str, device: Path) -> str: lines, nlogical, interactions = parse_qasm(text) lines = simplify_lines(lines) nphysical, edges = load_edges(device) dist = all_pairs(nphysical, edges) mapping = anneal(nlogical, nphysical, interactions, dist) # logical -> physical initial_mapping = mapping[:] try: setup_history, _ = realize_mapping(initial_mapping, nphysical, edges) except AssertionError: # A disconnected or crowded topology can make the greedy token swap # setup fail; identity layout remains correct and deterministic. initial_mapping = list(range(nlogical)) mapping = initial_mapping[:] setup_history = [] inverse = {p: q for q, p in enumerate(mapping)} out: list[str] = [] swap_history: list[tuple[int, int]] = [] setup_lines = [line for pair in setup_history for line in emit_swap(*pair)] setup_emitted = False for line in lines: stripped = line.strip() if not setup_emitted and stripped and not stripped.startswith(("OPENQASM", "include", "qreg", "creg", "//")): out.extend(setup_lines) setup_emitted = True if line.lstrip().startswith("qreg q["): out.append(re.sub(r"qreg\s+q\[\d+\]", f"qreg q[{nphysical}]", line)) continue qs = [int(x) for x in QREF.findall(line)] if len(qs) != 2 or line.lstrip().startswith("//"): if qs and not line.lstrip().startswith("qreg"): line = QREF.sub(lambda m: f"q[{mapping[int(m.group(1))]}]", line) out.append(line) continue q0, q1 = qs p0, p1 = mapping[q0], mapping[q1] if (min(p0, p1), max(p0, p1)) not in edges: path = shortest_path(p0, p1, nphysical, edges) for left, right in zip(path, path[1:]): out.extend(emit_swap(left, right)) swap_history.append((left, right)) lq, rq = inverse.get(left), inverse.get(right) if lq is not None: mapping[lq] = right if rq is not None: mapping[rq] = left inverse[left], inverse[right] = inverse.get(right), inverse.get(left) p0, p1 = mapping[q0], mapping[q1] out.append(QREF.sub(lambda m: f"q[{mapping[int(m.group(1))]}]", line)) if not setup_emitted: out.extend(setup_lines) # Reverse every routing SWAP after the circuit. This restores the initial # logical-to-physical permutation exactly, including when paths overlap. for left, right in reversed(swap_history): out.extend(emit_swap(left, right)) for left, right in reversed(setup_history): out.extend(emit_swap(left, right)) return "\n".join(out) + "\n" def main(argv: list[str]) -> int: if len(argv) not in (3, 4): print(__doc__.strip(), file=sys.stderr) return 2 src, device = Path(argv[1]), Path(argv[2]) result = route(src.read_text(), device) if len(argv) == 4: Path(argv[3]).write_text(result) else: sys.stdout.write(result) return 0 if __name__ == "__main__": raise SystemExit(main(sys.argv))