"""Twenty-seven squares at once on IBM hardware (Kickoff 12, Variants A and B).

Each square of the mala is the two-qubit encoding of Kickoff 03 (square_qubit_ibm.py):
|00> = bead 1, |01> = bead 28, |11> = bead 55, |10> = bead 82, the walk exp(-iHt) with
H = -(X0 + X1) is RX(-2t) on each qubit. Here 27 such pairs run side by side on 54 physical
qubits, with no gate between pairs, and four circuits measure all 27 at once:

  floor         prepare nothing, measure; per pair the target is 00
  transfer      RX(-pi) on both qubits (bead 1 -> bead 55 at t = pi/2); target 11
  in_step       H, CX, RX(-pi/2) on both: the 0 degree state at t = pi/4; target 01 or 10
  out_of_step   H, CX, RZ(pi) on qubit 1, RX(-pi/2) on both: the 180 degree dark state; target not 01/10

Variant B, the wire: one excitation on four qubits per square. Beads 1, 28, 55, 82 are qubits
q0, q1, q2, q3 of a group; H = -1/2 sum over the four edges (q0q1, q1q2, q2q3, q3q0) of XX + YY,
which is hopping on the four-cycle inside the one-excitation subspace; |1000> -> |0010> at t = pi/2.
Second-order Trotter, layers A = (q0q1, q2q3) and B = (q1q2, q3q0), each exchange one
XXPlusYYGate(theta) = exp(-i theta/4 (XX + YY)), so a step dt is theta = -2 dt. The groups are
four-qubit paths q0-q1-q2-q3 on the chip; the edge q3q0 is not on the chip and the transpiler routes it.

Usage
  python mala27_ibm.py --selfcheck             # exact, no quantum time
  python mala27_ibm.py --ideal                 # 4000 simulated shots of the 54-qubit circuits
  python mala27_ibm.py --pairs [--backend X]   # read calibration, choose 27 pairs, write pairs.json
  python mala27_ibm.py --hardware              # one job, the four circuits, on pairs.json's backend
  python mala27_ibm.py --ideal108              # choose n by simulation, write results108_ideal.json
  python mala27_ibm.py --groups                # choose the 27 four-qubit paths on pairs.json's backend
  python mala27_ibm.py --dryrun108             # transpile only: routing cost, no job
  python mala27_ibm.py --hardware108           # one job: transfer and floor, 108 qubits

The circuits are Kickoff 03's, per pair, unchanged. All four are Clifford, so the simulators are
qiskit.quantum_info.StabilizerState, which is exact at 54 qubits where a statevector (2^54
amplitudes) is not. Raw counts only: no readout mitigation, no twirling, no dynamical decoupling.
Never touches the API key; the saved account is used as QiskitRuntimeService() finds it.
"""
import argparse, json, math, sys, time
from datetime import datetime, timezone
from pathlib import Path
import numpy as np

HERE = Path(__file__).resolve().parent
NPAIRS, SHOTS = 27, 4000
CIRCUITS = ("floor", "transfer", "in_step", "out_of_step")
LINE_0_9815 = 0.9815 ** 27
MACHINES = ("ibm_kingston", "ibm_fez", "ibm_marrakesh")


# ----------------------------------------------------------------------------- circuits
def build(kind, npairs=NPAIRS):
    """One circuit on 2*npairs qubits. Pair i is qubits (2i, 2i+1), measured into clbits (2i, 2i+1)."""
    from qiskit import QuantumCircuit
    qc = QuantumCircuit(2 * npairs, 2 * npairs, name=kind)
    for i in range(npairs):
        a, b = 2 * i, 2 * i + 1
        if kind == "transfer":
            qc.rx(-math.pi, a); qc.rx(-math.pi, b)
        elif kind in ("in_step", "out_of_step"):
            qc.h(a); qc.cx(a, b)
            if kind == "out_of_step":
                qc.rz(math.pi, b)
            qc.rx(-math.pi / 2, a); qc.rx(-math.pi / 2, b)
    qc.measure(range(2 * npairs), range(2 * npairs))
    return qc


