#!/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+)\]") 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 route(text: str, device: Path) -> str: lines, nlogical, interactions = parse_qasm(text) nphysical, edges = load_edges(device) dist = all_pairs(nphysical, edges) mapping = anneal(nlogical, nphysical, interactions, dist) # logical -> physical inverse = {p: q for q, p in enumerate(mapping)} out: list[str] = [] for line in lines: 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)) 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)) 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))