"""Board fermion-workload (site key fermion): fermion-to-qubit encodings on exactly N qubits for a fixed Hubbard workload, ranked by the Pauli weight of the mapped workload (SPEC_v3_final s5 with review_v3final_fable W1-W3). Instance: an Lx x Ly open lattice, two spin modes per site (mode p = 2u + spin, site u = y*Lx + x), N = 2 Lx Ly modes and qubits, Majoranas gamma_2p = a_p^dag + a_p, gamma_2p+1 = i(a_p^dag - a_p). The frozen workload (regenerated here and compared with the instance list) is, for every neighbouring site pair u < v and spin s with p = 2u+s, q = 2v+s, the hopping bilinears [2p, 2q+1] and [2p+1, 2q], then for every site u the onsite quartic [4u, 4u+1, 4u+2, 4u+3]. Artifact {"majoranas": [{"x": "0101..", "z": "1100..", "sign": 0|1}, ...]}: exactly 2N images, strings of length N (character i = qubit i), image j = (-1)^sign i^popcount(x & z) X^x Z^z. Accept iff every pair of distinct images anticommutes: popcount(x_i & z_j) + popcount(z_i & x_j) odd. 2N pairwise anticommuting Paulis on N qubits are independent, so they generate the whole Pauli group and the representation is faithful; no rank certificate is needed. Score: for every listed term J, w_J = popcount(OR of XOR_j x_j and XOR_j z_j); weight = sum of w_J, maxweight = max w_J, both minimized. Signs and phases never change support, acceptance or score; `sign` is validated only. Method: integer bitsets for every string, one bitset test per pair (N(2N-1) tests) and one XOR per Majorana occurrence. """ import json import os import time from common import Reject, bitstring, exact_keys, is_int, load_instance, short popcount = int.bit_count if hasattr(int, "bit_count") else (lambda v: bin(v).count("1")) BOARD = "fermion-workload" INSTANCE_KEYS = ["board", "instance", "mode", "cpu_seconds", "mem_mb", "lx", "ly", "n", "terms"] N_MAX = 128 class Budget(Exception): pass def workload(lx, ly): """The frozen term list of SPEC_v3_final s5 (hopping bilinears per bond and spin, then one quartic per site).""" pairs = [] for y in range(ly): for x in range(lx): u = y * lx + x if x + 1 < lx: pairs.append((u, u + 1)) if y + 1 < ly: pairs.append((u, u + lx)) terms = [] for u, v in sorted(pairs): for spin in (0, 1): p, q = 2 * u + spin, 2 * v + spin terms.append({"majoranas": [2 * p, 2 * q + 1], "theta_num": -1, "theta_den": 32}) terms.append({"majoranas": [2 * p + 1, 2 * q], "theta_num": 1, "theta_den": 32}) for u in range(lx * ly): terms.append({"majoranas": [4 * u, 4 * u + 1, 4 * u + 2, 4 * u + 3], "theta_num": 1, "theta_den": 16}) return terms def instance_problem(I): """None if the instance file is well formed and matches the generator, else a description of the defect.""" if not isinstance(I, dict) or sorted(I) != sorted(INSTANCE_KEYS): return "instance keys differ from the specification" lx, ly, n = I["lx"], I["ly"], I["n"] if I["board"] != BOARD or not all(is_int(v) and v >= 1 for v in (lx, ly, n)): return "instance header is malformed" if n != 2 * lx * ly or n > N_MAX: return f"n = {short(n)} is not 2 * lx * ly <= {N_MAX}" if json.dumps(I["terms"], sort_keys=True) != json.dumps(workload(lx, ly), sort_keys=True): return "instance terms differ from the regenerated workload" # compared as JSON: 1.0 or true is not 1 return None def parse(art, n): """Strict artifact parsing -> (xs, zs, signs): lists of 2n int bitsets (bit i = qubit i) and sign bits.""" exact_keys(art, ["majoranas"]) ims = art["majoranas"] if not isinstance(ims, list): raise Reject("majoranas must be a list") if len(ims) != 2 * n: raise Reject(f"majoranas must list exactly 2N = {2 * n} images (one per Majorana operator), got {len(ims)}") xs, zs, signs = [], [], [] for j, m in enumerate(ims): where = f"majoranas[{j}]" if not isinstance(m, dict): raise Reject(f"{where} must be an object with keys x, z, sign") exact_keys(m, ["x", "z", "sign"], where=where) xs.append(bitstring(m["x"], n, f"{where}.x")) zs.append(bitstring(m["z"], n, f"{where}.z")) s = m["sign"] if not is_int(s) or s not in (0, 1): raise Reject(f"{where}.sign must be the integer 0 or 1, got {short(s)}") signs.append(s) return xs, zs, signs def pauli_text(x, z, n): return "".join("IXZY"[(x >> q & 1) | (z >> q & 1) << 1] for q in range(n)) def check_car(xs, zs, n, deadline): """Reject unless the 2n images pairwise anticommute; identity and repeated images get their own reason.""" seen = {} for j, (x, z) in enumerate(zip(xs, zs)): if not x | z: raise Reject(f"majoranas[{j}] is the identity, which commutes with every image (not a valid encoding)") if (x, z) in seen: raise Reject(f"majoranas[{seen[(x, z)]}] and majoranas[{j}] have the same Pauli string " f"{short(pauli_text(x, z, n))} (signs aside), so they commute") seen[(x, z)] = j m = len(xs) for i in range(m): if time.process_time() > deadline: raise Budget xi, zi = xs[i], zs[i] for j in range(i + 1, m): if not popcount(xi & zs[j] ^ zi & xs[j]) & 1: raise Reject(f"majoranas[{i}] = {short(pauli_text(xi, zi, n))} and majoranas[{j}] = " f"{short(pauli_text(xs[j], zs[j], n))} commute; every pair of distinct images must " "anticommute") return m * (m - 1) // 2 def verify(inst, art): return check(load_instance("fermion", inst), art) def check(I, art, cpu_budget=None): """verify() on an instance given as a loaded dict (tests and the cost measurement pass instances this way).""" t0 = time.process_time() bad = instance_problem(I) if bad: return {"status": "error", "detail": {"reason": f"invalid instance file: {bad}"}} if cpu_budget is None: cpu_budget = 0.9 * float(os.environ.get("QARENA_CPU", I["cpu_seconds"])) deadline = t0 + cpu_budget n, terms = I["n"], I["terms"] xs, zs, signs = parse(art, n) try: pairs = check_car(xs, zs, n, deadline) if time.process_time() > deadline: raise Budget except Budget: return {"status": "error", "detail": {"reason": "anticommutation check did not finish within the time limit " "(not ranked)"}} hist, total, top = {}, 0, 0 for t in terms: x = z = 0 for j in t["majoranas"]: x ^= xs[j] z ^= zs[j] w = popcount(x | z) if w == 0: raise RuntimeError("internal: a term maps to the identity although the images are independent") total += w top = max(top, w) hist[w] = hist.get(w, 0) + 1 return {"status": "accepted", "score": {"weight": total, "maxweight": top}, "detail": {"n": n, "majoranas": 2 * n, "terms": len(terms), "weight": total, "maxweight": top, "term_weight_histogram": {str(w): hist[w] for w in sorted(hist)}, "majorana_weight_sum": sum(popcount(x | z) for x, z in zip(xs, zs)), "pairs_checked": pairs, "check": f"all {pairs} pairs of the {2 * n} images anticommute (a faithful encoding on {n} " f"qubits); every one of the {len(terms)} listed terms was mapped and weighed"}}