def no_cross_pair_gates(qc):
    for inst in qc.data:
        qs = {qc.find_bit(q).index for q in inst.qubits}
        if len(qs) > 1 and len({q // 2 for q in qs}) > 1:
            return False
    return True


# ----------------------------------------------------------------------------- analysis
def pair_bits(bools, i):
    """bools: shots x nbits, column j = clbit j. Returns (b0, b1) for pair i: qubit 0 and qubit 1."""
    return bools[:, 2 * i], bools[:, 2 * i + 1]


def success_matrix(kind, bools):
    """shots x npairs booleans: did pair i read its target in that shot?"""
    npairs = bools.shape[1] // 2
    cols = []
    for i in range(npairs):
        b0, b1 = pair_bits(bools, i)
        if kind == "floor":
            cols.append(~b0 & ~b1)
        elif kind == "transfer":
            cols.append(b0 & b1)
        elif kind == "in_step":
            cols.append(b0 ^ b1)
        else:  # out_of_step: success is NOT reading 01 or 10
            cols.append(~(b0 ^ b1))
    return np.stack(cols, axis=1)


def poisson_binomial(ps):
    dist = np.zeros(len(ps) + 1); dist[0] = 1.0
    for p in ps:
        dist[1:] = dist[1:] * (1 - p) + dist[:-1] * p
        dist[0] *= (1 - p)
    return dist


def analyse(kind, bools):
    ok = success_matrix(kind, bools)
    shots, npairs = ok.shape
    marg = ok.mean(axis=0)
    joint = float(ok.all(axis=1).mean())
    product = float(np.prod(marg))
    k = ok.sum(axis=1)
    any_k = np.bincount(k, minlength=npairs + 1) / shots
    out = {
        "marginals": [float(m) for m in marg],
        "mean": float(marg.mean()), "min": float(marg.min()), "max": float(marg.max()),
        "min_pair": int(marg.argmin()), "max_pair": int(marg.argmax()),
        "joint": joint, "product": product,
        "independence_gap": joint - product,
        "joint_standard_error": math.sqrt(max(joint * (1 - joint), 0) / shots),
        "any_k": [float(x) for x in any_k],
        "poisson_binomial": [float(x) for x in poisson_binomial(marg)],
    }
    if kind in ("in_step", "out_of_step"):
        # the per-pair number the kickoff reports: P(01) + P(10)
        odd = np.stack([pair_bits(bools, i)[0] ^ pair_bits(bools, i)[1] for i in range(npairs)], axis=1).mean(axis=0)
        out["P01_plus_P10"] = [float(x) for x in odd]
        out["P01_plus_P10_mean"] = float(odd.mean())
    if kind == "floor":
        out["floor_error"] = [float(1 - m) for m in marg]
        out["floor_error_mean"] = float(1 - marg.mean())
    if kind == "transfer":
        out["line_0_9815_pow_27"] = LINE_0_9815
    return out


def bools_from_counts(counts, nbits):
    rows, reps = [], []
    for s, c in counts.items():
        rows.append([s[-1 - j] == "1" for j in range(nbits)]); reps.append(c)
    return np.repeat(np.array(rows, dtype=bool), reps, axis=0)


# ----------------------------------------------------------------------------- simulators
def selfcheck():
    from qiskit.quantum_info import StabilizerState
    worst, lines = 0.0, []
    for kind in CIRCUITS:
        qc = build(kind)
        assert no_cross_pair_gates(qc), kind
        st = StabilizerState(qc.remove_final_measurements(inplace=False))
        target = {"floor": ["00"], "transfer": ["11"], "in_step": ["01", "10"], "out_of_step": ["00", "11"]}[kind]
        margs = []
        for i in range(NPAIRS):
            pd = st.probabilities_dict([2 * i, 2 * i + 1])   # key "q1q0"
            margs.append(sum(pd.get(t, 0.0) for t in target))
        margs = np.array(margs)
        # joint: pairs share no gate, so the state is a product over pairs and the joint is the product
        joint = float(np.prod(margs))
        if kind == "transfer":   # and check it directly: the one 54-bit string with every pair on 11
            joint_direct = st.probabilities_dict_from_bitstring("1" * (2 * NPAIRS))["1" * (2 * NPAIRS)]
            worst = max(worst, abs(joint_direct - 1))
        worst = max(worst, float(np.abs(margs - 1).max()), abs(joint - 1))
        oddmean = 1 - margs.mean() if kind == "out_of_step" else None
        lines.append(f"  {kind:<12} marginals min {margs.min():.12f}  joint {joint:.12f}" +
                     (f"  P(01)+P(10) mean {oddmean:.1e}" if oddmean is not None else ""))
    print("self-check, exact stabilizer simulation of the 54-qubit circuits:")
    print("\n".join(lines))
    print(f"  largest deviation from the ideal: {worst:.1e}")
    return worst < 1e-12


def run_ideal():
    from qiskit.quantum_info import StabilizerState
    rng_seed = 27
    res = {}
    for n, kind in enumerate(CIRCUITS):
        st = StabilizerState(build(kind).remove_final_measurements(inplace=False))
        st.seed(rng_seed + n)
        mem = st.sample_memory(SHOTS)            # strings, qubit 0 rightmost
        counts = {}
        for s in mem:
            counts[s] = counts.get(s, 0) + 1
        res[kind] = {"counts": counts, **analyse(kind, bools_from_counts(counts, 2 * NPAIRS))}
    return res


# ----------------------------------------------------------------------------- hardware
def service():
    from qiskit_ibm_runtime import QiskitRuntimeService
    return QiskitRuntimeService()


def choose_pairs(backend):
    t = backend.target
    twoq = next(g for g in ("cz", "ecr", "cx") if g in t.operation_names)
    one = "sx" if "sx" in t.operation_names else "x"
    err = lambda gate, qargs: (t[gate].get(qargs).error if t[gate].get(qargs) is not None and t[gate].get(qargs).error is not None else 1.0)
    edges = {}
    for qargs in t[twoq]:
        a, b = sorted(qargs)
        e = err(twoq, qargs)
        edges[(a, b)] = min(e, edges.get((a, b), 1.0))
    ro = lambda q: err("measure", (q,))
    ranked = sorted(edges, key=lambda ab: (edges[ab], ro(ab[0]) + ro(ab[1])))
    used, pairs = set(), []
    for a, b in ranked:
        if a in used or b in used or edges[(a, b)] >= 1.0:
            continue
        pairs.append((a, b)); used |= {a, b}
        if len(pairs) == NPAIRS:
            break
    if len(pairs) < NPAIRS:
        raise SystemExit(f"only {len(pairs)} disjoint coupled pairs with finite error on {backend.name}")
    rows = []
    for i, (a, b) in enumerate(pairs):
        rows.append({"pair": i, "qubits": [a, b], "two_qubit_gate": twoq, "two_qubit_error": edges[(a, b)],
                     "single_qubit_error": [err(one, (a,)), err(one, (b,))],
                     "readout_error": [ro(a), ro(b)]})
    return rows, twoq


def kickoff03_pair(svc):
    """Physical qubits Kickoff 03's square ran on (ibm_kingston, job daq3rdeekp0c73aq6aig), if retrievable."""
    try:
        job = svc.job("daq3rdeekp0c73aq6aig")
        pub = job.inputs["pubs"][0]
        qc = pub[0] if isinstance(pub, (tuple, list)) else pub.circuit
        phys = sorted({qc.find_bit(q).index for inst in qc.data if inst.operation.name == "measure" for q in inst.qubits})
        return {"backend": job.backend().name, "qubits": phys}
    except Exception as e:
        return {"error": f"{type(e).__name__}: {e}"}


def do_pairs(backend_name):
    svc = service()
    if backend_name:
        backend = svc.backend(backend_name)
    else:
        cands = [svc.backend(n) for n in MACHINES]
        backend = min(cands, key=lambda b: b.status().pending_jobs)
    rows, twoq = choose_pairs(backend)
    k03 = kickoff03_pair(svc)
    note = None
    if backend.name == "ibm_kingston" and "qubits" in k03:
        note = any(sorted(r["qubits"]) == sorted(k03["qubits"]) for r in rows)
    out = {"backend": backend.name, "selected_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
           "pending_jobs_at_selection": {n: svc.backend(n).status().pending_jobs for n in MACHINES},
           "calibration_last_update": str(getattr(backend.properties(), "last_update_date", None)),
           "rule": "greedy by lowest two-qubit gate error, ties by lowest summed readout error, no qubit in two pairs",
           "pairs": rows, "kickoff03_pair": k03, "kickoff03_pair_among_the_27": note}
    (HERE / "pairs.json").write_text(json.dumps(out, indent=1))
    e2 = [r["two_qubit_error"] for r in rows]; ro = [sum(r["readout_error"]) / 2 for r in rows]
    print(f"{backend.name}: 27 pairs chosen; two-qubit error {min(e2):.2e} to {max(e2):.2e}; "
          f"mean readout error per qubit {np.mean(ro):.4f} (max {max(max(r['readout_error']) for r in rows):.4f})")
    print("Kickoff 03's pair:", k03, "| among the 27:", note)


def run_hardware():
    from qiskit.transpiler import generate_preset_pass_manager
    from qiskit_ibm_runtime import SamplerV2
    sel = json.loads((HERE / "pairs.json").read_text())
    svc = service(); backend = svc.backend(sel["backend"])
    layout = [q for r in sel["pairs"] for q in r["qubits"]]
    pm = generate_preset_pass_manager(backend=backend, optimization_level=3, initial_layout=layout)
    circs = [build(k) for k in CIRCUITS]
    isa = [pm.run(c) for c in circs]
    info = {}
    for k, c in zip(CIRCUITS, isa):
        final = c.layout.final_index_layout() if c.layout is not None else None
        if final is not None and list(final[: 2 * NPAIRS]) != layout:
            raise SystemExit(f"{k}: the transpiler moved the pairs: {final[:6]}... vs {layout[:6]}...")
        ops = c.count_ops()
        info[k] = {"depth": c.depth(), "two_qubit_gates": int(sum(v for g, v in ops.items() if g in ("cz", "ecr", "cx"))),
                   "ops": {g: int(v) for g, v in ops.items()}}
    sampler = SamplerV2(mode=backend)
    sampler.options.default_shots = SHOTS
    sampler.options.dynamical_decoupling.enable = False
    sampler.options.twirling.enable_gates = False
    sampler.options.twirling.enable_measure = False
    opts = {"default_shots": SHOTS, "dynamical_decoupling.enable": False,
            "twirling.enable_gates": False, "twirling.enable_measure": False}
    t_sub = datetime.now(timezone.utc)
    job = sampler.run(isa)
    print("backend:", backend.name, "| job id:", job.job_id(), "| waiting")
    t0 = time.time(); res = job.result(); wall = time.time() - t0
    print(f"done in {wall:.0f} s")
    out = {}
    for n, k in enumerate(CIRCUITS):
        ba = res[n].data.c
        bools = ba.to_bool_array(order="little")         # column j = clbit j
        out[k] = {"counts": ba.get_counts(), **analyse(k, bools)}
    meta = {"backend": backend.name, "job_id": job.job_id(), "submitted_utc": t_sub.isoformat(timespec="seconds"),
            "wait_seconds": round(wall, 1), "shots": SHOTS, "sampler_options": opts, "transpiled": info,
            "layout": layout}
    try:
        meta["usage"] = job.metrics().get("usage"); meta["timestamps"] = job.metrics().get("timestamps")
    except Exception as e:
        meta["metrics_error"] = str(e)
    return out, meta


# ----------------------------------------------------------------------------- Variant B, the wire
T_FINAL = math.pi / 2
NGROUPS_TARGET = 27


def group_ops(qc, g, n):
    """Second-order Trotter on group g = (q0, q1, q2, q3) (circuit indices), n steps to t = pi/2."""
    from qiskit.circuit.library import XXPlusYYGate
    q0, q1, q2, q3 = g
    dt = T_FINAL / n
    ex = lambda a, b, tau: qc.append(XXPlusYYGate(-2 * tau), [a, b])
    for _ in range(n):
        ex(q0, q1, dt / 2); ex(q2, q3, dt / 2)        # A(dt/2)
        ex(q1, q2, dt); ex(q3, q0, dt)                # B(dt)
        ex(q0, q1, dt / 2); ex(q2, q3, dt / 2)        # A(dt/2)


def build108(kind, ngroups, n):
    """Group i is circuit qubits 4i..4i+3 = (q0, q1, q2, q3), measured into the same clbits."""
    from qiskit import QuantumCircuit
    qc = QuantumCircuit(4 * ngroups, 4 * ngroups, name=kind)
    for i in range(ngroups):
        g = tuple(range(4 * i, 4 * i + 4))
        qc.x(g[0])                                     # the particle on bead 1: |1000>
        if kind == "transfer":
            group_ops(qc, g, n)
    qc.measure(range(4 * ngroups), range(4 * ngroups))
    return qc


def ideal_group(n):
    """Exact probabilities on one group after n Trotter steps: P(|0010>), leakage, and the continuous-time value."""
    from qiskit import QuantumCircuit
    from qiskit.quantum_info import Statevector
    qc = QuantumCircuit(4); qc.x(0); group_ops(qc, (0, 1, 2, 3), n)
    probs = Statevector(qc).probabilities()           # index = sum q_j 2^j
    target = 1 << 2
    leak = sum(p for i, p in enumerate(probs) if bin(i).count("1") != 1)
    return float(probs[target]), float(leak)


def choose_n():
    scan = []
    for n in range(1, 13):
        p, leak = ideal_group(n)
        scan.append({"n": n, "ideal_transfer": p, "leakage": leak})
        if p > 0.99:
            return n, scan
    raise SystemExit("no n up to 12 gives ideal transfer above 0.99")


def analyse108(kind, bools):
    ng = bools.shape[1] // 4
    ok, leakc = [], []
    for i in range(ng):
        q = bools[:, 4 * i:4 * i + 4]
        weight = q.sum(axis=1)
        tgt = np.array([False, False, True, False]) if kind == "transfer" else np.array([True, False, False, False])
        ok.append((q == tgt).all(axis=1)); leakc.append(weight != 1)
    ok = np.stack(ok, axis=1); leak = np.stack(leakc, axis=1)
    marg = ok.mean(axis=0); shots = ok.shape[0]
    joint = float(ok.all(axis=1).mean()); product = float(np.prod(marg))
    k = ok.sum(axis=1)
    return {
        "marginals": [float(m) for m in marg], "mean": float(marg.mean()), "min": float(marg.min()), "max": float(marg.max()),
        "min_group": int(marg.argmin()), "max_group": int(marg.argmax()),
        "leakage": [float(x) for x in leak.mean(axis=0)], "leakage_mean": float(leak.mean()),
        "joint": joint, "product": product, "independence_gap": joint - product,
        "joint_standard_error": math.sqrt(max(joint * (1 - joint), 0) / shots),
        "any_k": [float(x) for x in np.bincount(k, minlength=ng + 1) / shots],
        "poisson_binomial": [float(x) for x in poisson_binomial(marg)],
    }


def choose_groups(backend):
    t = backend.target
    twoq = next(g for g in ("cz", "ecr", "cx") if g in t.operation_names)
    err = lambda gate, qargs: (t[gate].get(qargs).error if t[gate].get(qargs) is not None and t[gate].get(qargs).error is not None else 1.0)
    edge = {}
    for qargs in t[twoq]:
        a, b = sorted(qargs); edge[(a, b)] = min(err(twoq, qargs), edge.get((a, b), 1.0))
    nbr = {}
    for a, b in edge:
        nbr.setdefault(a, set()).add(b); nbr.setdefault(b, set()).add(a)
    E = lambda a, b: edge[tuple(sorted((a, b)))]
    paths = set()
    for a in nbr:
        for b in nbr[a]:
            for c in nbr[b] - {a}:
                for d in nbr[c] - {a, b}:
                    p = (a, b, c, d)
                    paths.add(min(p, p[::-1]))
    ro = lambda q: err("measure", (q,))
    ranked = sorted(paths, key=lambda p: (E(p[0], p[1]) + E(p[1], p[2]) + E(p[2], p[3]), sum(ro(q) for q in p)))
    used, groups = set(), []
    for p in ranked:
        if used & set(p) or max(E(p[0], p[1]), E(p[1], p[2]), E(p[2], p[3])) >= 1.0:
            continue
        groups.append(p); used |= set(p)
        if len(groups) == NGROUPS_TARGET:
            break
    rows = [{"group": i, "qubits": list(p), "path_edge_errors": [E(p[0], p[1]), E(p[1], p[2]), E(p[2], p[3])],
             "path_error_sum": E(p[0], p[1]) + E(p[1], p[2]) + E(p[2], p[3]), "readout_error": [ro(q) for q in p]}
            for i, p in enumerate(groups)]
    return rows, twoq, len(paths)


def do_groups():
    sel = json.loads((HERE / "pairs.json").read_text())
    svc = service(); backend = svc.backend(sel["backend"])
    rows, twoq, npaths = choose_groups(backend)
    out = {"backend": backend.name, "selected_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
           "calibration_last_update": str(getattr(backend.properties(), "last_update_date", None)),
           "rule": "greedy by lowest summed two-qubit error along the path q0-q1-q2-q3, ties by summed readout error, disjoint",
           "four_qubit_paths_on_chip": npaths, "groups_found": len(rows), "groups": rows}
    (HERE / "groups.json").write_text(json.dumps(out, indent=1))
    ps = [r["path_error_sum"] for r in rows]; ro = [x for r in rows for x in r["readout_error"]]
    print(f"{backend.name}: {len(rows)} disjoint four-qubit paths (of {npaths} on the chip); summed path error "
          f"{min(ps):.2e} to {max(ps):.2e}; readout per qubit mean {np.mean(ro):.4f}, max {max(ro):.4f}")


def isa108():
    from qiskit.transpiler import generate_preset_pass_manager
    grp = json.loads((HERE / "groups.json").read_text()); ideal = json.loads((HERE / "results108_ideal.json").read_text())
    svc = service(); backend = svc.backend(grp["backend"])
    ng, n = grp["groups_found"], ideal["n"]
    layout = [q for r in grp["groups"] for q in r["qubits"]]
    pm = generate_preset_pass_manager(backend=backend, optimization_level=3, initial_layout=layout, seed_transpiler=108)
    circs = {k: pm.run(build108(k, ng, n)) for k in ("transfer", "floor")}
    info, gset = {}, set(layout)
    for k, c in circs.items():
        ops = c.count_ops()
        touched = sorted({c.find_bit(q).index for inst in c.data for q in inst.qubits})
        cross = 0
        owner = {q: i for i, r in enumerate(grp["groups"]) for q in r["qubits"]}
        for inst in c.data:
            if inst.operation.num_qubits == 2:
                a, b = (c.find_bit(q).index for q in inst.qubits)
                if owner.get(a) != owner.get(b):
                    cross += 1
        info[k] = {"depth": c.depth(), "two_qubit_gates": int(sum(v for g, v in ops.items() if g in ("cz", "ecr", "cx"))),
                   "ops": {g: int(v) for g, v in ops.items()},
                   "physical_qubits_outside_groups": [q for q in touched if q not in gset],
                   "two_qubit_gates_between_groups_or_outside": cross}
    return backend, circs, info, layout, ng, n


def do_ideal108():
    n, scan = choose_n()
    p, leak = ideal_group(n)
    out = {"n": n, "t": T_FINAL, "ideal_transfer_per_group": p, "ideal_leakage_per_group": leak,
           "ideal_joint_27": p ** NGROUPS_TARGET, "scan": scan,
           "note": "groups are identical and share no gate, so the per-group statevector is exact and the joint is its 27th power"}
    (HERE / "results108_ideal.json").write_text(json.dumps(out, indent=1))
    print(f"n = {n}: ideal transfer per group {p:.6f}, leakage {leak:.1e}; scan " +
          ", ".join(f"n={r['n']}: {r['ideal_transfer']:.4f}" for r in scan))


def do_dryrun108():
    backend, circs, info, layout, ng, n = isa108()
    print(f"{backend.name}, {ng} groups, n = {n}")
    for k, v in info.items():
        print(f"  {k}: depth {v['depth']}, two-qubit gates {v['two_qubit_gates']} ({v['two_qubit_gates'] / ng:.1f} per group), "
              f"qubits outside the groups {v['physical_qubits_outside_groups']}, cross-group two-qubit gates {v['two_qubit_gates_between_groups_or_outside']}")
    return info


def do_hardware108():
    from qiskit_ibm_runtime import SamplerV2
    backend, circs, info, layout, ng, n = isa108()
    sampler = SamplerV2(mode=backend)
    sampler.options.default_shots = SHOTS
    sampler.options.dynamical_decoupling.enable = False
    sampler.options.twirling.enable_gates = False
    sampler.options.twirling.enable_measure = False
    t_sub = datetime.now(timezone.utc)
    job = sampler.run([circs["transfer"], circs["floor"]])
    print("backend:", backend.name, "| job id:", job.job_id(), "| waiting")
    t0 = time.time(); res = job.result(); wall = time.time() - t0
    print(f"done in {wall:.0f} s")
    out = {}
    for idx, k in enumerate(("transfer", "floor")):
        ba = res[idx].data.c
        out[k] = {"counts": ba.get_counts(), **analyse108(k, ba.to_bool_array(order="little"))}
    ideal = json.loads((HERE / "results108_ideal.json").read_text())
    meta = {"backend": backend.name, "job_id": job.job_id(), "submitted_utc": t_sub.isoformat(timespec="seconds"),
            "wait_seconds": round(wall, 1), "shots": SHOTS, "groups": ng, "trotter_steps": n,
            "ideal_transfer_per_group": ideal["ideal_transfer_per_group"], "transpiled": info, "layout": layout,
            "sampler_options": {"default_shots": SHOTS, "dynamical_decoupling.enable": False,
                                "twirling.enable_gates": False, "twirling.enable_measure": False}}
    try:
        meta["usage"] = job.metrics().get("usage"); meta["timestamps"] = job.metrics().get("timestamps")
    except Exception as e:
        meta["metrics_error"] = str(e)
    (HERE / "results108.json").write_text(json.dumps({"meta": meta, "circuits": out}, indent=1))
    tr, fl = out["transfer"], out["floor"]
    print(f"transfer: mean group {tr['mean']:.4f} (ideal {ideal['ideal_transfer_per_group']:.4f}), min {tr['min']:.4f} (group {tr['min_group']}), "
          f"max {tr['max']:.4f} (group {tr['max_group']}); joint_{ng} {tr['joint']:.4f} ± {tr['joint_standard_error']:.4f}, "
          f"product {tr['product']:.2e}; mean leakage {tr['leakage_mean']:.4f}")
    print(f"floor: mean P(1000) {fl['mean']:.4f}, mean leakage {fl['leakage_mean']:.4f}")
    try:
        import matplotlib; matplotlib.use("Agg"); import matplotlib.pyplot as plt
        S, T1, T2, BAR, LINE = "#fcfcfb", "#0b0b0b", "#52514e", "#2a78d6", "#eb6834"
        fig, ax = plt.subplots(figsize=(8, 4.6), facecolor=S); ax.set_facecolor(S)
        ks = np.arange(ng + 1)
        ax.bar(ks, tr["any_k"], color=BAR, width=0.8, label="measured")
        ax.plot(ks, tr["poisson_binomial"], "o-", color=LINE, lw=1.8, ms=4, label=f"independent failures (Poisson-binomial from the {ng} marginals)")
        ax.set_xlabel(f"groups that transferred in the same shot (of {ng})", color=T2); ax.set_ylabel("fraction of shots", color=T2)
        ax.set_title(f"The wire on {backend.name}: mean group transfer {tr['mean']:.3f}, all {ng} at once {tr['joint']:.4f}", loc="left", fontsize=12, color=T1, weight="bold")
        ax.legend(frameon=False, fontsize=9, labelcolor=T2, loc="upper left"); ax.tick_params(colors=T2)
        for sp in ("top", "right"): ax.spines[sp].set_visible(False)
        fig.text(0.01, -0.02, f"ideal Trotter transfer per group {ideal['ideal_transfer_per_group']:.4f} (n = {n}) · {SHOTS} shots", fontsize=9, color=T2)
        fig.savefig(HERE / "histogram108.png", dpi=130, facecolor=S, bbox_inches="tight")
    except Exception as e:
        print("plot skipped:", e)


# ----------------------------------------------------------------------------- report
def report(res, meta, stem):
    (HERE / f"{stem}.json").write_text(json.dumps({"meta": meta, "circuits": res}, indent=1))
    tr = res["transfer"]
    print(f"\ntransfer: joint_27 {tr['joint']:.4f} ± {tr['joint_standard_error']:.4f} | product_27 {tr['product']:.4f} | "
          f"gap {tr['independence_gap']:+.4f} | 0.9815^27 = {LINE_0_9815:.4f}")
    print(f"          marginals mean {tr['mean']:.4f}, min {tr['min']:.4f} (pair {tr['min_pair']}), max {tr['max']:.4f} (pair {tr['max_pair']})")
    for k in ("in_step", "out_of_step"):
        print(f"{k}: mean P(01)+P(10) {res[k]['P01_plus_P10_mean']:.4f} | joint {res[k]['joint']:.4f} vs product {res[k]['product']:.4f}")
    print(f"floor: mean error {res['floor']['floor_error_mean']:.4f}")
    try:
        import matplotlib; matplotlib.use("Agg"); import matplotlib.pyplot as plt
        S, T1, T2, BAR, LINE = "#fcfcfb", "#0b0b0b", "#52514e", "#2a78d6", "#eb6834"
        fig, ax = plt.subplots(figsize=(8, 4.6), facecolor=S); ax.set_facecolor(S)
        ks = np.arange(NPAIRS + 1)
        ax.bar(ks, tr["any_k"], color=BAR, width=0.8, label="measured")
        ax.plot(ks, tr["poisson_binomial"], "o-", color=LINE, lw=1.8, ms=4, label="independent failures (Poisson-binomial from the 27 marginals)")
        lo = max(0, min(int(np.nonzero(np.array(tr["any_k"]) > 0)[0].min()), NPAIRS - 8) - 1)
        ax.set_xlim(lo - 0.6, NPAIRS + 0.6)
        ax.set_xlabel("squares that flipped in the same shot (of 27)", color=T2); ax.set_ylabel("fraction of shots", color=T2)
        ax.set_title(f"27 squares at once on {meta['backend']}: all 27 flipped in {tr['joint']:.3f} of shots", loc="left", fontsize=12, color=T1, weight="bold")
        ax.legend(frameon=False, fontsize=9, labelcolor=T2, loc="upper left"); ax.tick_params(colors=T2)
        for s in ("top", "right"): ax.spines[s].set_visible(False)
        fig.text(0.01, -0.02, f"product of marginals {tr['product']:.3f} · 0.9815^27 = {LINE_0_9815:.3f} · {SHOTS} shots", fontsize=9, color=T2)
        fig.savefig(HERE / f"histogram27{'' if stem == 'results27' else '_ideal'}.png", dpi=130, facecolor=S, bbox_inches="tight")
    except Exception as e:
        print("plot skipped:", e)


if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    for f in ("selfcheck", "ideal", "pairs", "hardware", "ideal108", "groups", "dryrun108", "hardware108"):
        ap.add_argument(f"--{f}", action="store_true")
    ap.add_argument("--backend", default=None)
    a = ap.parse_args()
    if a.selfcheck or not (a.ideal or a.pairs or a.hardware or a.ideal108 or a.groups or a.dryrun108 or a.hardware108):
        sys.exit(0 if selfcheck() else 1)
    if a.ideal:
        res = run_ideal()
        report(res, {"backend": "stabilizer simulator", "shots": SHOTS, "seed": 27}, "results27_ideal")
    if a.pairs:
        do_pairs(a.backend)
    if a.hardware:
        res, meta = run_hardware()
        report(res, meta, "results27")
    if a.ideal108:
        do_ideal108()
    if a.groups:
        do_groups()
    if a.dryrun108:
        do_dryrun108()
    if a.hardware108:
        do_hardware108()
